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 * Returns the proper write/execute permission for a physical page that is
875 * part of the initial boot allocations.
877 * If the page has kernel text, it is marked as read-only. If the page has
878 * kernel read-only data, it is marked as read-only/not-executable. If the
879 * page has only read-write data, it is marked as read-write/not-executable.
880 * If the page is below/above the kernel range, it is marked as read-write.
882 * This function operates on 2M pages, since we map the kernel space that
885 * Note that this doesn't currently provide any protection for modules.
887 static inline pt_entry_t
888 bootaddr_rwx(vm_paddr_t pa)
892 * Everything in the same 2M page as the start of the kernel
893 * should be static. On the other hand, things in the same 2M
894 * page as the end of the kernel could be read-write/executable,
895 * as the kernel image is not guaranteed to end on a 2M boundary.
897 if (pa < trunc_2mpage(btext - KERNBASE) ||
898 pa >= trunc_2mpage(_end - KERNBASE))
901 * The linker should ensure that the read-only and read-write
902 * portions don't share the same 2M page, so this shouldn't
903 * impact read-only data. However, in any case, any page with
904 * read-write data needs to be read-write.
906 if (pa >= trunc_2mpage(brwsection - KERNBASE))
907 return (X86_PG_RW | pg_nx);
909 * Mark any 2M page containing kernel text as read-only. Mark
910 * other pages with read-only data as read-only and not executable.
911 * (It is likely a small portion of the read-only data section will
912 * be marked as read-only, but executable. This should be acceptable
913 * since the read-only protection will keep the data from changing.)
914 * Note that fixups to the .text section will still work until we
917 if (pa < round_2mpage(etext - KERNBASE))
923 create_pagetables(vm_paddr_t *firstaddr)
925 int i, j, ndm1g, nkpdpe, nkdmpde;
930 uint64_t DMPDkernphys;
932 /* Allocate page table pages for the direct map */
933 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
934 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
936 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
937 if (ndmpdpphys > NDMPML4E) {
939 * Each NDMPML4E allows 512 GB, so limit to that,
940 * and then readjust ndmpdp and ndmpdpphys.
942 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
943 Maxmem = atop(NDMPML4E * NBPML4);
944 ndmpdpphys = NDMPML4E;
945 ndmpdp = NDMPML4E * NPDEPG;
947 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
949 if ((amd_feature & AMDID_PAGE1GB) != 0) {
951 * Calculate the number of 1G pages that will fully fit in
954 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
957 * Allocate 2M pages for the kernel. These will be used in
958 * place of the first one or more 1G pages from ndm1g.
960 nkdmpde = howmany((vm_offset_t)(brwsection - KERNBASE), NBPDP);
961 DMPDkernphys = allocpages(firstaddr, nkdmpde);
964 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
965 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
968 KPML4phys = allocpages(firstaddr, 1);
969 KPDPphys = allocpages(firstaddr, NKPML4E);
972 * Allocate the initial number of kernel page table pages required to
973 * bootstrap. We defer this until after all memory-size dependent
974 * allocations are done (e.g. direct map), so that we don't have to
975 * build in too much slop in our estimate.
977 * Note that when NKPML4E > 1, we have an empty page underneath
978 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
979 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
981 nkpt_init(*firstaddr);
982 nkpdpe = NKPDPE(nkpt);
984 KPTphys = allocpages(firstaddr, nkpt);
985 KPDphys = allocpages(firstaddr, nkpdpe);
987 /* Fill in the underlying page table pages */
988 /* XXX not fully used, underneath 2M pages */
989 pt_p = (pt_entry_t *)KPTphys;
990 for (i = 0; ptoa(i) < *firstaddr; i++)
991 pt_p[i] = ptoa(i) | X86_PG_V | pg_g | bootaddr_rwx(ptoa(i));
993 /* Now map the page tables at their location within PTmap */
994 pd_p = (pd_entry_t *)KPDphys;
995 for (i = 0; i < nkpt; i++)
996 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
998 /* Map from zero to end of allocations under 2M pages */
999 /* This replaces some of the KPTphys entries above */
1000 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
1001 pd_p[i] = (i << PDRSHIFT) | X86_PG_V | PG_PS | pg_g |
1002 bootaddr_rwx(i << PDRSHIFT);
1005 * Because we map the physical blocks in 2M pages, adjust firstaddr
1006 * to record the physical blocks we've actually mapped into kernel
1007 * virtual address space.
1009 *firstaddr = round_2mpage(*firstaddr);
1011 /* And connect up the PD to the PDP (leaving room for L4 pages) */
1012 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
1013 for (i = 0; i < nkpdpe; i++)
1014 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
1018 * Now, set up the direct map region using 2MB and/or 1GB pages. If
1019 * the end of physical memory is not aligned to a 1GB page boundary,
1020 * then the residual physical memory is mapped with 2MB pages. Later,
1021 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
1022 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
1023 * that are partially used.
1025 pd_p = (pd_entry_t *)DMPDphys;
1026 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
1027 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
1028 /* Preset PG_M and PG_A because demotion expects it. */
1029 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1030 X86_PG_M | X86_PG_A | pg_nx;
1032 pdp_p = (pdp_entry_t *)DMPDPphys;
1033 for (i = 0; i < ndm1g; i++) {
1034 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
1035 /* Preset PG_M and PG_A because demotion expects it. */
1036 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1037 X86_PG_M | X86_PG_A | pg_nx;
1039 for (j = 0; i < ndmpdp; i++, j++) {
1040 pdp_p[i] = DMPDphys + ptoa(j);
1041 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_U;
1045 * Instead of using a 1G page for the memory containing the kernel,
1046 * use 2M pages with appropriate permissions. (If using 1G pages,
1047 * this will partially overwrite the PDPEs above.)
1050 pd_p = (pd_entry_t *)DMPDkernphys;
1051 for (i = 0; i < (NPDEPG * nkdmpde); i++)
1052 pd_p[i] = (i << PDRSHIFT) | X86_PG_V | PG_PS | pg_g |
1053 X86_PG_M | X86_PG_A | pg_nx |
1054 bootaddr_rwx(i << PDRSHIFT);
1055 for (i = 0; i < nkdmpde; i++)
1056 pdp_p[i] = (DMPDkernphys + ptoa(i)) | X86_PG_RW |
1060 /* And recursively map PML4 to itself in order to get PTmap */
1061 p4_p = (pml4_entry_t *)KPML4phys;
1062 p4_p[PML4PML4I] = KPML4phys;
1063 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | PG_U | pg_nx;
1065 /* Connect the Direct Map slot(s) up to the PML4. */
1066 for (i = 0; i < ndmpdpphys; i++) {
1067 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
1068 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | PG_U;
1071 /* Connect the KVA slots up to the PML4 */
1072 for (i = 0; i < NKPML4E; i++) {
1073 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
1074 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V | PG_U;
1079 * Bootstrap the system enough to run with virtual memory.
1081 * On amd64 this is called after mapping has already been enabled
1082 * and just syncs the pmap module with what has already been done.
1083 * [We can't call it easily with mapping off since the kernel is not
1084 * mapped with PA == VA, hence we would have to relocate every address
1085 * from the linked base (virtual) address "KERNBASE" to the actual
1086 * (physical) address starting relative to 0]
1089 pmap_bootstrap(vm_paddr_t *firstaddr)
1099 * Create an initial set of page tables to run the kernel in.
1101 create_pagetables(firstaddr);
1104 * Add a physical memory segment (vm_phys_seg) corresponding to the
1105 * preallocated kernel page table pages so that vm_page structures
1106 * representing these pages will be created. The vm_page structures
1107 * are required for promotion of the corresponding kernel virtual
1108 * addresses to superpage mappings.
1110 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1112 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
1114 virtual_end = VM_MAX_KERNEL_ADDRESS;
1117 /* XXX do %cr0 as well */
1118 load_cr4(rcr4() | CR4_PGE);
1119 load_cr3(KPML4phys);
1120 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1121 load_cr4(rcr4() | CR4_SMEP);
1124 * Initialize the kernel pmap (which is statically allocated).
1126 PMAP_LOCK_INIT(kernel_pmap);
1127 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1128 kernel_pmap->pm_cr3 = KPML4phys;
1129 kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
1130 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1131 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1132 kernel_pmap->pm_flags = pmap_flags;
1135 * Initialize the TLB invalidations generation number lock.
1137 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1140 * Reserve some special page table entries/VA space for temporary
1143 #define SYSMAP(c, p, v, n) \
1144 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1150 * Crashdump maps. The first page is reused as CMAP1 for the
1153 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1154 CADDR1 = crashdumpmap;
1159 * Initialize the PAT MSR.
1160 * pmap_init_pat() clears and sets CR4_PGE, which, as a
1161 * side-effect, invalidates stale PG_G TLB entries that might
1162 * have been created in our pre-boot environment.
1166 /* Initialize TLB Context Id. */
1167 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1168 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1169 /* Check for INVPCID support */
1170 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1172 for (i = 0; i < MAXCPU; i++) {
1173 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1174 kernel_pmap->pm_pcids[i].pm_gen = 1;
1176 PCPU_SET(pcid_next, PMAP_PCID_KERN + 1);
1177 PCPU_SET(pcid_gen, 1);
1179 * pcpu area for APs is zeroed during AP startup.
1180 * pc_pcid_next and pc_pcid_gen are initialized by AP
1181 * during pcpu setup.
1183 load_cr4(rcr4() | CR4_PCIDE);
1185 pmap_pcid_enabled = 0;
1190 * Setup the PAT MSR.
1195 int pat_table[PAT_INDEX_SIZE];
1200 /* Bail if this CPU doesn't implement PAT. */
1201 if ((cpu_feature & CPUID_PAT) == 0)
1204 /* Set default PAT index table. */
1205 for (i = 0; i < PAT_INDEX_SIZE; i++)
1207 pat_table[PAT_WRITE_BACK] = 0;
1208 pat_table[PAT_WRITE_THROUGH] = 1;
1209 pat_table[PAT_UNCACHEABLE] = 3;
1210 pat_table[PAT_WRITE_COMBINING] = 3;
1211 pat_table[PAT_WRITE_PROTECTED] = 3;
1212 pat_table[PAT_UNCACHED] = 3;
1214 /* Initialize default PAT entries. */
1215 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1216 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1217 PAT_VALUE(2, PAT_UNCACHED) |
1218 PAT_VALUE(3, PAT_UNCACHEABLE) |
1219 PAT_VALUE(4, PAT_WRITE_BACK) |
1220 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1221 PAT_VALUE(6, PAT_UNCACHED) |
1222 PAT_VALUE(7, PAT_UNCACHEABLE);
1226 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1227 * Program 5 and 6 as WP and WC.
1228 * Leave 4 and 7 as WB and UC.
1230 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1231 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1232 PAT_VALUE(6, PAT_WRITE_COMBINING);
1233 pat_table[PAT_UNCACHED] = 2;
1234 pat_table[PAT_WRITE_PROTECTED] = 5;
1235 pat_table[PAT_WRITE_COMBINING] = 6;
1238 * Just replace PAT Index 2 with WC instead of UC-.
1240 pat_msr &= ~PAT_MASK(2);
1241 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1242 pat_table[PAT_WRITE_COMBINING] = 2;
1247 load_cr4(cr4 & ~CR4_PGE);
1249 /* Disable caches (CD = 1, NW = 0). */
1251 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1253 /* Flushes caches and TLBs. */
1257 /* Update PAT and index table. */
1258 wrmsr(MSR_PAT, pat_msr);
1259 for (i = 0; i < PAT_INDEX_SIZE; i++)
1260 pat_index[i] = pat_table[i];
1262 /* Flush caches and TLBs again. */
1266 /* Restore caches and PGE. */
1272 * Initialize a vm_page's machine-dependent fields.
1275 pmap_page_init(vm_page_t m)
1278 TAILQ_INIT(&m->md.pv_list);
1279 m->md.pat_mode = PAT_WRITE_BACK;
1283 * Initialize the pmap module.
1284 * Called by vm_init, to initialize any structures that the pmap
1285 * system needs to map virtual memory.
1290 struct pmap_preinit_mapping *ppim;
1293 int error, i, pv_npg, ret, skz63;
1295 /* Detect bare-metal Skylake Server and Skylake-X. */
1296 if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
1297 CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
1299 * Skylake-X errata SKZ63. Processor May Hang When
1300 * Executing Code In an HLE Transaction Region between
1301 * 40000000H and 403FFFFFH.
1303 * Mark the pages in the range as preallocated. It
1304 * seems to be impossible to distinguish between
1305 * Skylake Server and Skylake X.
1308 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
1311 printf("SKZ63: skipping 4M RAM starting "
1312 "at physical 1G\n");
1313 for (i = 0; i < atop(0x400000); i++) {
1314 ret = vm_page_blacklist_add(0x40000000 +
1316 if (!ret && bootverbose)
1317 printf("page at %#lx already used\n",
1318 0x40000000 + ptoa(i));
1324 * Initialize the vm page array entries for the kernel pmap's
1327 for (i = 0; i < nkpt; i++) {
1328 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1329 KASSERT(mpte >= vm_page_array &&
1330 mpte < &vm_page_array[vm_page_array_size],
1331 ("pmap_init: page table page is out of range"));
1332 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1333 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1334 mpte->wire_count = 1;
1339 * If the kernel is running on a virtual machine, then it must assume
1340 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1341 * be prepared for the hypervisor changing the vendor and family that
1342 * are reported by CPUID. Consequently, the workaround for AMD Family
1343 * 10h Erratum 383 is enabled if the processor's feature set does not
1344 * include at least one feature that is only supported by older Intel
1345 * or newer AMD processors.
1347 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1348 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1349 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1351 workaround_erratum383 = 1;
1354 * Are large page mappings enabled?
1356 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1357 if (pg_ps_enabled) {
1358 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1359 ("pmap_init: can't assign to pagesizes[1]"));
1360 pagesizes[1] = NBPDR;
1364 * Initialize the pv chunk list mutex.
1366 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1369 * Initialize the pool of pv list locks.
1371 for (i = 0; i < NPV_LIST_LOCKS; i++)
1372 rw_init(&pv_list_locks[i], "pmap pv list");
1375 * Calculate the size of the pv head table for superpages.
1377 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1380 * Allocate memory for the pv head table for superpages.
1382 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1384 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1386 for (i = 0; i < pv_npg; i++)
1387 TAILQ_INIT(&pv_table[i].pv_list);
1388 TAILQ_INIT(&pv_dummy.pv_list);
1390 pmap_initialized = 1;
1391 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1392 ppim = pmap_preinit_mapping + i;
1395 /* Make the direct map consistent */
1396 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1397 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1398 ppim->sz, ppim->mode);
1402 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1403 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1406 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1407 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1408 (vmem_addr_t *)&qframe);
1410 panic("qframe allocation failed");
1413 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1414 "2MB page mapping counters");
1416 static u_long pmap_pde_demotions;
1417 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1418 &pmap_pde_demotions, 0, "2MB page demotions");
1420 static u_long pmap_pde_mappings;
1421 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1422 &pmap_pde_mappings, 0, "2MB page mappings");
1424 static u_long pmap_pde_p_failures;
1425 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1426 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1428 static u_long pmap_pde_promotions;
1429 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1430 &pmap_pde_promotions, 0, "2MB page promotions");
1432 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1433 "1GB page mapping counters");
1435 static u_long pmap_pdpe_demotions;
1436 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1437 &pmap_pdpe_demotions, 0, "1GB page demotions");
1439 /***************************************************
1440 * Low level helper routines.....
1441 ***************************************************/
1444 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1446 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1448 switch (pmap->pm_type) {
1451 /* Verify that both PAT bits are not set at the same time */
1452 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1453 ("Invalid PAT bits in entry %#lx", entry));
1455 /* Swap the PAT bits if one of them is set */
1456 if ((entry & x86_pat_bits) != 0)
1457 entry ^= x86_pat_bits;
1461 * Nothing to do - the memory attributes are represented
1462 * the same way for regular pages and superpages.
1466 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1473 * Determine the appropriate bits to set in a PTE or PDE for a specified
1477 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1479 int cache_bits, pat_flag, pat_idx;
1481 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1482 panic("Unknown caching mode %d\n", mode);
1484 switch (pmap->pm_type) {
1487 /* The PAT bit is different for PTE's and PDE's. */
1488 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1490 /* Map the caching mode to a PAT index. */
1491 pat_idx = pat_index[mode];
1493 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1496 cache_bits |= pat_flag;
1498 cache_bits |= PG_NC_PCD;
1500 cache_bits |= PG_NC_PWT;
1504 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1508 panic("unsupported pmap type %d", pmap->pm_type);
1511 return (cache_bits);
1515 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1519 switch (pmap->pm_type) {
1522 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1525 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1528 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1535 pmap_ps_enabled(pmap_t pmap)
1538 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1542 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1545 switch (pmap->pm_type) {
1552 * This is a little bogus since the generation number is
1553 * supposed to be bumped up when a region of the address
1554 * space is invalidated in the page tables.
1556 * In this case the old PDE entry is valid but yet we want
1557 * to make sure that any mappings using the old entry are
1558 * invalidated in the TLB.
1560 * The reason this works as expected is because we rendezvous
1561 * "all" host cpus and force any vcpu context to exit as a
1564 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1567 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1569 pde_store(pde, newpde);
1573 * After changing the page size for the specified virtual address in the page
1574 * table, flush the corresponding entries from the processor's TLB. Only the
1575 * calling processor's TLB is affected.
1577 * The calling thread must be pinned to a processor.
1580 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1584 if (pmap_type_guest(pmap))
1587 KASSERT(pmap->pm_type == PT_X86,
1588 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1590 PG_G = pmap_global_bit(pmap);
1592 if ((newpde & PG_PS) == 0)
1593 /* Demotion: flush a specific 2MB page mapping. */
1595 else if ((newpde & PG_G) == 0)
1597 * Promotion: flush every 4KB page mapping from the TLB
1598 * because there are too many to flush individually.
1603 * Promotion: flush every 4KB page mapping from the TLB,
1604 * including any global (PG_G) mappings.
1612 * For SMP, these functions have to use the IPI mechanism for coherence.
1614 * N.B.: Before calling any of the following TLB invalidation functions,
1615 * the calling processor must ensure that all stores updating a non-
1616 * kernel page table are globally performed. Otherwise, another
1617 * processor could cache an old, pre-update entry without being
1618 * invalidated. This can happen one of two ways: (1) The pmap becomes
1619 * active on another processor after its pm_active field is checked by
1620 * one of the following functions but before a store updating the page
1621 * table is globally performed. (2) The pmap becomes active on another
1622 * processor before its pm_active field is checked but due to
1623 * speculative loads one of the following functions stills reads the
1624 * pmap as inactive on the other processor.
1626 * The kernel page table is exempt because its pm_active field is
1627 * immutable. The kernel page table is always active on every
1632 * Interrupt the cpus that are executing in the guest context.
1633 * This will force the vcpu to exit and the cached EPT mappings
1634 * will be invalidated by the host before the next vmresume.
1636 static __inline void
1637 pmap_invalidate_ept(pmap_t pmap)
1642 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1643 ("pmap_invalidate_ept: absurd pm_active"));
1646 * The TLB mappings associated with a vcpu context are not
1647 * flushed each time a different vcpu is chosen to execute.
1649 * This is in contrast with a process's vtop mappings that
1650 * are flushed from the TLB on each context switch.
1652 * Therefore we need to do more than just a TLB shootdown on
1653 * the active cpus in 'pmap->pm_active'. To do this we keep
1654 * track of the number of invalidations performed on this pmap.
1656 * Each vcpu keeps a cache of this counter and compares it
1657 * just before a vmresume. If the counter is out-of-date an
1658 * invept will be done to flush stale mappings from the TLB.
1660 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1663 * Force the vcpu to exit and trap back into the hypervisor.
1665 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1666 ipi_selected(pmap->pm_active, ipinum);
1671 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1674 struct invpcid_descr d;
1675 uint64_t kcr3, ucr3;
1679 if (pmap_type_guest(pmap)) {
1680 pmap_invalidate_ept(pmap);
1684 KASSERT(pmap->pm_type == PT_X86,
1685 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1688 if (pmap == kernel_pmap) {
1692 cpuid = PCPU_GET(cpuid);
1693 if (pmap == PCPU_GET(curpmap)) {
1695 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1697 * Disable context switching. pm_pcid
1698 * is recalculated on switch, which
1699 * might make us use wrong pcid below.
1702 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1704 if (invpcid_works) {
1705 d.pcid = pcid | PMAP_PCID_USER_PT;
1708 invpcid(&d, INVPCID_ADDR);
1710 kcr3 = pmap->pm_cr3 | pcid |
1712 ucr3 = pmap->pm_ucr3 | pcid |
1713 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1714 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1718 } else if (pmap_pcid_enabled)
1719 pmap->pm_pcids[cpuid].pm_gen = 0;
1720 if (pmap_pcid_enabled) {
1723 pmap->pm_pcids[i].pm_gen = 0;
1726 mask = &pmap->pm_active;
1728 smp_masked_invlpg(*mask, va, pmap);
1732 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1733 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1736 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1739 struct invpcid_descr d;
1741 uint64_t kcr3, ucr3;
1745 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1746 pmap_invalidate_all(pmap);
1750 if (pmap_type_guest(pmap)) {
1751 pmap_invalidate_ept(pmap);
1755 KASSERT(pmap->pm_type == PT_X86,
1756 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1759 cpuid = PCPU_GET(cpuid);
1760 if (pmap == kernel_pmap) {
1761 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1765 if (pmap == PCPU_GET(curpmap)) {
1766 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1768 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1770 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1771 if (invpcid_works) {
1772 d.pcid = pcid | PMAP_PCID_USER_PT;
1775 for (; d.addr < eva; d.addr +=
1777 invpcid(&d, INVPCID_ADDR);
1779 kcr3 = pmap->pm_cr3 | pcid |
1781 ucr3 = pmap->pm_ucr3 | pcid |
1782 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1783 pmap_pti_pcid_invlrng(ucr3, kcr3, sva,
1788 } else if (pmap_pcid_enabled) {
1789 pmap->pm_pcids[cpuid].pm_gen = 0;
1791 if (pmap_pcid_enabled) {
1794 pmap->pm_pcids[i].pm_gen = 0;
1797 mask = &pmap->pm_active;
1799 smp_masked_invlpg_range(*mask, sva, eva, pmap);
1804 pmap_invalidate_all(pmap_t pmap)
1807 struct invpcid_descr d;
1808 uint64_t kcr3, ucr3;
1812 if (pmap_type_guest(pmap)) {
1813 pmap_invalidate_ept(pmap);
1817 KASSERT(pmap->pm_type == PT_X86,
1818 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1821 if (pmap == kernel_pmap) {
1822 if (pmap_pcid_enabled && invpcid_works) {
1823 bzero(&d, sizeof(d));
1824 invpcid(&d, INVPCID_CTXGLOB);
1830 cpuid = PCPU_GET(cpuid);
1831 if (pmap == PCPU_GET(curpmap)) {
1832 if (pmap_pcid_enabled) {
1834 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1835 if (invpcid_works) {
1839 invpcid(&d, INVPCID_CTX);
1840 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1841 d.pcid |= PMAP_PCID_USER_PT;
1842 invpcid(&d, INVPCID_CTX);
1845 kcr3 = pmap->pm_cr3 | pcid;
1846 ucr3 = pmap->pm_ucr3;
1847 if (ucr3 != PMAP_NO_CR3) {
1848 ucr3 |= pcid | PMAP_PCID_USER_PT;
1849 pmap_pti_pcid_invalidate(ucr3,
1859 } else if (pmap_pcid_enabled) {
1860 pmap->pm_pcids[cpuid].pm_gen = 0;
1862 if (pmap_pcid_enabled) {
1865 pmap->pm_pcids[i].pm_gen = 0;
1868 mask = &pmap->pm_active;
1870 smp_masked_invltlb(*mask, pmap);
1875 pmap_invalidate_cache(void)
1885 cpuset_t invalidate; /* processors that invalidate their TLB */
1890 u_int store; /* processor that updates the PDE */
1894 pmap_update_pde_action(void *arg)
1896 struct pde_action *act = arg;
1898 if (act->store == PCPU_GET(cpuid))
1899 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1903 pmap_update_pde_teardown(void *arg)
1905 struct pde_action *act = arg;
1907 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1908 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1912 * Change the page size for the specified virtual address in a way that
1913 * prevents any possibility of the TLB ever having two entries that map the
1914 * same virtual address using different page sizes. This is the recommended
1915 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1916 * machine check exception for a TLB state that is improperly diagnosed as a
1920 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1922 struct pde_action act;
1923 cpuset_t active, other_cpus;
1927 cpuid = PCPU_GET(cpuid);
1928 other_cpus = all_cpus;
1929 CPU_CLR(cpuid, &other_cpus);
1930 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1933 active = pmap->pm_active;
1935 if (CPU_OVERLAP(&active, &other_cpus)) {
1937 act.invalidate = active;
1941 act.newpde = newpde;
1942 CPU_SET(cpuid, &active);
1943 smp_rendezvous_cpus(active,
1944 smp_no_rendezvous_barrier, pmap_update_pde_action,
1945 pmap_update_pde_teardown, &act);
1947 pmap_update_pde_store(pmap, pde, newpde);
1948 if (CPU_ISSET(cpuid, &active))
1949 pmap_update_pde_invalidate(pmap, va, newpde);
1955 * Normal, non-SMP, invalidation functions.
1958 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1960 struct invpcid_descr d;
1961 uint64_t kcr3, ucr3;
1964 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1968 KASSERT(pmap->pm_type == PT_X86,
1969 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1971 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1973 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
1974 pmap->pm_ucr3 != PMAP_NO_CR3) {
1976 pcid = pmap->pm_pcids[0].pm_pcid;
1977 if (invpcid_works) {
1978 d.pcid = pcid | PMAP_PCID_USER_PT;
1981 invpcid(&d, INVPCID_ADDR);
1983 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
1984 ucr3 = pmap->pm_ucr3 | pcid |
1985 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1986 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1990 } else if (pmap_pcid_enabled)
1991 pmap->pm_pcids[0].pm_gen = 0;
1995 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1997 struct invpcid_descr d;
1999 uint64_t kcr3, ucr3;
2001 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
2005 KASSERT(pmap->pm_type == PT_X86,
2006 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
2008 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
2009 for (addr = sva; addr < eva; addr += PAGE_SIZE)
2011 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
2012 pmap->pm_ucr3 != PMAP_NO_CR3) {
2014 if (invpcid_works) {
2015 d.pcid = pmap->pm_pcids[0].pm_pcid |
2019 for (; d.addr < eva; d.addr += PAGE_SIZE)
2020 invpcid(&d, INVPCID_ADDR);
2022 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].
2023 pm_pcid | CR3_PCID_SAVE;
2024 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[0].
2025 pm_pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
2026 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
2030 } else if (pmap_pcid_enabled) {
2031 pmap->pm_pcids[0].pm_gen = 0;
2036 pmap_invalidate_all(pmap_t pmap)
2038 struct invpcid_descr d;
2039 uint64_t kcr3, ucr3;
2041 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
2045 KASSERT(pmap->pm_type == PT_X86,
2046 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
2048 if (pmap == kernel_pmap) {
2049 if (pmap_pcid_enabled && invpcid_works) {
2050 bzero(&d, sizeof(d));
2051 invpcid(&d, INVPCID_CTXGLOB);
2055 } else if (pmap == PCPU_GET(curpmap)) {
2056 if (pmap_pcid_enabled) {
2058 if (invpcid_works) {
2059 d.pcid = pmap->pm_pcids[0].pm_pcid;
2062 invpcid(&d, INVPCID_CTX);
2063 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2064 d.pcid |= PMAP_PCID_USER_PT;
2065 invpcid(&d, INVPCID_CTX);
2068 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].pm_pcid;
2069 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2070 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[
2071 0].pm_pcid | PMAP_PCID_USER_PT;
2072 pmap_pti_pcid_invalidate(ucr3, kcr3);
2080 } else if (pmap_pcid_enabled) {
2081 pmap->pm_pcids[0].pm_gen = 0;
2086 pmap_invalidate_cache(void)
2093 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
2096 pmap_update_pde_store(pmap, pde, newpde);
2097 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
2098 pmap_update_pde_invalidate(pmap, va, newpde);
2100 pmap->pm_pcids[0].pm_gen = 0;
2105 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
2109 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
2110 * by a promotion that did not invalidate the 512 4KB page mappings
2111 * that might exist in the TLB. Consequently, at this point, the TLB
2112 * may hold both 4KB and 2MB page mappings for the address range [va,
2113 * va + NBPDR). Therefore, the entire range must be invalidated here.
2114 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
2115 * 4KB page mappings for the address range [va, va + NBPDR), and so a
2116 * single INVLPG suffices to invalidate the 2MB page mapping from the
2119 if ((pde & PG_PROMOTED) != 0)
2120 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
2122 pmap_invalidate_page(pmap, va);
2125 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
2128 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
2132 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
2134 KASSERT((sva & PAGE_MASK) == 0,
2135 ("pmap_invalidate_cache_range: sva not page-aligned"));
2136 KASSERT((eva & PAGE_MASK) == 0,
2137 ("pmap_invalidate_cache_range: eva not page-aligned"));
2140 if ((cpu_feature & CPUID_SS) != 0 && !force)
2141 ; /* If "Self Snoop" is supported and allowed, do nothing. */
2142 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
2143 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2145 * XXX: Some CPUs fault, hang, or trash the local APIC
2146 * registers if we use CLFLUSH on the local APIC
2147 * range. The local APIC is always uncached, so we
2148 * don't need to flush for that range anyway.
2150 if (pmap_kextract(sva) == lapic_paddr)
2154 * Otherwise, do per-cache line flush. Use the sfence
2155 * instruction to insure that previous stores are
2156 * included in the write-back. The processor
2157 * propagates flush to other processors in the cache
2161 for (; sva < eva; sva += cpu_clflush_line_size)
2164 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
2165 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2166 if (pmap_kextract(sva) == lapic_paddr)
2169 * Writes are ordered by CLFLUSH on Intel CPUs.
2171 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2173 for (; sva < eva; sva += cpu_clflush_line_size)
2175 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2180 * No targeted cache flush methods are supported by CPU,
2181 * or the supplied range is bigger than 2MB.
2182 * Globally invalidate cache.
2184 pmap_invalidate_cache();
2189 * Remove the specified set of pages from the data and instruction caches.
2191 * In contrast to pmap_invalidate_cache_range(), this function does not
2192 * rely on the CPU's self-snoop feature, because it is intended for use
2193 * when moving pages into a different cache domain.
2196 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
2198 vm_offset_t daddr, eva;
2202 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
2203 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
2204 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
2205 pmap_invalidate_cache();
2209 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2211 for (i = 0; i < count; i++) {
2212 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
2213 eva = daddr + PAGE_SIZE;
2214 for (; daddr < eva; daddr += cpu_clflush_line_size) {
2223 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2229 * Routine: pmap_extract
2231 * Extract the physical page address associated
2232 * with the given map/virtual_address pair.
2235 pmap_extract(pmap_t pmap, vm_offset_t va)
2239 pt_entry_t *pte, PG_V;
2243 PG_V = pmap_valid_bit(pmap);
2245 pdpe = pmap_pdpe(pmap, va);
2246 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2247 if ((*pdpe & PG_PS) != 0)
2248 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
2250 pde = pmap_pdpe_to_pde(pdpe, va);
2251 if ((*pde & PG_V) != 0) {
2252 if ((*pde & PG_PS) != 0) {
2253 pa = (*pde & PG_PS_FRAME) |
2256 pte = pmap_pde_to_pte(pde, va);
2257 pa = (*pte & PG_FRAME) |
2268 * Routine: pmap_extract_and_hold
2270 * Atomically extract and hold the physical page
2271 * with the given pmap and virtual address pair
2272 * if that mapping permits the given protection.
2275 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
2277 pd_entry_t pde, *pdep;
2278 pt_entry_t pte, PG_RW, PG_V;
2284 PG_RW = pmap_rw_bit(pmap);
2285 PG_V = pmap_valid_bit(pmap);
2288 pdep = pmap_pde(pmap, va);
2289 if (pdep != NULL && (pde = *pdep)) {
2291 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2292 if (vm_page_pa_tryrelock(pmap, (pde &
2293 PG_PS_FRAME) | (va & PDRMASK), &pa))
2295 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
2300 pte = *pmap_pde_to_pte(pdep, va);
2302 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2303 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2306 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
2317 pmap_kextract(vm_offset_t va)
2322 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2323 pa = DMAP_TO_PHYS(va);
2327 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2330 * Beware of a concurrent promotion that changes the
2331 * PDE at this point! For example, vtopte() must not
2332 * be used to access the PTE because it would use the
2333 * new PDE. It is, however, safe to use the old PDE
2334 * because the page table page is preserved by the
2337 pa = *pmap_pde_to_pte(&pde, va);
2338 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2344 /***************************************************
2345 * Low level mapping routines.....
2346 ***************************************************/
2349 * Add a wired page to the kva.
2350 * Note: not SMP coherent.
2353 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2358 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g);
2361 static __inline void
2362 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2368 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2369 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | cache_bits);
2373 * Remove a page from the kernel pagetables.
2374 * Note: not SMP coherent.
2377 pmap_kremove(vm_offset_t va)
2386 * Used to map a range of physical addresses into kernel
2387 * virtual address space.
2389 * The value passed in '*virt' is a suggested virtual address for
2390 * the mapping. Architectures which can support a direct-mapped
2391 * physical to virtual region can return the appropriate address
2392 * within that region, leaving '*virt' unchanged. Other
2393 * architectures should map the pages starting at '*virt' and
2394 * update '*virt' with the first usable address after the mapped
2398 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2400 return PHYS_TO_DMAP(start);
2405 * Add a list of wired pages to the kva
2406 * this routine is only used for temporary
2407 * kernel mappings that do not need to have
2408 * page modification or references recorded.
2409 * Note that old mappings are simply written
2410 * over. The page *must* be wired.
2411 * Note: SMP coherent. Uses a ranged shootdown IPI.
2414 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2416 pt_entry_t *endpte, oldpte, pa, *pte;
2422 endpte = pte + count;
2423 while (pte < endpte) {
2425 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2426 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2427 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2429 pte_store(pte, pa | pg_g | pg_nx | X86_PG_RW | X86_PG_V);
2433 if (__predict_false((oldpte & X86_PG_V) != 0))
2434 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2439 * This routine tears out page mappings from the
2440 * kernel -- it is meant only for temporary mappings.
2441 * Note: SMP coherent. Uses a ranged shootdown IPI.
2444 pmap_qremove(vm_offset_t sva, int count)
2449 while (count-- > 0) {
2450 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2454 pmap_invalidate_range(kernel_pmap, sva, va);
2457 /***************************************************
2458 * Page table page management routines.....
2459 ***************************************************/
2461 * Schedule the specified unused page table page to be freed. Specifically,
2462 * add the page to the specified list of pages that will be released to the
2463 * physical memory manager after the TLB has been updated.
2465 static __inline void
2466 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2467 boolean_t set_PG_ZERO)
2471 m->flags |= PG_ZERO;
2473 m->flags &= ~PG_ZERO;
2474 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2478 * Inserts the specified page table page into the specified pmap's collection
2479 * of idle page table pages. Each of a pmap's page table pages is responsible
2480 * for mapping a distinct range of virtual addresses. The pmap's collection is
2481 * ordered by this virtual address range.
2484 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2487 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2488 return (vm_radix_insert(&pmap->pm_root, mpte));
2492 * Removes the page table page mapping the specified virtual address from the
2493 * specified pmap's collection of idle page table pages, and returns it.
2494 * Otherwise, returns NULL if there is no page table page corresponding to the
2495 * specified virtual address.
2497 static __inline vm_page_t
2498 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
2501 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2502 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
2506 * Decrements a page table page's wire count, which is used to record the
2507 * number of valid page table entries within the page. If the wire count
2508 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2509 * page table page was unmapped and FALSE otherwise.
2511 static inline boolean_t
2512 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2516 if (m->wire_count == 0) {
2517 _pmap_unwire_ptp(pmap, va, m, free);
2524 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2527 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2529 * unmap the page table page
2531 if (m->pindex >= (NUPDE + NUPDPE)) {
2534 pml4 = pmap_pml4e(pmap, va);
2536 if (pmap->pm_pml4u != NULL && va <= VM_MAXUSER_ADDRESS) {
2537 pml4 = &pmap->pm_pml4u[pmap_pml4e_index(va)];
2540 } else if (m->pindex >= NUPDE) {
2543 pdp = pmap_pdpe(pmap, va);
2548 pd = pmap_pde(pmap, va);
2551 pmap_resident_count_dec(pmap, 1);
2552 if (m->pindex < NUPDE) {
2553 /* We just released a PT, unhold the matching PD */
2556 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2557 pmap_unwire_ptp(pmap, va, pdpg, free);
2559 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2560 /* We just released a PD, unhold the matching PDP */
2563 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2564 pmap_unwire_ptp(pmap, va, pdppg, free);
2568 * Put page on a list so that it is released after
2569 * *ALL* TLB shootdown is done
2571 pmap_add_delayed_free_list(m, free, TRUE);
2575 * After removing a page table entry, this routine is used to
2576 * conditionally free the page, and manage the hold/wire counts.
2579 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2580 struct spglist *free)
2584 if (va >= VM_MAXUSER_ADDRESS)
2586 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2587 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2588 return (pmap_unwire_ptp(pmap, va, mpte, free));
2592 pmap_pinit0(pmap_t pmap)
2596 PMAP_LOCK_INIT(pmap);
2597 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2598 pmap->pm_pml4u = NULL;
2599 pmap->pm_cr3 = KPML4phys;
2600 /* hack to keep pmap_pti_pcid_invalidate() alive */
2601 pmap->pm_ucr3 = PMAP_NO_CR3;
2602 pmap->pm_root.rt_root = 0;
2603 CPU_ZERO(&pmap->pm_active);
2604 TAILQ_INIT(&pmap->pm_pvchunk);
2605 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2606 pmap->pm_flags = pmap_flags;
2608 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2609 pmap->pm_pcids[i].pm_gen = 0;
2611 __pcpu[i].pc_kcr3 = PMAP_NO_CR3;
2613 PCPU_SET(curpmap, kernel_pmap);
2614 pmap_activate(curthread);
2615 CPU_FILL(&kernel_pmap->pm_active);
2619 pmap_pinit_pml4(vm_page_t pml4pg)
2621 pml4_entry_t *pm_pml4;
2624 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2626 /* Wire in kernel global address entries. */
2627 for (i = 0; i < NKPML4E; i++) {
2628 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2631 for (i = 0; i < ndmpdpphys; i++) {
2632 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2636 /* install self-referential address mapping entry(s) */
2637 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2638 X86_PG_A | X86_PG_M;
2642 pmap_pinit_pml4_pti(vm_page_t pml4pg)
2644 pml4_entry_t *pm_pml4;
2647 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2648 for (i = 0; i < NPML4EPG; i++)
2649 pm_pml4[i] = pti_pml4[i];
2653 * Initialize a preallocated and zeroed pmap structure,
2654 * such as one in a vmspace structure.
2657 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2659 vm_page_t pml4pg, pml4pgu;
2660 vm_paddr_t pml4phys;
2664 * allocate the page directory page
2666 pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
2667 VM_ALLOC_WIRED | VM_ALLOC_ZERO | VM_ALLOC_WAITOK);
2669 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2670 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2672 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2673 pmap->pm_pcids[i].pm_gen = 0;
2675 pmap->pm_cr3 = PMAP_NO_CR3; /* initialize to an invalid value */
2676 pmap->pm_ucr3 = PMAP_NO_CR3;
2677 pmap->pm_pml4u = NULL;
2679 pmap->pm_type = pm_type;
2680 if ((pml4pg->flags & PG_ZERO) == 0)
2681 pagezero(pmap->pm_pml4);
2684 * Do not install the host kernel mappings in the nested page
2685 * tables. These mappings are meaningless in the guest physical
2687 * Install minimal kernel mappings in PTI case.
2689 if (pm_type == PT_X86) {
2690 pmap->pm_cr3 = pml4phys;
2691 pmap_pinit_pml4(pml4pg);
2693 pml4pgu = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2694 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2695 pmap->pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(
2696 VM_PAGE_TO_PHYS(pml4pgu));
2697 pmap_pinit_pml4_pti(pml4pgu);
2698 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pml4pgu);
2702 pmap->pm_root.rt_root = 0;
2703 CPU_ZERO(&pmap->pm_active);
2704 TAILQ_INIT(&pmap->pm_pvchunk);
2705 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2706 pmap->pm_flags = flags;
2707 pmap->pm_eptgen = 0;
2713 pmap_pinit(pmap_t pmap)
2716 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2720 * This routine is called if the desired page table page does not exist.
2722 * If page table page allocation fails, this routine may sleep before
2723 * returning NULL. It sleeps only if a lock pointer was given.
2725 * Note: If a page allocation fails at page table level two or three,
2726 * one or two pages may be held during the wait, only to be released
2727 * afterwards. This conservative approach is easily argued to avoid
2731 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2733 vm_page_t m, pdppg, pdpg;
2734 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2736 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2738 PG_A = pmap_accessed_bit(pmap);
2739 PG_M = pmap_modified_bit(pmap);
2740 PG_V = pmap_valid_bit(pmap);
2741 PG_RW = pmap_rw_bit(pmap);
2744 * Allocate a page table page.
2746 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2747 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2748 if (lockp != NULL) {
2749 RELEASE_PV_LIST_LOCK(lockp);
2751 PMAP_ASSERT_NOT_IN_DI();
2757 * Indicate the need to retry. While waiting, the page table
2758 * page may have been allocated.
2762 if ((m->flags & PG_ZERO) == 0)
2766 * Map the pagetable page into the process address space, if
2767 * it isn't already there.
2770 if (ptepindex >= (NUPDE + NUPDPE)) {
2771 pml4_entry_t *pml4, *pml4u;
2772 vm_pindex_t pml4index;
2774 /* Wire up a new PDPE page */
2775 pml4index = ptepindex - (NUPDE + NUPDPE);
2776 pml4 = &pmap->pm_pml4[pml4index];
2777 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2778 if (pmap->pm_pml4u != NULL && pml4index < NUPML4E) {
2780 * PTI: Make all user-space mappings in the
2781 * kernel-mode page table no-execute so that
2782 * we detect any programming errors that leave
2783 * the kernel-mode page table active on return
2788 pml4u = &pmap->pm_pml4u[pml4index];
2789 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
2793 } else if (ptepindex >= NUPDE) {
2794 vm_pindex_t pml4index;
2795 vm_pindex_t pdpindex;
2799 /* Wire up a new PDE page */
2800 pdpindex = ptepindex - NUPDE;
2801 pml4index = pdpindex >> NPML4EPGSHIFT;
2803 pml4 = &pmap->pm_pml4[pml4index];
2804 if ((*pml4 & PG_V) == 0) {
2805 /* Have to allocate a new pdp, recurse */
2806 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2808 vm_page_unwire_noq(m);
2809 vm_page_free_zero(m);
2813 /* Add reference to pdp page */
2814 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2815 pdppg->wire_count++;
2817 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2819 /* Now find the pdp page */
2820 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2821 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2824 vm_pindex_t pml4index;
2825 vm_pindex_t pdpindex;
2830 /* Wire up a new PTE page */
2831 pdpindex = ptepindex >> NPDPEPGSHIFT;
2832 pml4index = pdpindex >> NPML4EPGSHIFT;
2834 /* First, find the pdp and check that its valid. */
2835 pml4 = &pmap->pm_pml4[pml4index];
2836 if ((*pml4 & PG_V) == 0) {
2837 /* Have to allocate a new pd, recurse */
2838 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2840 vm_page_unwire_noq(m);
2841 vm_page_free_zero(m);
2844 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2845 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2847 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2848 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2849 if ((*pdp & PG_V) == 0) {
2850 /* Have to allocate a new pd, recurse */
2851 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2853 vm_page_unwire_noq(m);
2854 vm_page_free_zero(m);
2858 /* Add reference to the pd page */
2859 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2863 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2865 /* Now we know where the page directory page is */
2866 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2867 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2870 pmap_resident_count_inc(pmap, 1);
2876 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2878 vm_pindex_t pdpindex, ptepindex;
2879 pdp_entry_t *pdpe, PG_V;
2882 PG_V = pmap_valid_bit(pmap);
2885 pdpe = pmap_pdpe(pmap, va);
2886 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2887 /* Add a reference to the pd page. */
2888 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2891 /* Allocate a pd page. */
2892 ptepindex = pmap_pde_pindex(va);
2893 pdpindex = ptepindex >> NPDPEPGSHIFT;
2894 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2895 if (pdpg == NULL && lockp != NULL)
2902 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2904 vm_pindex_t ptepindex;
2905 pd_entry_t *pd, PG_V;
2908 PG_V = pmap_valid_bit(pmap);
2911 * Calculate pagetable page index
2913 ptepindex = pmap_pde_pindex(va);
2916 * Get the page directory entry
2918 pd = pmap_pde(pmap, va);
2921 * This supports switching from a 2MB page to a
2924 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2925 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2927 * Invalidation of the 2MB page mapping may have caused
2928 * the deallocation of the underlying PD page.
2935 * If the page table page is mapped, we just increment the
2936 * hold count, and activate it.
2938 if (pd != NULL && (*pd & PG_V) != 0) {
2939 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2943 * Here if the pte page isn't mapped, or if it has been
2946 m = _pmap_allocpte(pmap, ptepindex, lockp);
2947 if (m == NULL && lockp != NULL)
2954 /***************************************************
2955 * Pmap allocation/deallocation routines.
2956 ***************************************************/
2959 * Release any resources held by the given physical map.
2960 * Called when a pmap initialized by pmap_pinit is being released.
2961 * Should only be called if the map contains no valid mappings.
2964 pmap_release(pmap_t pmap)
2969 KASSERT(pmap->pm_stats.resident_count == 0,
2970 ("pmap_release: pmap resident count %ld != 0",
2971 pmap->pm_stats.resident_count));
2972 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2973 ("pmap_release: pmap has reserved page table page(s)"));
2974 KASSERT(CPU_EMPTY(&pmap->pm_active),
2975 ("releasing active pmap %p", pmap));
2977 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2979 for (i = 0; i < NKPML4E; i++) /* KVA */
2980 pmap->pm_pml4[KPML4BASE + i] = 0;
2981 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
2982 pmap->pm_pml4[DMPML4I + i] = 0;
2983 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
2985 vm_page_unwire_noq(m);
2986 vm_page_free_zero(m);
2988 if (pmap->pm_pml4u != NULL) {
2989 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4u));
2990 vm_page_unwire_noq(m);
2996 kvm_size(SYSCTL_HANDLER_ARGS)
2998 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
3000 return sysctl_handle_long(oidp, &ksize, 0, req);
3002 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
3003 0, 0, kvm_size, "LU", "Size of KVM");
3006 kvm_free(SYSCTL_HANDLER_ARGS)
3008 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
3010 return sysctl_handle_long(oidp, &kfree, 0, req);
3012 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
3013 0, 0, kvm_free, "LU", "Amount of KVM free");
3016 * grow the number of kernel page table entries, if needed
3019 pmap_growkernel(vm_offset_t addr)
3023 pd_entry_t *pde, newpdir;
3026 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
3029 * Return if "addr" is within the range of kernel page table pages
3030 * that were preallocated during pmap bootstrap. Moreover, leave
3031 * "kernel_vm_end" and the kernel page table as they were.
3033 * The correctness of this action is based on the following
3034 * argument: vm_map_insert() allocates contiguous ranges of the
3035 * kernel virtual address space. It calls this function if a range
3036 * ends after "kernel_vm_end". If the kernel is mapped between
3037 * "kernel_vm_end" and "addr", then the range cannot begin at
3038 * "kernel_vm_end". In fact, its beginning address cannot be less
3039 * than the kernel. Thus, there is no immediate need to allocate
3040 * any new kernel page table pages between "kernel_vm_end" and
3043 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
3046 addr = roundup2(addr, NBPDR);
3047 if (addr - 1 >= kernel_map->max_offset)
3048 addr = kernel_map->max_offset;
3049 while (kernel_vm_end < addr) {
3050 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
3051 if ((*pdpe & X86_PG_V) == 0) {
3052 /* We need a new PDP entry */
3053 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
3054 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
3055 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
3057 panic("pmap_growkernel: no memory to grow kernel");
3058 if ((nkpg->flags & PG_ZERO) == 0)
3059 pmap_zero_page(nkpg);
3060 paddr = VM_PAGE_TO_PHYS(nkpg);
3061 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
3062 X86_PG_A | X86_PG_M);
3063 continue; /* try again */
3065 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
3066 if ((*pde & X86_PG_V) != 0) {
3067 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3068 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
3069 kernel_vm_end = kernel_map->max_offset;
3075 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
3076 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
3079 panic("pmap_growkernel: no memory to grow kernel");
3080 if ((nkpg->flags & PG_ZERO) == 0)
3081 pmap_zero_page(nkpg);
3082 paddr = VM_PAGE_TO_PHYS(nkpg);
3083 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
3084 pde_store(pde, newpdir);
3086 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3087 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
3088 kernel_vm_end = kernel_map->max_offset;
3095 /***************************************************
3096 * page management routines.
3097 ***************************************************/
3099 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
3100 CTASSERT(_NPCM == 3);
3101 CTASSERT(_NPCPV == 168);
3103 static __inline struct pv_chunk *
3104 pv_to_chunk(pv_entry_t pv)
3107 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
3110 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
3112 #define PC_FREE0 0xfffffffffffffffful
3113 #define PC_FREE1 0xfffffffffffffffful
3114 #define PC_FREE2 0x000000fffffffffful
3116 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
3119 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
3121 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
3122 "Current number of pv entry chunks");
3123 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
3124 "Current number of pv entry chunks allocated");
3125 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
3126 "Current number of pv entry chunks frees");
3127 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
3128 "Number of times tried to get a chunk page but failed.");
3130 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
3131 static int pv_entry_spare;
3133 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
3134 "Current number of pv entry frees");
3135 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
3136 "Current number of pv entry allocs");
3137 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
3138 "Current number of pv entries");
3139 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
3140 "Current number of spare pv entries");
3144 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
3149 pmap_invalidate_all(pmap);
3150 if (pmap != locked_pmap)
3153 pmap_delayed_invl_finished();
3157 * We are in a serious low memory condition. Resort to
3158 * drastic measures to free some pages so we can allocate
3159 * another pv entry chunk.
3161 * Returns NULL if PV entries were reclaimed from the specified pmap.
3163 * We do not, however, unmap 2mpages because subsequent accesses will
3164 * allocate per-page pv entries until repromotion occurs, thereby
3165 * exacerbating the shortage of free pv entries.
3168 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
3170 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
3171 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
3172 struct md_page *pvh;
3174 pmap_t next_pmap, pmap;
3175 pt_entry_t *pte, tpte;
3176 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3180 struct spglist free;
3182 int bit, field, freed;
3184 static int active_reclaims = 0;
3186 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
3187 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
3190 PG_G = PG_A = PG_M = PG_RW = 0;
3192 bzero(&pc_marker_b, sizeof(pc_marker_b));
3193 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
3194 pc_marker = (struct pv_chunk *)&pc_marker_b;
3195 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
3198 * A delayed invalidation block should already be active if
3199 * pmap_advise() or pmap_remove() called this function by way
3200 * of pmap_demote_pde_locked().
3202 start_di = pmap_not_in_di();
3204 mtx_lock(&pv_chunks_mutex);
3206 TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
3207 TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
3208 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
3209 SLIST_EMPTY(&free)) {
3210 next_pmap = pc->pc_pmap;
3211 if (next_pmap == NULL) {
3213 * The next chunk is a marker. However, it is
3214 * not our marker, so active_reclaims must be
3215 * > 1. Consequently, the next_chunk code
3216 * will not rotate the pv_chunks list.
3220 mtx_unlock(&pv_chunks_mutex);
3223 * A pv_chunk can only be removed from the pc_lru list
3224 * when both pc_chunks_mutex is owned and the
3225 * corresponding pmap is locked.
3227 if (pmap != next_pmap) {
3228 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
3231 /* Avoid deadlock and lock recursion. */
3232 if (pmap > locked_pmap) {
3233 RELEASE_PV_LIST_LOCK(lockp);
3236 pmap_delayed_invl_started();
3237 mtx_lock(&pv_chunks_mutex);
3239 } else if (pmap != locked_pmap) {
3240 if (PMAP_TRYLOCK(pmap)) {
3242 pmap_delayed_invl_started();
3243 mtx_lock(&pv_chunks_mutex);
3246 pmap = NULL; /* pmap is not locked */
3247 mtx_lock(&pv_chunks_mutex);
3248 pc = TAILQ_NEXT(pc_marker, pc_lru);
3250 pc->pc_pmap != next_pmap)
3254 } else if (start_di)
3255 pmap_delayed_invl_started();
3256 PG_G = pmap_global_bit(pmap);
3257 PG_A = pmap_accessed_bit(pmap);
3258 PG_M = pmap_modified_bit(pmap);
3259 PG_RW = pmap_rw_bit(pmap);
3263 * Destroy every non-wired, 4 KB page mapping in the chunk.
3266 for (field = 0; field < _NPCM; field++) {
3267 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
3268 inuse != 0; inuse &= ~(1UL << bit)) {
3270 pv = &pc->pc_pventry[field * 64 + bit];
3272 pde = pmap_pde(pmap, va);
3273 if ((*pde & PG_PS) != 0)
3275 pte = pmap_pde_to_pte(pde, va);
3276 if ((*pte & PG_W) != 0)
3278 tpte = pte_load_clear(pte);
3279 if ((tpte & PG_G) != 0)
3280 pmap_invalidate_page(pmap, va);
3281 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3282 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3284 if ((tpte & PG_A) != 0)
3285 vm_page_aflag_set(m, PGA_REFERENCED);
3286 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3287 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3289 if (TAILQ_EMPTY(&m->md.pv_list) &&
3290 (m->flags & PG_FICTITIOUS) == 0) {
3291 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3292 if (TAILQ_EMPTY(&pvh->pv_list)) {
3293 vm_page_aflag_clear(m,
3297 pmap_delayed_invl_page(m);
3298 pc->pc_map[field] |= 1UL << bit;
3299 pmap_unuse_pt(pmap, va, *pde, &free);
3304 mtx_lock(&pv_chunks_mutex);
3307 /* Every freed mapping is for a 4 KB page. */
3308 pmap_resident_count_dec(pmap, freed);
3309 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
3310 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
3311 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
3312 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3313 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
3314 pc->pc_map[2] == PC_FREE2) {
3315 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3316 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3317 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3318 /* Entire chunk is free; return it. */
3319 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3320 dump_drop_page(m_pc->phys_addr);
3321 mtx_lock(&pv_chunks_mutex);
3322 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3325 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3326 mtx_lock(&pv_chunks_mutex);
3327 /* One freed pv entry in locked_pmap is sufficient. */
3328 if (pmap == locked_pmap)
3331 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3332 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
3333 if (active_reclaims == 1 && pmap != NULL) {
3335 * Rotate the pv chunks list so that we do not
3336 * scan the same pv chunks that could not be
3337 * freed (because they contained a wired
3338 * and/or superpage mapping) on every
3339 * invocation of reclaim_pv_chunk().
3341 while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
3342 MPASS(pc->pc_pmap != NULL);
3343 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3344 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3348 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3349 TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
3351 mtx_unlock(&pv_chunks_mutex);
3352 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
3353 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
3354 m_pc = SLIST_FIRST(&free);
3355 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3356 /* Recycle a freed page table page. */
3357 m_pc->wire_count = 1;
3359 vm_page_free_pages_toq(&free, true);
3364 * free the pv_entry back to the free list
3367 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3369 struct pv_chunk *pc;
3370 int idx, field, bit;
3372 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3373 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3374 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3375 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3376 pc = pv_to_chunk(pv);
3377 idx = pv - &pc->pc_pventry[0];
3380 pc->pc_map[field] |= 1ul << bit;
3381 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3382 pc->pc_map[2] != PC_FREE2) {
3383 /* 98% of the time, pc is already at the head of the list. */
3384 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3385 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3386 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3390 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3395 free_pv_chunk(struct pv_chunk *pc)
3399 mtx_lock(&pv_chunks_mutex);
3400 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3401 mtx_unlock(&pv_chunks_mutex);
3402 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3403 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3404 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3405 /* entire chunk is free, return it */
3406 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3407 dump_drop_page(m->phys_addr);
3408 vm_page_unwire(m, PQ_NONE);
3413 * Returns a new PV entry, allocating a new PV chunk from the system when
3414 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3415 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3418 * The given PV list lock may be released.
3421 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3425 struct pv_chunk *pc;
3428 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3429 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3431 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3433 for (field = 0; field < _NPCM; field++) {
3434 if (pc->pc_map[field]) {
3435 bit = bsfq(pc->pc_map[field]);
3439 if (field < _NPCM) {
3440 pv = &pc->pc_pventry[field * 64 + bit];
3441 pc->pc_map[field] &= ~(1ul << bit);
3442 /* If this was the last item, move it to tail */
3443 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3444 pc->pc_map[2] == 0) {
3445 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3446 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3449 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3450 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3454 /* No free items, allocate another chunk */
3455 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3458 if (lockp == NULL) {
3459 PV_STAT(pc_chunk_tryfail++);
3462 m = reclaim_pv_chunk(pmap, lockp);
3466 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3467 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3468 dump_add_page(m->phys_addr);
3469 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3471 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3472 pc->pc_map[1] = PC_FREE1;
3473 pc->pc_map[2] = PC_FREE2;
3474 mtx_lock(&pv_chunks_mutex);
3475 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3476 mtx_unlock(&pv_chunks_mutex);
3477 pv = &pc->pc_pventry[0];
3478 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3479 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3480 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3485 * Returns the number of one bits within the given PV chunk map.
3487 * The erratas for Intel processors state that "POPCNT Instruction May
3488 * Take Longer to Execute Than Expected". It is believed that the
3489 * issue is the spurious dependency on the destination register.
3490 * Provide a hint to the register rename logic that the destination
3491 * value is overwritten, by clearing it, as suggested in the
3492 * optimization manual. It should be cheap for unaffected processors
3495 * Reference numbers for erratas are
3496 * 4th Gen Core: HSD146
3497 * 5th Gen Core: BDM85
3498 * 6th Gen Core: SKL029
3501 popcnt_pc_map_pq(uint64_t *map)
3505 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3506 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3507 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3508 : "=&r" (result), "=&r" (tmp)
3509 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3514 * Ensure that the number of spare PV entries in the specified pmap meets or
3515 * exceeds the given count, "needed".
3517 * The given PV list lock may be released.
3520 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3522 struct pch new_tail;
3523 struct pv_chunk *pc;
3527 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3528 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3531 * Newly allocated PV chunks must be stored in a private list until
3532 * the required number of PV chunks have been allocated. Otherwise,
3533 * reclaim_pv_chunk() could recycle one of these chunks. In
3534 * contrast, these chunks must be added to the pmap upon allocation.
3536 TAILQ_INIT(&new_tail);
3539 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3541 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3542 bit_count((bitstr_t *)pc->pc_map, 0,
3543 sizeof(pc->pc_map) * NBBY, &free);
3546 free = popcnt_pc_map_pq(pc->pc_map);
3550 if (avail >= needed)
3553 for (; avail < needed; avail += _NPCPV) {
3554 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3557 m = reclaim_pv_chunk(pmap, lockp);
3561 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3562 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3563 dump_add_page(m->phys_addr);
3564 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3566 pc->pc_map[0] = PC_FREE0;
3567 pc->pc_map[1] = PC_FREE1;
3568 pc->pc_map[2] = PC_FREE2;
3569 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3570 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3571 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3573 if (!TAILQ_EMPTY(&new_tail)) {
3574 mtx_lock(&pv_chunks_mutex);
3575 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3576 mtx_unlock(&pv_chunks_mutex);
3581 * First find and then remove the pv entry for the specified pmap and virtual
3582 * address from the specified pv list. Returns the pv entry if found and NULL
3583 * otherwise. This operation can be performed on pv lists for either 4KB or
3584 * 2MB page mappings.
3586 static __inline pv_entry_t
3587 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3591 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3592 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3593 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3602 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3603 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3604 * entries for each of the 4KB page mappings.
3607 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3608 struct rwlock **lockp)
3610 struct md_page *pvh;
3611 struct pv_chunk *pc;
3613 vm_offset_t va_last;
3617 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3618 KASSERT((pa & PDRMASK) == 0,
3619 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3620 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3623 * Transfer the 2mpage's pv entry for this mapping to the first
3624 * page's pv list. Once this transfer begins, the pv list lock
3625 * must not be released until the last pv entry is reinstantiated.
3627 pvh = pa_to_pvh(pa);
3628 va = trunc_2mpage(va);
3629 pv = pmap_pvh_remove(pvh, pmap, va);
3630 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3631 m = PHYS_TO_VM_PAGE(pa);
3632 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3634 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3635 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3636 va_last = va + NBPDR - PAGE_SIZE;
3638 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3639 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3640 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3641 for (field = 0; field < _NPCM; field++) {
3642 while (pc->pc_map[field]) {
3643 bit = bsfq(pc->pc_map[field]);
3644 pc->pc_map[field] &= ~(1ul << bit);
3645 pv = &pc->pc_pventry[field * 64 + bit];
3649 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3650 ("pmap_pv_demote_pde: page %p is not managed", m));
3651 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3657 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3658 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3661 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3662 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3663 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3665 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3666 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3669 #if VM_NRESERVLEVEL > 0
3671 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3672 * replace the many pv entries for the 4KB page mappings by a single pv entry
3673 * for the 2MB page mapping.
3676 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3677 struct rwlock **lockp)
3679 struct md_page *pvh;
3681 vm_offset_t va_last;
3684 KASSERT((pa & PDRMASK) == 0,
3685 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3686 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3689 * Transfer the first page's pv entry for this mapping to the 2mpage's
3690 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3691 * a transfer avoids the possibility that get_pv_entry() calls
3692 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3693 * mappings that is being promoted.
3695 m = PHYS_TO_VM_PAGE(pa);
3696 va = trunc_2mpage(va);
3697 pv = pmap_pvh_remove(&m->md, pmap, va);
3698 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3699 pvh = pa_to_pvh(pa);
3700 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3702 /* Free the remaining NPTEPG - 1 pv entries. */
3703 va_last = va + NBPDR - PAGE_SIZE;
3707 pmap_pvh_free(&m->md, pmap, va);
3708 } while (va < va_last);
3710 #endif /* VM_NRESERVLEVEL > 0 */
3713 * First find and then destroy the pv entry for the specified pmap and virtual
3714 * address. This operation can be performed on pv lists for either 4KB or 2MB
3718 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3722 pv = pmap_pvh_remove(pvh, pmap, va);
3723 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3724 free_pv_entry(pmap, pv);
3728 * Conditionally create the PV entry for a 4KB page mapping if the required
3729 * memory can be allocated without resorting to reclamation.
3732 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3733 struct rwlock **lockp)
3737 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3738 /* Pass NULL instead of the lock pointer to disable reclamation. */
3739 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3741 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3742 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3750 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3751 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3752 * false if the PV entry cannot be allocated without resorting to reclamation.
3755 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
3756 struct rwlock **lockp)
3758 struct md_page *pvh;
3762 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3763 /* Pass NULL instead of the lock pointer to disable reclamation. */
3764 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3765 NULL : lockp)) == NULL)
3768 pa = pde & PG_PS_FRAME;
3769 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3770 pvh = pa_to_pvh(pa);
3771 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3777 * Fills a page table page with mappings to consecutive physical pages.
3780 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3784 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3786 newpte += PAGE_SIZE;
3791 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3792 * mapping is invalidated.
3795 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3797 struct rwlock *lock;
3801 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3808 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3809 struct rwlock **lockp)
3811 pd_entry_t newpde, oldpde;
3812 pt_entry_t *firstpte, newpte;
3813 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3816 struct spglist free;
3820 PG_G = pmap_global_bit(pmap);
3821 PG_A = pmap_accessed_bit(pmap);
3822 PG_M = pmap_modified_bit(pmap);
3823 PG_RW = pmap_rw_bit(pmap);
3824 PG_V = pmap_valid_bit(pmap);
3825 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3827 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3829 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3830 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3831 if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
3833 KASSERT((oldpde & PG_W) == 0,
3834 ("pmap_demote_pde: page table page for a wired mapping"
3838 * Invalidate the 2MB page mapping and return "failure" if the
3839 * mapping was never accessed or the allocation of the new
3840 * page table page fails. If the 2MB page mapping belongs to
3841 * the direct map region of the kernel's address space, then
3842 * the page allocation request specifies the highest possible
3843 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3844 * normal. Page table pages are preallocated for every other
3845 * part of the kernel address space, so the direct map region
3846 * is the only part of the kernel address space that must be
3849 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3850 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3851 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3852 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3854 sva = trunc_2mpage(va);
3855 pmap_remove_pde(pmap, pde, sva, &free, lockp);
3856 if ((oldpde & PG_G) == 0)
3857 pmap_invalidate_pde_page(pmap, sva, oldpde);
3858 vm_page_free_pages_toq(&free, true);
3859 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3860 " in pmap %p", va, pmap);
3863 if (va < VM_MAXUSER_ADDRESS)
3864 pmap_resident_count_inc(pmap, 1);
3866 mptepa = VM_PAGE_TO_PHYS(mpte);
3867 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3868 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3869 KASSERT((oldpde & PG_A) != 0,
3870 ("pmap_demote_pde: oldpde is missing PG_A"));
3871 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3872 ("pmap_demote_pde: oldpde is missing PG_M"));
3873 newpte = oldpde & ~PG_PS;
3874 newpte = pmap_swap_pat(pmap, newpte);
3877 * If the page table page is new, initialize it.
3879 if (mpte->wire_count == 1) {
3880 mpte->wire_count = NPTEPG;
3881 pmap_fill_ptp(firstpte, newpte);
3883 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3884 ("pmap_demote_pde: firstpte and newpte map different physical"
3888 * If the mapping has changed attributes, update the page table
3891 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3892 pmap_fill_ptp(firstpte, newpte);
3895 * The spare PV entries must be reserved prior to demoting the
3896 * mapping, that is, prior to changing the PDE. Otherwise, the state
3897 * of the PDE and the PV lists will be inconsistent, which can result
3898 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3899 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3900 * PV entry for the 2MB page mapping that is being demoted.
3902 if ((oldpde & PG_MANAGED) != 0)
3903 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3906 * Demote the mapping. This pmap is locked. The old PDE has
3907 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3908 * set. Thus, there is no danger of a race with another
3909 * processor changing the setting of PG_A and/or PG_M between
3910 * the read above and the store below.
3912 if (workaround_erratum383)
3913 pmap_update_pde(pmap, va, pde, newpde);
3915 pde_store(pde, newpde);
3918 * Invalidate a stale recursive mapping of the page table page.
3920 if (va >= VM_MAXUSER_ADDRESS)
3921 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3924 * Demote the PV entry.
3926 if ((oldpde & PG_MANAGED) != 0)
3927 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3929 atomic_add_long(&pmap_pde_demotions, 1);
3930 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3931 " in pmap %p", va, pmap);
3936 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3939 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3945 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3946 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3947 mpte = pmap_remove_pt_page(pmap, va);
3949 panic("pmap_remove_kernel_pde: Missing pt page.");
3951 mptepa = VM_PAGE_TO_PHYS(mpte);
3952 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3955 * Initialize the page table page.
3957 pagezero((void *)PHYS_TO_DMAP(mptepa));
3960 * Demote the mapping.
3962 if (workaround_erratum383)
3963 pmap_update_pde(pmap, va, pde, newpde);
3965 pde_store(pde, newpde);
3968 * Invalidate a stale recursive mapping of the page table page.
3970 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3974 * pmap_remove_pde: do the things to unmap a superpage in a process
3977 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
3978 struct spglist *free, struct rwlock **lockp)
3980 struct md_page *pvh;
3982 vm_offset_t eva, va;
3984 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3986 PG_G = pmap_global_bit(pmap);
3987 PG_A = pmap_accessed_bit(pmap);
3988 PG_M = pmap_modified_bit(pmap);
3989 PG_RW = pmap_rw_bit(pmap);
3991 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3992 KASSERT((sva & PDRMASK) == 0,
3993 ("pmap_remove_pde: sva is not 2mpage aligned"));
3994 oldpde = pte_load_clear(pdq);
3996 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
3997 if ((oldpde & PG_G) != 0)
3998 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
3999 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
4000 if (oldpde & PG_MANAGED) {
4001 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
4002 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
4003 pmap_pvh_free(pvh, pmap, sva);
4005 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4006 va < eva; va += PAGE_SIZE, m++) {
4007 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
4010 vm_page_aflag_set(m, PGA_REFERENCED);
4011 if (TAILQ_EMPTY(&m->md.pv_list) &&
4012 TAILQ_EMPTY(&pvh->pv_list))
4013 vm_page_aflag_clear(m, PGA_WRITEABLE);
4014 pmap_delayed_invl_page(m);
4017 if (pmap == kernel_pmap) {
4018 pmap_remove_kernel_pde(pmap, pdq, sva);
4020 mpte = pmap_remove_pt_page(pmap, sva);
4022 pmap_resident_count_dec(pmap, 1);
4023 KASSERT(mpte->wire_count == NPTEPG,
4024 ("pmap_remove_pde: pte page wire count error"));
4025 mpte->wire_count = 0;
4026 pmap_add_delayed_free_list(mpte, free, FALSE);
4029 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
4033 * pmap_remove_pte: do the things to unmap a page in a process
4036 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
4037 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
4039 struct md_page *pvh;
4040 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
4043 PG_A = pmap_accessed_bit(pmap);
4044 PG_M = pmap_modified_bit(pmap);
4045 PG_RW = pmap_rw_bit(pmap);
4047 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4048 oldpte = pte_load_clear(ptq);
4050 pmap->pm_stats.wired_count -= 1;
4051 pmap_resident_count_dec(pmap, 1);
4052 if (oldpte & PG_MANAGED) {
4053 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
4054 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4057 vm_page_aflag_set(m, PGA_REFERENCED);
4058 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
4059 pmap_pvh_free(&m->md, pmap, va);
4060 if (TAILQ_EMPTY(&m->md.pv_list) &&
4061 (m->flags & PG_FICTITIOUS) == 0) {
4062 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4063 if (TAILQ_EMPTY(&pvh->pv_list))
4064 vm_page_aflag_clear(m, PGA_WRITEABLE);
4066 pmap_delayed_invl_page(m);
4068 return (pmap_unuse_pt(pmap, va, ptepde, free));
4072 * Remove a single page from a process address space
4075 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
4076 struct spglist *free)
4078 struct rwlock *lock;
4079 pt_entry_t *pte, PG_V;
4081 PG_V = pmap_valid_bit(pmap);
4082 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4083 if ((*pde & PG_V) == 0)
4085 pte = pmap_pde_to_pte(pde, va);
4086 if ((*pte & PG_V) == 0)
4089 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
4092 pmap_invalidate_page(pmap, va);
4096 * Removes the specified range of addresses from the page table page.
4099 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
4100 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
4102 pt_entry_t PG_G, *pte;
4106 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4107 PG_G = pmap_global_bit(pmap);
4110 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
4114 pmap_invalidate_range(pmap, va, sva);
4119 if ((*pte & PG_G) == 0)
4123 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
4129 pmap_invalidate_range(pmap, va, sva);
4134 * Remove the given range of addresses from the specified map.
4136 * It is assumed that the start and end are properly
4137 * rounded to the page size.
4140 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4142 struct rwlock *lock;
4143 vm_offset_t va_next;
4144 pml4_entry_t *pml4e;
4146 pd_entry_t ptpaddr, *pde;
4147 pt_entry_t PG_G, PG_V;
4148 struct spglist free;
4151 PG_G = pmap_global_bit(pmap);
4152 PG_V = pmap_valid_bit(pmap);
4155 * Perform an unsynchronized read. This is, however, safe.
4157 if (pmap->pm_stats.resident_count == 0)
4163 pmap_delayed_invl_started();
4167 * special handling of removing one page. a very
4168 * common operation and easy to short circuit some
4171 if (sva + PAGE_SIZE == eva) {
4172 pde = pmap_pde(pmap, sva);
4173 if (pde && (*pde & PG_PS) == 0) {
4174 pmap_remove_page(pmap, sva, pde, &free);
4180 for (; sva < eva; sva = va_next) {
4182 if (pmap->pm_stats.resident_count == 0)
4185 pml4e = pmap_pml4e(pmap, sva);
4186 if ((*pml4e & PG_V) == 0) {
4187 va_next = (sva + NBPML4) & ~PML4MASK;
4193 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4194 if ((*pdpe & PG_V) == 0) {
4195 va_next = (sva + NBPDP) & ~PDPMASK;
4202 * Calculate index for next page table.
4204 va_next = (sva + NBPDR) & ~PDRMASK;
4208 pde = pmap_pdpe_to_pde(pdpe, sva);
4212 * Weed out invalid mappings.
4218 * Check for large page.
4220 if ((ptpaddr & PG_PS) != 0) {
4222 * Are we removing the entire large page? If not,
4223 * demote the mapping and fall through.
4225 if (sva + NBPDR == va_next && eva >= va_next) {
4227 * The TLB entry for a PG_G mapping is
4228 * invalidated by pmap_remove_pde().
4230 if ((ptpaddr & PG_G) == 0)
4232 pmap_remove_pde(pmap, pde, sva, &free, &lock);
4234 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
4236 /* The large page mapping was destroyed. */
4243 * Limit our scan to either the end of the va represented
4244 * by the current page table page, or to the end of the
4245 * range being removed.
4250 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
4257 pmap_invalidate_all(pmap);
4259 pmap_delayed_invl_finished();
4260 vm_page_free_pages_toq(&free, true);
4264 * Routine: pmap_remove_all
4266 * Removes this physical page from
4267 * all physical maps in which it resides.
4268 * Reflects back modify bits to the pager.
4271 * Original versions of this routine were very
4272 * inefficient because they iteratively called
4273 * pmap_remove (slow...)
4277 pmap_remove_all(vm_page_t m)
4279 struct md_page *pvh;
4282 struct rwlock *lock;
4283 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
4286 struct spglist free;
4287 int pvh_gen, md_gen;
4289 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4290 ("pmap_remove_all: page %p is not managed", m));
4292 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4293 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
4294 pa_to_pvh(VM_PAGE_TO_PHYS(m));
4297 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
4299 if (!PMAP_TRYLOCK(pmap)) {
4300 pvh_gen = pvh->pv_gen;
4304 if (pvh_gen != pvh->pv_gen) {
4311 pde = pmap_pde(pmap, va);
4312 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
4315 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4317 if (!PMAP_TRYLOCK(pmap)) {
4318 pvh_gen = pvh->pv_gen;
4319 md_gen = m->md.pv_gen;
4323 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
4329 PG_A = pmap_accessed_bit(pmap);
4330 PG_M = pmap_modified_bit(pmap);
4331 PG_RW = pmap_rw_bit(pmap);
4332 pmap_resident_count_dec(pmap, 1);
4333 pde = pmap_pde(pmap, pv->pv_va);
4334 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
4335 " a 2mpage in page %p's pv list", m));
4336 pte = pmap_pde_to_pte(pde, pv->pv_va);
4337 tpte = pte_load_clear(pte);
4339 pmap->pm_stats.wired_count--;
4341 vm_page_aflag_set(m, PGA_REFERENCED);
4344 * Update the vm_page_t clean and reference bits.
4346 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4348 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
4349 pmap_invalidate_page(pmap, pv->pv_va);
4350 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4352 free_pv_entry(pmap, pv);
4355 vm_page_aflag_clear(m, PGA_WRITEABLE);
4357 pmap_delayed_invl_wait(m);
4358 vm_page_free_pages_toq(&free, true);
4362 * pmap_protect_pde: do the things to protect a 2mpage in a process
4365 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
4367 pd_entry_t newpde, oldpde;
4368 vm_offset_t eva, va;
4370 boolean_t anychanged;
4371 pt_entry_t PG_G, PG_M, PG_RW;
4373 PG_G = pmap_global_bit(pmap);
4374 PG_M = pmap_modified_bit(pmap);
4375 PG_RW = pmap_rw_bit(pmap);
4377 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4378 KASSERT((sva & PDRMASK) == 0,
4379 ("pmap_protect_pde: sva is not 2mpage aligned"));
4382 oldpde = newpde = *pde;
4383 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4384 (PG_MANAGED | PG_M | PG_RW)) {
4386 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4387 va < eva; va += PAGE_SIZE, m++)
4390 if ((prot & VM_PROT_WRITE) == 0)
4391 newpde &= ~(PG_RW | PG_M);
4392 if ((prot & VM_PROT_EXECUTE) == 0)
4394 if (newpde != oldpde) {
4396 * As an optimization to future operations on this PDE, clear
4397 * PG_PROMOTED. The impending invalidation will remove any
4398 * lingering 4KB page mappings from the TLB.
4400 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
4402 if ((oldpde & PG_G) != 0)
4403 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4407 return (anychanged);
4411 * Set the physical protection on the
4412 * specified range of this map as requested.
4415 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4417 vm_offset_t va_next;
4418 pml4_entry_t *pml4e;
4420 pd_entry_t ptpaddr, *pde;
4421 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4422 boolean_t anychanged;
4424 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4425 if (prot == VM_PROT_NONE) {
4426 pmap_remove(pmap, sva, eva);
4430 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4431 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4434 PG_G = pmap_global_bit(pmap);
4435 PG_M = pmap_modified_bit(pmap);
4436 PG_V = pmap_valid_bit(pmap);
4437 PG_RW = pmap_rw_bit(pmap);
4441 * Although this function delays and batches the invalidation
4442 * of stale TLB entries, it does not need to call
4443 * pmap_delayed_invl_started() and
4444 * pmap_delayed_invl_finished(), because it does not
4445 * ordinarily destroy mappings. Stale TLB entries from
4446 * protection-only changes need only be invalidated before the
4447 * pmap lock is released, because protection-only changes do
4448 * not destroy PV entries. Even operations that iterate over
4449 * a physical page's PV list of mappings, like
4450 * pmap_remove_write(), acquire the pmap lock for each
4451 * mapping. Consequently, for protection-only changes, the
4452 * pmap lock suffices to synchronize both page table and TLB
4455 * This function only destroys a mapping if pmap_demote_pde()
4456 * fails. In that case, stale TLB entries are immediately
4461 for (; sva < eva; sva = va_next) {
4463 pml4e = pmap_pml4e(pmap, sva);
4464 if ((*pml4e & PG_V) == 0) {
4465 va_next = (sva + NBPML4) & ~PML4MASK;
4471 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4472 if ((*pdpe & PG_V) == 0) {
4473 va_next = (sva + NBPDP) & ~PDPMASK;
4479 va_next = (sva + NBPDR) & ~PDRMASK;
4483 pde = pmap_pdpe_to_pde(pdpe, sva);
4487 * Weed out invalid mappings.
4493 * Check for large page.
4495 if ((ptpaddr & PG_PS) != 0) {
4497 * Are we protecting the entire large page? If not,
4498 * demote the mapping and fall through.
4500 if (sva + NBPDR == va_next && eva >= va_next) {
4502 * The TLB entry for a PG_G mapping is
4503 * invalidated by pmap_protect_pde().
4505 if (pmap_protect_pde(pmap, pde, sva, prot))
4508 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4510 * The large page mapping was destroyed.
4519 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4521 pt_entry_t obits, pbits;
4525 obits = pbits = *pte;
4526 if ((pbits & PG_V) == 0)
4529 if ((prot & VM_PROT_WRITE) == 0) {
4530 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4531 (PG_MANAGED | PG_M | PG_RW)) {
4532 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4535 pbits &= ~(PG_RW | PG_M);
4537 if ((prot & VM_PROT_EXECUTE) == 0)
4540 if (pbits != obits) {
4541 if (!atomic_cmpset_long(pte, obits, pbits))
4544 pmap_invalidate_page(pmap, sva);
4551 pmap_invalidate_all(pmap);
4555 #if VM_NRESERVLEVEL > 0
4557 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4558 * single page table page (PTP) to a single 2MB page mapping. For promotion
4559 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4560 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4561 * identical characteristics.
4564 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4565 struct rwlock **lockp)
4568 pt_entry_t *firstpte, oldpte, pa, *pte;
4569 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4573 PG_A = pmap_accessed_bit(pmap);
4574 PG_G = pmap_global_bit(pmap);
4575 PG_M = pmap_modified_bit(pmap);
4576 PG_V = pmap_valid_bit(pmap);
4577 PG_RW = pmap_rw_bit(pmap);
4578 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4580 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4583 * Examine the first PTE in the specified PTP. Abort if this PTE is
4584 * either invalid, unused, or does not map the first 4KB physical page
4585 * within a 2MB page.
4587 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4590 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4591 atomic_add_long(&pmap_pde_p_failures, 1);
4592 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4593 " in pmap %p", va, pmap);
4596 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4598 * When PG_M is already clear, PG_RW can be cleared without
4599 * a TLB invalidation.
4601 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4607 * Examine each of the other PTEs in the specified PTP. Abort if this
4608 * PTE maps an unexpected 4KB physical page or does not have identical
4609 * characteristics to the first PTE.
4611 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4612 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4615 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4616 atomic_add_long(&pmap_pde_p_failures, 1);
4617 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4618 " in pmap %p", va, pmap);
4621 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4623 * When PG_M is already clear, PG_RW can be cleared
4624 * without a TLB invalidation.
4626 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4629 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4630 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4631 (va & ~PDRMASK), pmap);
4633 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4634 atomic_add_long(&pmap_pde_p_failures, 1);
4635 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4636 " in pmap %p", va, pmap);
4643 * Save the page table page in its current state until the PDE
4644 * mapping the superpage is demoted by pmap_demote_pde() or
4645 * destroyed by pmap_remove_pde().
4647 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4648 KASSERT(mpte >= vm_page_array &&
4649 mpte < &vm_page_array[vm_page_array_size],
4650 ("pmap_promote_pde: page table page is out of range"));
4651 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4652 ("pmap_promote_pde: page table page's pindex is wrong"));
4653 if (pmap_insert_pt_page(pmap, mpte)) {
4654 atomic_add_long(&pmap_pde_p_failures, 1);
4656 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4662 * Promote the pv entries.
4664 if ((newpde & PG_MANAGED) != 0)
4665 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4668 * Propagate the PAT index to its proper position.
4670 newpde = pmap_swap_pat(pmap, newpde);
4673 * Map the superpage.
4675 if (workaround_erratum383)
4676 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4678 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
4680 atomic_add_long(&pmap_pde_promotions, 1);
4681 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4682 " in pmap %p", va, pmap);
4684 #endif /* VM_NRESERVLEVEL > 0 */
4687 * Insert the given physical page (p) at
4688 * the specified virtual address (v) in the
4689 * target physical map with the protection requested.
4691 * If specified, the page will be wired down, meaning
4692 * that the related pte can not be reclaimed.
4694 * NB: This is the only routine which MAY NOT lazy-evaluate
4695 * or lose information. That is, this routine must actually
4696 * insert this page into the given map NOW.
4698 * When destroying both a page table and PV entry, this function
4699 * performs the TLB invalidation before releasing the PV list
4700 * lock, so we do not need pmap_delayed_invl_page() calls here.
4703 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4704 u_int flags, int8_t psind)
4706 struct rwlock *lock;
4708 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4709 pt_entry_t newpte, origpte;
4716 PG_A = pmap_accessed_bit(pmap);
4717 PG_G = pmap_global_bit(pmap);
4718 PG_M = pmap_modified_bit(pmap);
4719 PG_V = pmap_valid_bit(pmap);
4720 PG_RW = pmap_rw_bit(pmap);
4722 va = trunc_page(va);
4723 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4724 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4725 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4727 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4728 va >= kmi.clean_eva,
4729 ("pmap_enter: managed mapping within the clean submap"));
4730 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4731 VM_OBJECT_ASSERT_LOCKED(m->object);
4732 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
4733 ("pmap_enter: flags %u has reserved bits set", flags));
4734 pa = VM_PAGE_TO_PHYS(m);
4735 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4736 if ((flags & VM_PROT_WRITE) != 0)
4738 if ((prot & VM_PROT_WRITE) != 0)
4740 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4741 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4742 if ((prot & VM_PROT_EXECUTE) == 0)
4744 if ((flags & PMAP_ENTER_WIRED) != 0)
4746 if (va < VM_MAXUSER_ADDRESS)
4748 if (pmap == kernel_pmap)
4750 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
4753 * Set modified bit gratuitously for writeable mappings if
4754 * the page is unmanaged. We do not want to take a fault
4755 * to do the dirty bit accounting for these mappings.
4757 if ((m->oflags & VPO_UNMANAGED) != 0) {
4758 if ((newpte & PG_RW) != 0)
4761 newpte |= PG_MANAGED;
4766 /* Assert the required virtual and physical alignment. */
4767 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
4768 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4769 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
4775 * In the case that a page table page is not
4776 * resident, we are creating it here.
4779 pde = pmap_pde(pmap, va);
4780 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4781 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4782 pte = pmap_pde_to_pte(pde, va);
4783 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4784 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4787 } else if (va < VM_MAXUSER_ADDRESS) {
4789 * Here if the pte page isn't mapped, or if it has been
4792 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4793 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4794 nosleep ? NULL : &lock);
4795 if (mpte == NULL && nosleep) {
4796 rv = KERN_RESOURCE_SHORTAGE;
4801 panic("pmap_enter: invalid page directory va=%#lx", va);
4806 * Is the specified virtual address already mapped?
4808 if ((origpte & PG_V) != 0) {
4810 * Wiring change, just update stats. We don't worry about
4811 * wiring PT pages as they remain resident as long as there
4812 * are valid mappings in them. Hence, if a user page is wired,
4813 * the PT page will be also.
4815 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4816 pmap->pm_stats.wired_count++;
4817 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4818 pmap->pm_stats.wired_count--;
4821 * Remove the extra PT page reference.
4825 KASSERT(mpte->wire_count > 0,
4826 ("pmap_enter: missing reference to page table page,"
4831 * Has the physical page changed?
4833 opa = origpte & PG_FRAME;
4836 * No, might be a protection or wiring change.
4838 if ((origpte & PG_MANAGED) != 0 &&
4839 (newpte & PG_RW) != 0)
4840 vm_page_aflag_set(m, PGA_WRITEABLE);
4841 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4847 * Increment the counters.
4849 if ((newpte & PG_W) != 0)
4850 pmap->pm_stats.wired_count++;
4851 pmap_resident_count_inc(pmap, 1);
4855 * Enter on the PV list if part of our managed memory.
4857 if ((newpte & PG_MANAGED) != 0) {
4858 pv = get_pv_entry(pmap, &lock);
4860 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4861 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4863 if ((newpte & PG_RW) != 0)
4864 vm_page_aflag_set(m, PGA_WRITEABLE);
4870 if ((origpte & PG_V) != 0) {
4872 origpte = pte_load_store(pte, newpte);
4873 opa = origpte & PG_FRAME;
4875 if ((origpte & PG_MANAGED) != 0) {
4876 om = PHYS_TO_VM_PAGE(opa);
4877 if ((origpte & (PG_M | PG_RW)) == (PG_M |
4880 if ((origpte & PG_A) != 0)
4881 vm_page_aflag_set(om, PGA_REFERENCED);
4882 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4883 pmap_pvh_free(&om->md, pmap, va);
4884 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4885 TAILQ_EMPTY(&om->md.pv_list) &&
4886 ((om->flags & PG_FICTITIOUS) != 0 ||
4887 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4888 vm_page_aflag_clear(om, PGA_WRITEABLE);
4890 } else if ((newpte & PG_M) == 0 && (origpte & (PG_M |
4891 PG_RW)) == (PG_M | PG_RW)) {
4892 if ((origpte & PG_MANAGED) != 0)
4896 * Although the PTE may still have PG_RW set, TLB
4897 * invalidation may nonetheless be required because
4898 * the PTE no longer has PG_M set.
4900 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4902 * This PTE change does not require TLB invalidation.
4906 if ((origpte & PG_A) != 0)
4907 pmap_invalidate_page(pmap, va);
4909 pte_store(pte, newpte);
4913 #if VM_NRESERVLEVEL > 0
4915 * If both the page table page and the reservation are fully
4916 * populated, then attempt promotion.
4918 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4919 pmap_ps_enabled(pmap) &&
4920 (m->flags & PG_FICTITIOUS) == 0 &&
4921 vm_reserv_level_iffullpop(m) == 0)
4922 pmap_promote_pde(pmap, pde, va, &lock);
4934 * Tries to create a read- and/or execute-only 2MB page mapping. Returns true
4935 * if successful. Returns false if (1) a page table page cannot be allocated
4936 * without sleeping, (2) a mapping already exists at the specified virtual
4937 * address, or (3) a PV entry cannot be allocated without reclaiming another
4941 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4942 struct rwlock **lockp)
4947 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4948 PG_V = pmap_valid_bit(pmap);
4949 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
4951 if ((m->oflags & VPO_UNMANAGED) == 0)
4952 newpde |= PG_MANAGED;
4953 if ((prot & VM_PROT_EXECUTE) == 0)
4955 if (va < VM_MAXUSER_ADDRESS)
4957 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
4958 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
4963 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
4964 * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
4965 * otherwise. Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
4966 * a mapping already exists at the specified virtual address. Returns
4967 * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
4968 * page allocation failed. Returns KERN_RESOURCE_SHORTAGE if
4969 * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
4971 * The parameter "m" is only used when creating a managed, writeable mapping.
4974 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
4975 vm_page_t m, struct rwlock **lockp)
4977 struct spglist free;
4978 pd_entry_t oldpde, *pde;
4979 pt_entry_t PG_G, PG_RW, PG_V;
4982 PG_G = pmap_global_bit(pmap);
4983 PG_RW = pmap_rw_bit(pmap);
4984 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
4985 ("pmap_enter_pde: newpde is missing PG_M"));
4986 PG_V = pmap_valid_bit(pmap);
4987 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4989 if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
4990 NULL : lockp)) == NULL) {
4991 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4992 " in pmap %p", va, pmap);
4993 return (KERN_RESOURCE_SHORTAGE);
4995 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4996 pde = &pde[pmap_pde_index(va)];
4998 if ((oldpde & PG_V) != 0) {
4999 KASSERT(pdpg->wire_count > 1,
5000 ("pmap_enter_pde: pdpg's wire count is too low"));
5001 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
5003 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5004 " in pmap %p", va, pmap);
5005 return (KERN_FAILURE);
5007 /* Break the existing mapping(s). */
5009 if ((oldpde & PG_PS) != 0) {
5011 * The reference to the PD page that was acquired by
5012 * pmap_allocpde() ensures that it won't be freed.
5013 * However, if the PDE resulted from a promotion, then
5014 * a reserved PT page could be freed.
5016 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
5017 if ((oldpde & PG_G) == 0)
5018 pmap_invalidate_pde_page(pmap, va, oldpde);
5020 pmap_delayed_invl_started();
5021 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
5023 pmap_invalidate_all(pmap);
5024 pmap_delayed_invl_finished();
5026 vm_page_free_pages_toq(&free, true);
5027 if (va >= VM_MAXUSER_ADDRESS) {
5028 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
5029 if (pmap_insert_pt_page(pmap, mt)) {
5031 * XXX Currently, this can't happen because
5032 * we do not perform pmap_enter(psind == 1)
5033 * on the kernel pmap.
5035 panic("pmap_enter_pde: trie insert failed");
5038 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
5041 if ((newpde & PG_MANAGED) != 0) {
5043 * Abort this mapping if its PV entry could not be created.
5045 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
5047 if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
5049 * Although "va" is not mapped, paging-
5050 * structure caches could nonetheless have
5051 * entries that refer to the freed page table
5052 * pages. Invalidate those entries.
5054 pmap_invalidate_page(pmap, va);
5055 vm_page_free_pages_toq(&free, true);
5057 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5058 " in pmap %p", va, pmap);
5059 return (KERN_RESOURCE_SHORTAGE);
5061 if ((newpde & PG_RW) != 0) {
5062 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5063 vm_page_aflag_set(mt, PGA_WRITEABLE);
5068 * Increment counters.
5070 if ((newpde & PG_W) != 0)
5071 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
5072 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5075 * Map the superpage. (This is not a promoted mapping; there will not
5076 * be any lingering 4KB page mappings in the TLB.)
5078 pde_store(pde, newpde);
5080 atomic_add_long(&pmap_pde_mappings, 1);
5081 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
5082 " in pmap %p", va, pmap);
5083 return (KERN_SUCCESS);
5087 * Maps a sequence of resident pages belonging to the same object.
5088 * The sequence begins with the given page m_start. This page is
5089 * mapped at the given virtual address start. Each subsequent page is
5090 * mapped at a virtual address that is offset from start by the same
5091 * amount as the page is offset from m_start within the object. The
5092 * last page in the sequence is the page with the largest offset from
5093 * m_start that can be mapped at a virtual address less than the given
5094 * virtual address end. Not every virtual page between start and end
5095 * is mapped; only those for which a resident page exists with the
5096 * corresponding offset from m_start are mapped.
5099 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
5100 vm_page_t m_start, vm_prot_t prot)
5102 struct rwlock *lock;
5105 vm_pindex_t diff, psize;
5107 VM_OBJECT_ASSERT_LOCKED(m_start->object);
5109 psize = atop(end - start);
5114 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
5115 va = start + ptoa(diff);
5116 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
5117 m->psind == 1 && pmap_ps_enabled(pmap) &&
5118 pmap_enter_2mpage(pmap, va, m, prot, &lock))
5119 m = &m[NBPDR / PAGE_SIZE - 1];
5121 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
5123 m = TAILQ_NEXT(m, listq);
5131 * this code makes some *MAJOR* assumptions:
5132 * 1. Current pmap & pmap exists.
5135 * 4. No page table pages.
5136 * but is *MUCH* faster than pmap_enter...
5140 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
5142 struct rwlock *lock;
5146 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
5153 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
5154 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
5156 struct spglist free;
5157 pt_entry_t *pte, PG_V;
5160 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
5161 (m->oflags & VPO_UNMANAGED) != 0,
5162 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
5163 PG_V = pmap_valid_bit(pmap);
5164 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5167 * In the case that a page table page is not
5168 * resident, we are creating it here.
5170 if (va < VM_MAXUSER_ADDRESS) {
5171 vm_pindex_t ptepindex;
5175 * Calculate pagetable page index
5177 ptepindex = pmap_pde_pindex(va);
5178 if (mpte && (mpte->pindex == ptepindex)) {
5182 * Get the page directory entry
5184 ptepa = pmap_pde(pmap, va);
5187 * If the page table page is mapped, we just increment
5188 * the hold count, and activate it. Otherwise, we
5189 * attempt to allocate a page table page. If this
5190 * attempt fails, we don't retry. Instead, we give up.
5192 if (ptepa && (*ptepa & PG_V) != 0) {
5195 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
5199 * Pass NULL instead of the PV list lock
5200 * pointer, because we don't intend to sleep.
5202 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
5207 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
5208 pte = &pte[pmap_pte_index(va)];
5222 * Enter on the PV list if part of our managed memory.
5224 if ((m->oflags & VPO_UNMANAGED) == 0 &&
5225 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
5228 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
5230 * Although "va" is not mapped, paging-
5231 * structure caches could nonetheless have
5232 * entries that refer to the freed page table
5233 * pages. Invalidate those entries.
5235 pmap_invalidate_page(pmap, va);
5236 vm_page_free_pages_toq(&free, true);
5244 * Increment counters
5246 pmap_resident_count_inc(pmap, 1);
5248 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
5249 if ((prot & VM_PROT_EXECUTE) == 0)
5253 * Now validate mapping with RO protection
5255 if ((m->oflags & VPO_UNMANAGED) != 0)
5256 pte_store(pte, pa | PG_V | PG_U);
5258 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
5263 * Make a temporary mapping for a physical address. This is only intended
5264 * to be used for panic dumps.
5267 pmap_kenter_temporary(vm_paddr_t pa, int i)
5271 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
5272 pmap_kenter(va, pa);
5274 return ((void *)crashdumpmap);
5278 * This code maps large physical mmap regions into the
5279 * processor address space. Note that some shortcuts
5280 * are taken, but the code works.
5283 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
5284 vm_pindex_t pindex, vm_size_t size)
5287 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5288 vm_paddr_t pa, ptepa;
5292 PG_A = pmap_accessed_bit(pmap);
5293 PG_M = pmap_modified_bit(pmap);
5294 PG_V = pmap_valid_bit(pmap);
5295 PG_RW = pmap_rw_bit(pmap);
5297 VM_OBJECT_ASSERT_WLOCKED(object);
5298 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
5299 ("pmap_object_init_pt: non-device object"));
5300 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
5301 if (!pmap_ps_enabled(pmap))
5303 if (!vm_object_populate(object, pindex, pindex + atop(size)))
5305 p = vm_page_lookup(object, pindex);
5306 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5307 ("pmap_object_init_pt: invalid page %p", p));
5308 pat_mode = p->md.pat_mode;
5311 * Abort the mapping if the first page is not physically
5312 * aligned to a 2MB page boundary.
5314 ptepa = VM_PAGE_TO_PHYS(p);
5315 if (ptepa & (NBPDR - 1))
5319 * Skip the first page. Abort the mapping if the rest of
5320 * the pages are not physically contiguous or have differing
5321 * memory attributes.
5323 p = TAILQ_NEXT(p, listq);
5324 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
5326 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5327 ("pmap_object_init_pt: invalid page %p", p));
5328 if (pa != VM_PAGE_TO_PHYS(p) ||
5329 pat_mode != p->md.pat_mode)
5331 p = TAILQ_NEXT(p, listq);
5335 * Map using 2MB pages. Since "ptepa" is 2M aligned and
5336 * "size" is a multiple of 2M, adding the PAT setting to "pa"
5337 * will not affect the termination of this loop.
5340 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
5341 pa < ptepa + size; pa += NBPDR) {
5342 pdpg = pmap_allocpde(pmap, addr, NULL);
5345 * The creation of mappings below is only an
5346 * optimization. If a page directory page
5347 * cannot be allocated without blocking,
5348 * continue on to the next mapping rather than
5354 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5355 pde = &pde[pmap_pde_index(addr)];
5356 if ((*pde & PG_V) == 0) {
5357 pde_store(pde, pa | PG_PS | PG_M | PG_A |
5358 PG_U | PG_RW | PG_V);
5359 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5360 atomic_add_long(&pmap_pde_mappings, 1);
5362 /* Continue on if the PDE is already valid. */
5364 KASSERT(pdpg->wire_count > 0,
5365 ("pmap_object_init_pt: missing reference "
5366 "to page directory page, va: 0x%lx", addr));
5375 * Clear the wired attribute from the mappings for the specified range of
5376 * addresses in the given pmap. Every valid mapping within that range
5377 * must have the wired attribute set. In contrast, invalid mappings
5378 * cannot have the wired attribute set, so they are ignored.
5380 * The wired attribute of the page table entry is not a hardware
5381 * feature, so there is no need to invalidate any TLB entries.
5382 * Since pmap_demote_pde() for the wired entry must never fail,
5383 * pmap_delayed_invl_started()/finished() calls around the
5384 * function are not needed.
5387 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5389 vm_offset_t va_next;
5390 pml4_entry_t *pml4e;
5393 pt_entry_t *pte, PG_V;
5395 PG_V = pmap_valid_bit(pmap);
5397 for (; sva < eva; sva = va_next) {
5398 pml4e = pmap_pml4e(pmap, sva);
5399 if ((*pml4e & PG_V) == 0) {
5400 va_next = (sva + NBPML4) & ~PML4MASK;
5405 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5406 if ((*pdpe & PG_V) == 0) {
5407 va_next = (sva + NBPDP) & ~PDPMASK;
5412 va_next = (sva + NBPDR) & ~PDRMASK;
5415 pde = pmap_pdpe_to_pde(pdpe, sva);
5416 if ((*pde & PG_V) == 0)
5418 if ((*pde & PG_PS) != 0) {
5419 if ((*pde & PG_W) == 0)
5420 panic("pmap_unwire: pde %#jx is missing PG_W",
5424 * Are we unwiring the entire large page? If not,
5425 * demote the mapping and fall through.
5427 if (sva + NBPDR == va_next && eva >= va_next) {
5428 atomic_clear_long(pde, PG_W);
5429 pmap->pm_stats.wired_count -= NBPDR /
5432 } else if (!pmap_demote_pde(pmap, pde, sva))
5433 panic("pmap_unwire: demotion failed");
5437 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
5439 if ((*pte & PG_V) == 0)
5441 if ((*pte & PG_W) == 0)
5442 panic("pmap_unwire: pte %#jx is missing PG_W",
5446 * PG_W must be cleared atomically. Although the pmap
5447 * lock synchronizes access to PG_W, another processor
5448 * could be setting PG_M and/or PG_A concurrently.
5450 atomic_clear_long(pte, PG_W);
5451 pmap->pm_stats.wired_count--;
5458 * Copy the range specified by src_addr/len
5459 * from the source map to the range dst_addr/len
5460 * in the destination map.
5462 * This routine is only advisory and need not do anything.
5466 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5467 vm_offset_t src_addr)
5469 struct rwlock *lock;
5470 struct spglist free;
5472 vm_offset_t end_addr = src_addr + len;
5473 vm_offset_t va_next;
5474 vm_page_t dst_pdpg, dstmpte, srcmpte;
5475 pt_entry_t PG_A, PG_M, PG_V;
5477 if (dst_addr != src_addr)
5480 if (dst_pmap->pm_type != src_pmap->pm_type)
5484 * EPT page table entries that require emulation of A/D bits are
5485 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5486 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5487 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5488 * implementations flag an EPT misconfiguration for exec-only
5489 * mappings we skip this function entirely for emulated pmaps.
5491 if (pmap_emulate_ad_bits(dst_pmap))
5495 if (dst_pmap < src_pmap) {
5496 PMAP_LOCK(dst_pmap);
5497 PMAP_LOCK(src_pmap);
5499 PMAP_LOCK(src_pmap);
5500 PMAP_LOCK(dst_pmap);
5503 PG_A = pmap_accessed_bit(dst_pmap);
5504 PG_M = pmap_modified_bit(dst_pmap);
5505 PG_V = pmap_valid_bit(dst_pmap);
5507 for (addr = src_addr; addr < end_addr; addr = va_next) {
5508 pt_entry_t *src_pte, *dst_pte;
5509 pml4_entry_t *pml4e;
5511 pd_entry_t srcptepaddr, *pde;
5513 KASSERT(addr < UPT_MIN_ADDRESS,
5514 ("pmap_copy: invalid to pmap_copy page tables"));
5516 pml4e = pmap_pml4e(src_pmap, addr);
5517 if ((*pml4e & PG_V) == 0) {
5518 va_next = (addr + NBPML4) & ~PML4MASK;
5524 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5525 if ((*pdpe & PG_V) == 0) {
5526 va_next = (addr + NBPDP) & ~PDPMASK;
5532 va_next = (addr + NBPDR) & ~PDRMASK;
5536 pde = pmap_pdpe_to_pde(pdpe, addr);
5538 if (srcptepaddr == 0)
5541 if (srcptepaddr & PG_PS) {
5542 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5544 dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
5545 if (dst_pdpg == NULL)
5547 pde = (pd_entry_t *)
5548 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
5549 pde = &pde[pmap_pde_index(addr)];
5550 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5551 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
5552 PMAP_ENTER_NORECLAIM, &lock))) {
5553 *pde = srcptepaddr & ~PG_W;
5554 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5555 atomic_add_long(&pmap_pde_mappings, 1);
5557 dst_pdpg->wire_count--;
5561 srcptepaddr &= PG_FRAME;
5562 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5563 KASSERT(srcmpte->wire_count > 0,
5564 ("pmap_copy: source page table page is unused"));
5566 if (va_next > end_addr)
5569 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5570 src_pte = &src_pte[pmap_pte_index(addr)];
5572 while (addr < va_next) {
5576 * we only virtual copy managed pages
5578 if ((ptetemp & PG_MANAGED) != 0) {
5579 if (dstmpte != NULL &&
5580 dstmpte->pindex == pmap_pde_pindex(addr))
5581 dstmpte->wire_count++;
5582 else if ((dstmpte = pmap_allocpte(dst_pmap,
5583 addr, NULL)) == NULL)
5585 dst_pte = (pt_entry_t *)
5586 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5587 dst_pte = &dst_pte[pmap_pte_index(addr)];
5588 if (*dst_pte == 0 &&
5589 pmap_try_insert_pv_entry(dst_pmap, addr,
5590 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5593 * Clear the wired, modified, and
5594 * accessed (referenced) bits
5597 *dst_pte = ptetemp & ~(PG_W | PG_M |
5599 pmap_resident_count_inc(dst_pmap, 1);
5602 if (pmap_unwire_ptp(dst_pmap, addr,
5605 * Although "addr" is not
5606 * mapped, paging-structure
5607 * caches could nonetheless
5608 * have entries that refer to
5609 * the freed page table pages.
5610 * Invalidate those entries.
5612 pmap_invalidate_page(dst_pmap,
5614 vm_page_free_pages_toq(&free,
5619 if (dstmpte->wire_count >= srcmpte->wire_count)
5629 PMAP_UNLOCK(src_pmap);
5630 PMAP_UNLOCK(dst_pmap);
5634 * Zero the specified hardware page.
5637 pmap_zero_page(vm_page_t m)
5639 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5641 pagezero((void *)va);
5645 * Zero an an area within a single hardware page. off and size must not
5646 * cover an area beyond a single hardware page.
5649 pmap_zero_page_area(vm_page_t m, int off, int size)
5651 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5653 if (off == 0 && size == PAGE_SIZE)
5654 pagezero((void *)va);
5656 bzero((char *)va + off, size);
5660 * Copy 1 specified hardware page to another.
5663 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5665 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5666 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5668 pagecopy((void *)src, (void *)dst);
5671 int unmapped_buf_allowed = 1;
5674 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5675 vm_offset_t b_offset, int xfersize)
5679 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5683 while (xfersize > 0) {
5684 a_pg_offset = a_offset & PAGE_MASK;
5685 pages[0] = ma[a_offset >> PAGE_SHIFT];
5686 b_pg_offset = b_offset & PAGE_MASK;
5687 pages[1] = mb[b_offset >> PAGE_SHIFT];
5688 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5689 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5690 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5691 a_cp = (char *)vaddr[0] + a_pg_offset;
5692 b_cp = (char *)vaddr[1] + b_pg_offset;
5693 bcopy(a_cp, b_cp, cnt);
5694 if (__predict_false(mapped))
5695 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5703 * Returns true if the pmap's pv is one of the first
5704 * 16 pvs linked to from this page. This count may
5705 * be changed upwards or downwards in the future; it
5706 * is only necessary that true be returned for a small
5707 * subset of pmaps for proper page aging.
5710 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5712 struct md_page *pvh;
5713 struct rwlock *lock;
5718 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5719 ("pmap_page_exists_quick: page %p is not managed", m));
5721 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5723 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5724 if (PV_PMAP(pv) == pmap) {
5732 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5733 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5734 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5735 if (PV_PMAP(pv) == pmap) {
5749 * pmap_page_wired_mappings:
5751 * Return the number of managed mappings to the given physical page
5755 pmap_page_wired_mappings(vm_page_t m)
5757 struct rwlock *lock;
5758 struct md_page *pvh;
5762 int count, md_gen, pvh_gen;
5764 if ((m->oflags & VPO_UNMANAGED) != 0)
5766 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5770 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5772 if (!PMAP_TRYLOCK(pmap)) {
5773 md_gen = m->md.pv_gen;
5777 if (md_gen != m->md.pv_gen) {
5782 pte = pmap_pte(pmap, pv->pv_va);
5783 if ((*pte & PG_W) != 0)
5787 if ((m->flags & PG_FICTITIOUS) == 0) {
5788 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5789 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5791 if (!PMAP_TRYLOCK(pmap)) {
5792 md_gen = m->md.pv_gen;
5793 pvh_gen = pvh->pv_gen;
5797 if (md_gen != m->md.pv_gen ||
5798 pvh_gen != pvh->pv_gen) {
5803 pte = pmap_pde(pmap, pv->pv_va);
5804 if ((*pte & PG_W) != 0)
5814 * Returns TRUE if the given page is mapped individually or as part of
5815 * a 2mpage. Otherwise, returns FALSE.
5818 pmap_page_is_mapped(vm_page_t m)
5820 struct rwlock *lock;
5823 if ((m->oflags & VPO_UNMANAGED) != 0)
5825 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5827 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5828 ((m->flags & PG_FICTITIOUS) == 0 &&
5829 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5835 * Destroy all managed, non-wired mappings in the given user-space
5836 * pmap. This pmap cannot be active on any processor besides the
5839 * This function cannot be applied to the kernel pmap. Moreover, it
5840 * is not intended for general use. It is only to be used during
5841 * process termination. Consequently, it can be implemented in ways
5842 * that make it faster than pmap_remove(). First, it can more quickly
5843 * destroy mappings by iterating over the pmap's collection of PV
5844 * entries, rather than searching the page table. Second, it doesn't
5845 * have to test and clear the page table entries atomically, because
5846 * no processor is currently accessing the user address space. In
5847 * particular, a page table entry's dirty bit won't change state once
5848 * this function starts.
5850 * Although this function destroys all of the pmap's managed,
5851 * non-wired mappings, it can delay and batch the invalidation of TLB
5852 * entries without calling pmap_delayed_invl_started() and
5853 * pmap_delayed_invl_finished(). Because the pmap is not active on
5854 * any other processor, none of these TLB entries will ever be used
5855 * before their eventual invalidation. Consequently, there is no need
5856 * for either pmap_remove_all() or pmap_remove_write() to wait for
5857 * that eventual TLB invalidation.
5860 pmap_remove_pages(pmap_t pmap)
5863 pt_entry_t *pte, tpte;
5864 pt_entry_t PG_M, PG_RW, PG_V;
5865 struct spglist free;
5866 vm_page_t m, mpte, mt;
5868 struct md_page *pvh;
5869 struct pv_chunk *pc, *npc;
5870 struct rwlock *lock;
5872 uint64_t inuse, bitmask;
5873 int allfree, field, freed, idx;
5874 boolean_t superpage;
5878 * Assert that the given pmap is only active on the current
5879 * CPU. Unfortunately, we cannot block another CPU from
5880 * activating the pmap while this function is executing.
5882 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5885 cpuset_t other_cpus;
5887 other_cpus = all_cpus;
5889 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5890 CPU_AND(&other_cpus, &pmap->pm_active);
5892 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5897 PG_M = pmap_modified_bit(pmap);
5898 PG_V = pmap_valid_bit(pmap);
5899 PG_RW = pmap_rw_bit(pmap);
5903 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5906 for (field = 0; field < _NPCM; field++) {
5907 inuse = ~pc->pc_map[field] & pc_freemask[field];
5908 while (inuse != 0) {
5910 bitmask = 1UL << bit;
5911 idx = field * 64 + bit;
5912 pv = &pc->pc_pventry[idx];
5915 pte = pmap_pdpe(pmap, pv->pv_va);
5917 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5919 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5922 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5924 pte = &pte[pmap_pte_index(pv->pv_va)];
5928 * Keep track whether 'tpte' is a
5929 * superpage explicitly instead of
5930 * relying on PG_PS being set.
5932 * This is because PG_PS is numerically
5933 * identical to PG_PTE_PAT and thus a
5934 * regular page could be mistaken for
5940 if ((tpte & PG_V) == 0) {
5941 panic("bad pte va %lx pte %lx",
5946 * We cannot remove wired pages from a process' mapping at this time
5954 pa = tpte & PG_PS_FRAME;
5956 pa = tpte & PG_FRAME;
5958 m = PHYS_TO_VM_PAGE(pa);
5959 KASSERT(m->phys_addr == pa,
5960 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5961 m, (uintmax_t)m->phys_addr,
5964 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5965 m < &vm_page_array[vm_page_array_size],
5966 ("pmap_remove_pages: bad tpte %#jx",
5972 * Update the vm_page_t clean/reference bits.
5974 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5976 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5982 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5985 pc->pc_map[field] |= bitmask;
5987 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
5988 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
5989 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5991 if (TAILQ_EMPTY(&pvh->pv_list)) {
5992 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5993 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
5994 TAILQ_EMPTY(&mt->md.pv_list))
5995 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5997 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
5999 pmap_resident_count_dec(pmap, 1);
6000 KASSERT(mpte->wire_count == NPTEPG,
6001 ("pmap_remove_pages: pte page wire count error"));
6002 mpte->wire_count = 0;
6003 pmap_add_delayed_free_list(mpte, &free, FALSE);
6006 pmap_resident_count_dec(pmap, 1);
6007 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6009 if ((m->aflags & PGA_WRITEABLE) != 0 &&
6010 TAILQ_EMPTY(&m->md.pv_list) &&
6011 (m->flags & PG_FICTITIOUS) == 0) {
6012 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6013 if (TAILQ_EMPTY(&pvh->pv_list))
6014 vm_page_aflag_clear(m, PGA_WRITEABLE);
6017 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
6021 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
6022 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
6023 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
6025 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
6031 pmap_invalidate_all(pmap);
6033 vm_page_free_pages_toq(&free, true);
6037 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
6039 struct rwlock *lock;
6041 struct md_page *pvh;
6042 pt_entry_t *pte, mask;
6043 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6045 int md_gen, pvh_gen;
6049 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6052 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6054 if (!PMAP_TRYLOCK(pmap)) {
6055 md_gen = m->md.pv_gen;
6059 if (md_gen != m->md.pv_gen) {
6064 pte = pmap_pte(pmap, pv->pv_va);
6067 PG_M = pmap_modified_bit(pmap);
6068 PG_RW = pmap_rw_bit(pmap);
6069 mask |= PG_RW | PG_M;
6072 PG_A = pmap_accessed_bit(pmap);
6073 PG_V = pmap_valid_bit(pmap);
6074 mask |= PG_V | PG_A;
6076 rv = (*pte & mask) == mask;
6081 if ((m->flags & PG_FICTITIOUS) == 0) {
6082 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6083 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
6085 if (!PMAP_TRYLOCK(pmap)) {
6086 md_gen = m->md.pv_gen;
6087 pvh_gen = pvh->pv_gen;
6091 if (md_gen != m->md.pv_gen ||
6092 pvh_gen != pvh->pv_gen) {
6097 pte = pmap_pde(pmap, pv->pv_va);
6100 PG_M = pmap_modified_bit(pmap);
6101 PG_RW = pmap_rw_bit(pmap);
6102 mask |= PG_RW | PG_M;
6105 PG_A = pmap_accessed_bit(pmap);
6106 PG_V = pmap_valid_bit(pmap);
6107 mask |= PG_V | PG_A;
6109 rv = (*pte & mask) == mask;
6123 * Return whether or not the specified physical page was modified
6124 * in any physical maps.
6127 pmap_is_modified(vm_page_t m)
6130 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6131 ("pmap_is_modified: page %p is not managed", m));
6134 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6135 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
6136 * is clear, no PTEs can have PG_M set.
6138 VM_OBJECT_ASSERT_WLOCKED(m->object);
6139 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6141 return (pmap_page_test_mappings(m, FALSE, TRUE));
6145 * pmap_is_prefaultable:
6147 * Return whether or not the specified virtual address is eligible
6151 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
6154 pt_entry_t *pte, PG_V;
6157 PG_V = pmap_valid_bit(pmap);
6160 pde = pmap_pde(pmap, addr);
6161 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
6162 pte = pmap_pde_to_pte(pde, addr);
6163 rv = (*pte & PG_V) == 0;
6170 * pmap_is_referenced:
6172 * Return whether or not the specified physical page was referenced
6173 * in any physical maps.
6176 pmap_is_referenced(vm_page_t m)
6179 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6180 ("pmap_is_referenced: page %p is not managed", m));
6181 return (pmap_page_test_mappings(m, TRUE, FALSE));
6185 * Clear the write and modified bits in each of the given page's mappings.
6188 pmap_remove_write(vm_page_t m)
6190 struct md_page *pvh;
6192 struct rwlock *lock;
6193 pv_entry_t next_pv, pv;
6195 pt_entry_t oldpte, *pte, PG_M, PG_RW;
6197 int pvh_gen, md_gen;
6199 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6200 ("pmap_remove_write: page %p is not managed", m));
6203 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6204 * set by another thread while the object is locked. Thus,
6205 * if PGA_WRITEABLE is clear, no page table entries need updating.
6207 VM_OBJECT_ASSERT_WLOCKED(m->object);
6208 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6210 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6211 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6212 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6215 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6217 if (!PMAP_TRYLOCK(pmap)) {
6218 pvh_gen = pvh->pv_gen;
6222 if (pvh_gen != pvh->pv_gen) {
6228 PG_RW = pmap_rw_bit(pmap);
6230 pde = pmap_pde(pmap, va);
6231 if ((*pde & PG_RW) != 0)
6232 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6233 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6234 ("inconsistent pv lock %p %p for page %p",
6235 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6238 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6240 if (!PMAP_TRYLOCK(pmap)) {
6241 pvh_gen = pvh->pv_gen;
6242 md_gen = m->md.pv_gen;
6246 if (pvh_gen != pvh->pv_gen ||
6247 md_gen != m->md.pv_gen) {
6253 PG_M = pmap_modified_bit(pmap);
6254 PG_RW = pmap_rw_bit(pmap);
6255 pde = pmap_pde(pmap, pv->pv_va);
6256 KASSERT((*pde & PG_PS) == 0,
6257 ("pmap_remove_write: found a 2mpage in page %p's pv list",
6259 pte = pmap_pde_to_pte(pde, pv->pv_va);
6262 if (oldpte & PG_RW) {
6263 if (!atomic_cmpset_long(pte, oldpte, oldpte &
6266 if ((oldpte & PG_M) != 0)
6268 pmap_invalidate_page(pmap, pv->pv_va);
6273 vm_page_aflag_clear(m, PGA_WRITEABLE);
6274 pmap_delayed_invl_wait(m);
6277 static __inline boolean_t
6278 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
6281 if (!pmap_emulate_ad_bits(pmap))
6284 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
6287 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
6288 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
6289 * if the EPT_PG_WRITE bit is set.
6291 if ((pte & EPT_PG_WRITE) != 0)
6295 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
6297 if ((pte & EPT_PG_EXECUTE) == 0 ||
6298 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
6305 * pmap_ts_referenced:
6307 * Return a count of reference bits for a page, clearing those bits.
6308 * It is not necessary for every reference bit to be cleared, but it
6309 * is necessary that 0 only be returned when there are truly no
6310 * reference bits set.
6312 * As an optimization, update the page's dirty field if a modified bit is
6313 * found while counting reference bits. This opportunistic update can be
6314 * performed at low cost and can eliminate the need for some future calls
6315 * to pmap_is_modified(). However, since this function stops after
6316 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
6317 * dirty pages. Those dirty pages will only be detected by a future call
6318 * to pmap_is_modified().
6320 * A DI block is not needed within this function, because
6321 * invalidations are performed before the PV list lock is
6325 pmap_ts_referenced(vm_page_t m)
6327 struct md_page *pvh;
6330 struct rwlock *lock;
6331 pd_entry_t oldpde, *pde;
6332 pt_entry_t *pte, PG_A, PG_M, PG_RW;
6335 int cleared, md_gen, not_cleared, pvh_gen;
6336 struct spglist free;
6339 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6340 ("pmap_ts_referenced: page %p is not managed", m));
6343 pa = VM_PAGE_TO_PHYS(m);
6344 lock = PHYS_TO_PV_LIST_LOCK(pa);
6345 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
6349 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6350 goto small_mappings;
6356 if (!PMAP_TRYLOCK(pmap)) {
6357 pvh_gen = pvh->pv_gen;
6361 if (pvh_gen != pvh->pv_gen) {
6366 PG_A = pmap_accessed_bit(pmap);
6367 PG_M = pmap_modified_bit(pmap);
6368 PG_RW = pmap_rw_bit(pmap);
6370 pde = pmap_pde(pmap, pv->pv_va);
6372 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6374 * Although "oldpde" is mapping a 2MB page, because
6375 * this function is called at a 4KB page granularity,
6376 * we only update the 4KB page under test.
6380 if ((oldpde & PG_A) != 0) {
6382 * Since this reference bit is shared by 512 4KB
6383 * pages, it should not be cleared every time it is
6384 * tested. Apply a simple "hash" function on the
6385 * physical page number, the virtual superpage number,
6386 * and the pmap address to select one 4KB page out of
6387 * the 512 on which testing the reference bit will
6388 * result in clearing that reference bit. This
6389 * function is designed to avoid the selection of the
6390 * same 4KB page for every 2MB page mapping.
6392 * On demotion, a mapping that hasn't been referenced
6393 * is simply destroyed. To avoid the possibility of a
6394 * subsequent page fault on a demoted wired mapping,
6395 * always leave its reference bit set. Moreover,
6396 * since the superpage is wired, the current state of
6397 * its reference bit won't affect page replacement.
6399 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
6400 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
6401 (oldpde & PG_W) == 0) {
6402 if (safe_to_clear_referenced(pmap, oldpde)) {
6403 atomic_clear_long(pde, PG_A);
6404 pmap_invalidate_page(pmap, pv->pv_va);
6406 } else if (pmap_demote_pde_locked(pmap, pde,
6407 pv->pv_va, &lock)) {
6409 * Remove the mapping to a single page
6410 * so that a subsequent access may
6411 * repromote. Since the underlying
6412 * page table page is fully populated,
6413 * this removal never frees a page
6417 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6419 pte = pmap_pde_to_pte(pde, va);
6420 pmap_remove_pte(pmap, pte, va, *pde,
6422 pmap_invalidate_page(pmap, va);
6428 * The superpage mapping was removed
6429 * entirely and therefore 'pv' is no
6437 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6438 ("inconsistent pv lock %p %p for page %p",
6439 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6444 /* Rotate the PV list if it has more than one entry. */
6445 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6446 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6447 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6450 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6452 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6454 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6461 if (!PMAP_TRYLOCK(pmap)) {
6462 pvh_gen = pvh->pv_gen;
6463 md_gen = m->md.pv_gen;
6467 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6472 PG_A = pmap_accessed_bit(pmap);
6473 PG_M = pmap_modified_bit(pmap);
6474 PG_RW = pmap_rw_bit(pmap);
6475 pde = pmap_pde(pmap, pv->pv_va);
6476 KASSERT((*pde & PG_PS) == 0,
6477 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6479 pte = pmap_pde_to_pte(pde, pv->pv_va);
6480 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6482 if ((*pte & PG_A) != 0) {
6483 if (safe_to_clear_referenced(pmap, *pte)) {
6484 atomic_clear_long(pte, PG_A);
6485 pmap_invalidate_page(pmap, pv->pv_va);
6487 } else if ((*pte & PG_W) == 0) {
6489 * Wired pages cannot be paged out so
6490 * doing accessed bit emulation for
6491 * them is wasted effort. We do the
6492 * hard work for unwired pages only.
6494 pmap_remove_pte(pmap, pte, pv->pv_va,
6495 *pde, &free, &lock);
6496 pmap_invalidate_page(pmap, pv->pv_va);
6501 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6502 ("inconsistent pv lock %p %p for page %p",
6503 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6508 /* Rotate the PV list if it has more than one entry. */
6509 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6510 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6511 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6514 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6515 not_cleared < PMAP_TS_REFERENCED_MAX);
6518 vm_page_free_pages_toq(&free, true);
6519 return (cleared + not_cleared);
6523 * Apply the given advice to the specified range of addresses within the
6524 * given pmap. Depending on the advice, clear the referenced and/or
6525 * modified flags in each mapping and set the mapped page's dirty field.
6528 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6530 struct rwlock *lock;
6531 pml4_entry_t *pml4e;
6533 pd_entry_t oldpde, *pde;
6534 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6535 vm_offset_t va, va_next;
6537 boolean_t anychanged;
6539 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6543 * A/D bit emulation requires an alternate code path when clearing
6544 * the modified and accessed bits below. Since this function is
6545 * advisory in nature we skip it entirely for pmaps that require
6546 * A/D bit emulation.
6548 if (pmap_emulate_ad_bits(pmap))
6551 PG_A = pmap_accessed_bit(pmap);
6552 PG_G = pmap_global_bit(pmap);
6553 PG_M = pmap_modified_bit(pmap);
6554 PG_V = pmap_valid_bit(pmap);
6555 PG_RW = pmap_rw_bit(pmap);
6557 pmap_delayed_invl_started();
6559 for (; sva < eva; sva = va_next) {
6560 pml4e = pmap_pml4e(pmap, sva);
6561 if ((*pml4e & PG_V) == 0) {
6562 va_next = (sva + NBPML4) & ~PML4MASK;
6567 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6568 if ((*pdpe & PG_V) == 0) {
6569 va_next = (sva + NBPDP) & ~PDPMASK;
6574 va_next = (sva + NBPDR) & ~PDRMASK;
6577 pde = pmap_pdpe_to_pde(pdpe, sva);
6579 if ((oldpde & PG_V) == 0)
6581 else if ((oldpde & PG_PS) != 0) {
6582 if ((oldpde & PG_MANAGED) == 0)
6585 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6590 * The large page mapping was destroyed.
6596 * Unless the page mappings are wired, remove the
6597 * mapping to a single page so that a subsequent
6598 * access may repromote. Since the underlying page
6599 * table page is fully populated, this removal never
6600 * frees a page table page.
6602 if ((oldpde & PG_W) == 0) {
6603 pte = pmap_pde_to_pte(pde, sva);
6604 KASSERT((*pte & PG_V) != 0,
6605 ("pmap_advise: invalid PTE"));
6606 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6616 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6618 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6620 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6621 if (advice == MADV_DONTNEED) {
6623 * Future calls to pmap_is_modified()
6624 * can be avoided by making the page
6627 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6630 atomic_clear_long(pte, PG_M | PG_A);
6631 } else if ((*pte & PG_A) != 0)
6632 atomic_clear_long(pte, PG_A);
6636 if ((*pte & PG_G) != 0) {
6643 if (va != va_next) {
6644 pmap_invalidate_range(pmap, va, sva);
6649 pmap_invalidate_range(pmap, va, sva);
6652 pmap_invalidate_all(pmap);
6654 pmap_delayed_invl_finished();
6658 * Clear the modify bits on the specified physical page.
6661 pmap_clear_modify(vm_page_t m)
6663 struct md_page *pvh;
6665 pv_entry_t next_pv, pv;
6666 pd_entry_t oldpde, *pde;
6667 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6668 struct rwlock *lock;
6670 int md_gen, pvh_gen;
6672 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6673 ("pmap_clear_modify: page %p is not managed", m));
6674 VM_OBJECT_ASSERT_WLOCKED(m->object);
6675 KASSERT(!vm_page_xbusied(m),
6676 ("pmap_clear_modify: page %p is exclusive busied", m));
6679 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6680 * If the object containing the page is locked and the page is not
6681 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6683 if ((m->aflags & PGA_WRITEABLE) == 0)
6685 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6686 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6687 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6690 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6692 if (!PMAP_TRYLOCK(pmap)) {
6693 pvh_gen = pvh->pv_gen;
6697 if (pvh_gen != pvh->pv_gen) {
6702 PG_M = pmap_modified_bit(pmap);
6703 PG_V = pmap_valid_bit(pmap);
6704 PG_RW = pmap_rw_bit(pmap);
6706 pde = pmap_pde(pmap, va);
6708 if ((oldpde & PG_RW) != 0) {
6709 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6710 if ((oldpde & PG_W) == 0) {
6712 * Write protect the mapping to a
6713 * single page so that a subsequent
6714 * write access may repromote.
6716 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6718 pte = pmap_pde_to_pte(pde, va);
6720 if ((oldpte & PG_V) != 0) {
6721 while (!atomic_cmpset_long(pte,
6723 oldpte & ~(PG_M | PG_RW)))
6726 pmap_invalidate_page(pmap, va);
6733 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6735 if (!PMAP_TRYLOCK(pmap)) {
6736 md_gen = m->md.pv_gen;
6737 pvh_gen = pvh->pv_gen;
6741 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6746 PG_M = pmap_modified_bit(pmap);
6747 PG_RW = pmap_rw_bit(pmap);
6748 pde = pmap_pde(pmap, pv->pv_va);
6749 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6750 " a 2mpage in page %p's pv list", m));
6751 pte = pmap_pde_to_pte(pde, pv->pv_va);
6752 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6753 atomic_clear_long(pte, PG_M);
6754 pmap_invalidate_page(pmap, pv->pv_va);
6762 * Miscellaneous support routines follow
6765 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6766 static __inline void
6767 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6772 * The cache mode bits are all in the low 32-bits of the
6773 * PTE, so we can just spin on updating the low 32-bits.
6776 opte = *(u_int *)pte;
6777 npte = opte & ~mask;
6779 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6782 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6783 static __inline void
6784 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6789 * The cache mode bits are all in the low 32-bits of the
6790 * PDE, so we can just spin on updating the low 32-bits.
6793 opde = *(u_int *)pde;
6794 npde = opde & ~mask;
6796 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6800 * Map a set of physical memory pages into the kernel virtual
6801 * address space. Return a pointer to where it is mapped. This
6802 * routine is intended to be used for mapping device memory,
6806 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6808 struct pmap_preinit_mapping *ppim;
6809 vm_offset_t va, offset;
6813 offset = pa & PAGE_MASK;
6814 size = round_page(offset + size);
6815 pa = trunc_page(pa);
6817 if (!pmap_initialized) {
6819 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6820 ppim = pmap_preinit_mapping + i;
6821 if (ppim->va == 0) {
6825 ppim->va = virtual_avail;
6826 virtual_avail += size;
6832 panic("%s: too many preinit mappings", __func__);
6835 * If we have a preinit mapping, re-use it.
6837 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6838 ppim = pmap_preinit_mapping + i;
6839 if (ppim->pa == pa && ppim->sz == size &&
6841 return ((void *)(ppim->va + offset));
6844 * If the specified range of physical addresses fits within
6845 * the direct map window, use the direct map.
6847 if (pa < dmaplimit && pa + size < dmaplimit) {
6848 va = PHYS_TO_DMAP(pa);
6849 if (!pmap_change_attr(va, size, mode))
6850 return ((void *)(va + offset));
6852 va = kva_alloc(size);
6854 panic("%s: Couldn't allocate KVA", __func__);
6856 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6857 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6858 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6859 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6860 return ((void *)(va + offset));
6864 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6867 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6871 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6874 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6878 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6880 struct pmap_preinit_mapping *ppim;
6884 /* If we gave a direct map region in pmap_mapdev, do nothing */
6885 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6887 offset = va & PAGE_MASK;
6888 size = round_page(offset + size);
6889 va = trunc_page(va);
6890 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6891 ppim = pmap_preinit_mapping + i;
6892 if (ppim->va == va && ppim->sz == size) {
6893 if (pmap_initialized)
6899 if (va + size == virtual_avail)
6904 if (pmap_initialized)
6909 * Tries to demote a 1GB page mapping.
6912 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6914 pdp_entry_t newpdpe, oldpdpe;
6915 pd_entry_t *firstpde, newpde, *pde;
6916 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6920 PG_A = pmap_accessed_bit(pmap);
6921 PG_M = pmap_modified_bit(pmap);
6922 PG_V = pmap_valid_bit(pmap);
6923 PG_RW = pmap_rw_bit(pmap);
6925 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6927 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6928 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6929 if ((pdpg = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6930 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6931 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6932 " in pmap %p", va, pmap);
6935 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
6936 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
6937 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6938 KASSERT((oldpdpe & PG_A) != 0,
6939 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6940 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6941 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
6945 * Initialize the page directory page.
6947 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
6953 * Demote the mapping.
6958 * Invalidate a stale recursive mapping of the page directory page.
6960 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
6962 pmap_pdpe_demotions++;
6963 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
6964 " in pmap %p", va, pmap);
6969 * Sets the memory attribute for the specified page.
6972 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6975 m->md.pat_mode = ma;
6978 * If "m" is a normal page, update its direct mapping. This update
6979 * can be relied upon to perform any cache operations that are
6980 * required for data coherence.
6982 if ((m->flags & PG_FICTITIOUS) == 0 &&
6983 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6985 panic("memory attribute change on the direct map failed");
6989 * Changes the specified virtual address range's memory type to that given by
6990 * the parameter "mode". The specified virtual address range must be
6991 * completely contained within either the direct map or the kernel map. If
6992 * the virtual address range is contained within the kernel map, then the
6993 * memory type for each of the corresponding ranges of the direct map is also
6994 * changed. (The corresponding ranges of the direct map are those ranges that
6995 * map the same physical pages as the specified virtual address range.) These
6996 * changes to the direct map are necessary because Intel describes the
6997 * behavior of their processors as "undefined" if two or more mappings to the
6998 * same physical page have different memory types.
7000 * Returns zero if the change completed successfully, and either EINVAL or
7001 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
7002 * of the virtual address range was not mapped, and ENOMEM is returned if
7003 * there was insufficient memory available to complete the change. In the
7004 * latter case, the memory type may have been changed on some part of the
7005 * virtual address range or the direct map.
7008 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
7012 PMAP_LOCK(kernel_pmap);
7013 error = pmap_change_attr_locked(va, size, mode);
7014 PMAP_UNLOCK(kernel_pmap);
7019 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
7021 vm_offset_t base, offset, tmpva;
7022 vm_paddr_t pa_start, pa_end, pa_end1;
7026 int cache_bits_pte, cache_bits_pde, error;
7029 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
7030 base = trunc_page(va);
7031 offset = va & PAGE_MASK;
7032 size = round_page(offset + size);
7035 * Only supported on kernel virtual addresses, including the direct
7036 * map but excluding the recursive map.
7038 if (base < DMAP_MIN_ADDRESS)
7041 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
7042 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
7046 * Pages that aren't mapped aren't supported. Also break down 2MB pages
7047 * into 4KB pages if required.
7049 for (tmpva = base; tmpva < base + size; ) {
7050 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7051 if (pdpe == NULL || *pdpe == 0)
7053 if (*pdpe & PG_PS) {
7055 * If the current 1GB page already has the required
7056 * memory type, then we need not demote this page. Just
7057 * increment tmpva to the next 1GB page frame.
7059 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
7060 tmpva = trunc_1gpage(tmpva) + NBPDP;
7065 * If the current offset aligns with a 1GB page frame
7066 * and there is at least 1GB left within the range, then
7067 * we need not break down this page into 2MB pages.
7069 if ((tmpva & PDPMASK) == 0 &&
7070 tmpva + PDPMASK < base + size) {
7074 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
7077 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7082 * If the current 2MB page already has the required
7083 * memory type, then we need not demote this page. Just
7084 * increment tmpva to the next 2MB page frame.
7086 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
7087 tmpva = trunc_2mpage(tmpva) + NBPDR;
7092 * If the current offset aligns with a 2MB page frame
7093 * and there is at least 2MB left within the range, then
7094 * we need not break down this page into 4KB pages.
7096 if ((tmpva & PDRMASK) == 0 &&
7097 tmpva + PDRMASK < base + size) {
7101 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
7104 pte = pmap_pde_to_pte(pde, tmpva);
7112 * Ok, all the pages exist, so run through them updating their
7113 * cache mode if required.
7115 pa_start = pa_end = 0;
7116 for (tmpva = base; tmpva < base + size; ) {
7117 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7118 if (*pdpe & PG_PS) {
7119 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
7120 pmap_pde_attr(pdpe, cache_bits_pde,
7124 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7125 (*pdpe & PG_PS_FRAME) < dmaplimit) {
7126 if (pa_start == pa_end) {
7127 /* Start physical address run. */
7128 pa_start = *pdpe & PG_PS_FRAME;
7129 pa_end = pa_start + NBPDP;
7130 } else if (pa_end == (*pdpe & PG_PS_FRAME))
7133 /* Run ended, update direct map. */
7134 error = pmap_change_attr_locked(
7135 PHYS_TO_DMAP(pa_start),
7136 pa_end - pa_start, mode);
7139 /* Start physical address run. */
7140 pa_start = *pdpe & PG_PS_FRAME;
7141 pa_end = pa_start + NBPDP;
7144 tmpva = trunc_1gpage(tmpva) + NBPDP;
7147 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7149 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
7150 pmap_pde_attr(pde, cache_bits_pde,
7154 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7155 (*pde & PG_PS_FRAME) < dmaplimit) {
7156 if (pa_start == pa_end) {
7157 /* Start physical address run. */
7158 pa_start = *pde & PG_PS_FRAME;
7159 pa_end = pa_start + NBPDR;
7160 } else if (pa_end == (*pde & PG_PS_FRAME))
7163 /* Run ended, update direct map. */
7164 error = pmap_change_attr_locked(
7165 PHYS_TO_DMAP(pa_start),
7166 pa_end - pa_start, mode);
7169 /* Start physical address run. */
7170 pa_start = *pde & PG_PS_FRAME;
7171 pa_end = pa_start + NBPDR;
7174 tmpva = trunc_2mpage(tmpva) + NBPDR;
7176 pte = pmap_pde_to_pte(pde, tmpva);
7177 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
7178 pmap_pte_attr(pte, cache_bits_pte,
7182 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7183 (*pte & PG_FRAME) < dmaplimit) {
7184 if (pa_start == pa_end) {
7185 /* Start physical address run. */
7186 pa_start = *pte & PG_FRAME;
7187 pa_end = pa_start + PAGE_SIZE;
7188 } else if (pa_end == (*pte & PG_FRAME))
7189 pa_end += PAGE_SIZE;
7191 /* Run ended, update direct map. */
7192 error = pmap_change_attr_locked(
7193 PHYS_TO_DMAP(pa_start),
7194 pa_end - pa_start, mode);
7197 /* Start physical address run. */
7198 pa_start = *pte & PG_FRAME;
7199 pa_end = pa_start + PAGE_SIZE;
7205 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
7206 pa_end1 = MIN(pa_end, dmaplimit);
7207 if (pa_start != pa_end1)
7208 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
7209 pa_end1 - pa_start, mode);
7213 * Flush CPU caches if required to make sure any data isn't cached that
7214 * shouldn't be, etc.
7217 pmap_invalidate_range(kernel_pmap, base, tmpva);
7218 pmap_invalidate_cache_range(base, tmpva, FALSE);
7224 * Demotes any mapping within the direct map region that covers more than the
7225 * specified range of physical addresses. This range's size must be a power
7226 * of two and its starting address must be a multiple of its size. Since the
7227 * demotion does not change any attributes of the mapping, a TLB invalidation
7228 * is not mandatory. The caller may, however, request a TLB invalidation.
7231 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
7240 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
7241 KASSERT((base & (len - 1)) == 0,
7242 ("pmap_demote_DMAP: base is not a multiple of len"));
7243 if (len < NBPDP && base < dmaplimit) {
7244 va = PHYS_TO_DMAP(base);
7246 PMAP_LOCK(kernel_pmap);
7247 pdpe = pmap_pdpe(kernel_pmap, va);
7248 if ((*pdpe & X86_PG_V) == 0)
7249 panic("pmap_demote_DMAP: invalid PDPE");
7250 if ((*pdpe & PG_PS) != 0) {
7251 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
7252 panic("pmap_demote_DMAP: PDPE failed");
7256 pde = pmap_pdpe_to_pde(pdpe, va);
7257 if ((*pde & X86_PG_V) == 0)
7258 panic("pmap_demote_DMAP: invalid PDE");
7259 if ((*pde & PG_PS) != 0) {
7260 if (!pmap_demote_pde(kernel_pmap, pde, va))
7261 panic("pmap_demote_DMAP: PDE failed");
7265 if (changed && invalidate)
7266 pmap_invalidate_page(kernel_pmap, va);
7267 PMAP_UNLOCK(kernel_pmap);
7272 * perform the pmap work for mincore
7275 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
7278 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
7282 PG_A = pmap_accessed_bit(pmap);
7283 PG_M = pmap_modified_bit(pmap);
7284 PG_V = pmap_valid_bit(pmap);
7285 PG_RW = pmap_rw_bit(pmap);
7289 pdep = pmap_pde(pmap, addr);
7290 if (pdep != NULL && (*pdep & PG_V)) {
7291 if (*pdep & PG_PS) {
7293 /* Compute the physical address of the 4KB page. */
7294 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
7296 val = MINCORE_SUPER;
7298 pte = *pmap_pde_to_pte(pdep, addr);
7299 pa = pte & PG_FRAME;
7307 if ((pte & PG_V) != 0) {
7308 val |= MINCORE_INCORE;
7309 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7310 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
7311 if ((pte & PG_A) != 0)
7312 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
7314 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
7315 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
7316 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
7317 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
7318 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
7321 PA_UNLOCK_COND(*locked_pa);
7327 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
7329 uint32_t gen, new_gen, pcid_next;
7331 CRITICAL_ASSERT(curthread);
7332 gen = PCPU_GET(pcid_gen);
7333 if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN)
7334 return (pti ? 0 : CR3_PCID_SAVE);
7335 if (pmap->pm_pcids[cpuid].pm_gen == gen)
7336 return (CR3_PCID_SAVE);
7337 pcid_next = PCPU_GET(pcid_next);
7338 KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
7339 (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
7340 ("cpu %d pcid_next %#x", cpuid, pcid_next));
7341 if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
7342 (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
7346 PCPU_SET(pcid_gen, new_gen);
7347 pcid_next = PMAP_PCID_KERN + 1;
7351 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
7352 pmap->pm_pcids[cpuid].pm_gen = new_gen;
7353 PCPU_SET(pcid_next, pcid_next + 1);
7358 pmap_activate_sw(struct thread *td)
7360 pmap_t oldpmap, pmap;
7361 struct invpcid_descr d;
7362 uint64_t cached, cr3, kcr3, kern_pti_cached, ucr3;
7366 oldpmap = PCPU_GET(curpmap);
7367 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7368 if (oldpmap == pmap)
7370 cpuid = PCPU_GET(cpuid);
7372 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7374 CPU_SET(cpuid, &pmap->pm_active);
7377 if (pmap_pcid_enabled) {
7378 cached = pmap_pcid_alloc(pmap, cpuid);
7379 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
7380 pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
7381 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
7382 pmap->pm_pcids[cpuid].pm_pcid));
7383 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
7384 pmap == kernel_pmap,
7385 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
7386 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
7389 * If the INVPCID instruction is not available,
7390 * invltlb_pcid_handler() is used for handle
7391 * invalidate_all IPI, which checks for curpmap ==
7392 * smp_tlb_pmap. Below operations sequence has a
7393 * window where %CR3 is loaded with the new pmap's
7394 * PML4 address, but curpmap value is not yet updated.
7395 * This causes invltlb IPI handler, called between the
7396 * updates, to execute as NOP, which leaves stale TLB
7399 * Note that the most typical use of
7400 * pmap_activate_sw(), from the context switch, is
7401 * immune to this race, because interrupts are
7402 * disabled (while the thread lock is owned), and IPI
7403 * happends after curpmap is updated. Protect other
7404 * callers in a similar way, by disabling interrupts
7405 * around the %cr3 register reload and curpmap
7409 rflags = intr_disable();
7411 kern_pti_cached = pti ? 0 : cached;
7412 if (!kern_pti_cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
7413 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
7416 PCPU_SET(curpmap, pmap);
7418 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid;
7419 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[cpuid].pm_pcid |
7422 if (!cached && pmap->pm_ucr3 != PMAP_NO_CR3) {
7424 * Manually invalidate translations cached
7425 * from the user page table. They are not
7426 * flushed by reload of cr3 with the kernel
7427 * page table pointer above.
7429 if (invpcid_works) {
7430 d.pcid = PMAP_PCID_USER_PT |
7431 pmap->pm_pcids[cpuid].pm_pcid;
7434 invpcid(&d, INVPCID_CTX);
7436 pmap_pti_pcid_invalidate(ucr3, kcr3);
7440 PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
7441 PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
7444 intr_restore(rflags);
7446 PCPU_INC(pm_save_cnt);
7447 } else if (cr3 != pmap->pm_cr3) {
7448 load_cr3(pmap->pm_cr3);
7449 PCPU_SET(curpmap, pmap);
7451 PCPU_SET(kcr3, pmap->pm_cr3);
7452 PCPU_SET(ucr3, pmap->pm_ucr3);
7456 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
7458 CPU_CLR(cpuid, &oldpmap->pm_active);
7463 pmap_activate(struct thread *td)
7467 pmap_activate_sw(td);
7472 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
7477 * Increase the starting virtual address of the given mapping if a
7478 * different alignment might result in more superpage mappings.
7481 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7482 vm_offset_t *addr, vm_size_t size)
7484 vm_offset_t superpage_offset;
7488 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7489 offset += ptoa(object->pg_color);
7490 superpage_offset = offset & PDRMASK;
7491 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
7492 (*addr & PDRMASK) == superpage_offset)
7494 if ((*addr & PDRMASK) < superpage_offset)
7495 *addr = (*addr & ~PDRMASK) + superpage_offset;
7497 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
7501 static unsigned long num_dirty_emulations;
7502 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
7503 &num_dirty_emulations, 0, NULL);
7505 static unsigned long num_accessed_emulations;
7506 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
7507 &num_accessed_emulations, 0, NULL);
7509 static unsigned long num_superpage_accessed_emulations;
7510 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7511 &num_superpage_accessed_emulations, 0, NULL);
7513 static unsigned long ad_emulation_superpage_promotions;
7514 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7515 &ad_emulation_superpage_promotions, 0, NULL);
7516 #endif /* INVARIANTS */
7519 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7522 struct rwlock *lock;
7523 #if VM_NRESERVLEVEL > 0
7527 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7529 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7530 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7532 if (!pmap_emulate_ad_bits(pmap))
7535 PG_A = pmap_accessed_bit(pmap);
7536 PG_M = pmap_modified_bit(pmap);
7537 PG_V = pmap_valid_bit(pmap);
7538 PG_RW = pmap_rw_bit(pmap);
7544 pde = pmap_pde(pmap, va);
7545 if (pde == NULL || (*pde & PG_V) == 0)
7548 if ((*pde & PG_PS) != 0) {
7549 if (ftype == VM_PROT_READ) {
7551 atomic_add_long(&num_superpage_accessed_emulations, 1);
7559 pte = pmap_pde_to_pte(pde, va);
7560 if ((*pte & PG_V) == 0)
7563 if (ftype == VM_PROT_WRITE) {
7564 if ((*pte & PG_RW) == 0)
7567 * Set the modified and accessed bits simultaneously.
7569 * Intel EPT PTEs that do software emulation of A/D bits map
7570 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7571 * An EPT misconfiguration is triggered if the PTE is writable
7572 * but not readable (WR=10). This is avoided by setting PG_A
7573 * and PG_M simultaneously.
7575 *pte |= PG_M | PG_A;
7580 #if VM_NRESERVLEVEL > 0
7581 /* try to promote the mapping */
7582 if (va < VM_MAXUSER_ADDRESS)
7583 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7587 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7589 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7590 pmap_ps_enabled(pmap) &&
7591 (m->flags & PG_FICTITIOUS) == 0 &&
7592 vm_reserv_level_iffullpop(m) == 0) {
7593 pmap_promote_pde(pmap, pde, va, &lock);
7595 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7601 if (ftype == VM_PROT_WRITE)
7602 atomic_add_long(&num_dirty_emulations, 1);
7604 atomic_add_long(&num_accessed_emulations, 1);
7606 rv = 0; /* success */
7615 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7620 pt_entry_t *pte, PG_V;
7624 PG_V = pmap_valid_bit(pmap);
7627 pml4 = pmap_pml4e(pmap, va);
7629 if ((*pml4 & PG_V) == 0)
7632 pdp = pmap_pml4e_to_pdpe(pml4, va);
7634 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7637 pde = pmap_pdpe_to_pde(pdp, va);
7639 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7642 pte = pmap_pde_to_pte(pde, va);
7651 * Get the kernel virtual address of a set of physical pages. If there are
7652 * physical addresses not covered by the DMAP perform a transient mapping
7653 * that will be removed when calling pmap_unmap_io_transient.
7655 * \param page The pages the caller wishes to obtain the virtual
7656 * address on the kernel memory map.
7657 * \param vaddr On return contains the kernel virtual memory address
7658 * of the pages passed in the page parameter.
7659 * \param count Number of pages passed in.
7660 * \param can_fault TRUE if the thread using the mapped pages can take
7661 * page faults, FALSE otherwise.
7663 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7664 * finished or FALSE otherwise.
7668 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7669 boolean_t can_fault)
7672 boolean_t needs_mapping;
7674 int cache_bits, error, i;
7677 * Allocate any KVA space that we need, this is done in a separate
7678 * loop to prevent calling vmem_alloc while pinned.
7680 needs_mapping = FALSE;
7681 for (i = 0; i < count; i++) {
7682 paddr = VM_PAGE_TO_PHYS(page[i]);
7683 if (__predict_false(paddr >= dmaplimit)) {
7684 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7685 M_BESTFIT | M_WAITOK, &vaddr[i]);
7686 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7687 needs_mapping = TRUE;
7689 vaddr[i] = PHYS_TO_DMAP(paddr);
7693 /* Exit early if everything is covered by the DMAP */
7698 * NB: The sequence of updating a page table followed by accesses
7699 * to the corresponding pages used in the !DMAP case is subject to
7700 * the situation described in the "AMD64 Architecture Programmer's
7701 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7702 * Coherency Considerations". Therefore, issuing the INVLPG right
7703 * after modifying the PTE bits is crucial.
7707 for (i = 0; i < count; i++) {
7708 paddr = VM_PAGE_TO_PHYS(page[i]);
7709 if (paddr >= dmaplimit) {
7712 * Slow path, since we can get page faults
7713 * while mappings are active don't pin the
7714 * thread to the CPU and instead add a global
7715 * mapping visible to all CPUs.
7717 pmap_qenter(vaddr[i], &page[i], 1);
7719 pte = vtopte(vaddr[i]);
7720 cache_bits = pmap_cache_bits(kernel_pmap,
7721 page[i]->md.pat_mode, 0);
7722 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7729 return (needs_mapping);
7733 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7734 boolean_t can_fault)
7741 for (i = 0; i < count; i++) {
7742 paddr = VM_PAGE_TO_PHYS(page[i]);
7743 if (paddr >= dmaplimit) {
7745 pmap_qremove(vaddr[i], 1);
7746 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7752 pmap_quick_enter_page(vm_page_t m)
7756 paddr = VM_PAGE_TO_PHYS(m);
7757 if (paddr < dmaplimit)
7758 return (PHYS_TO_DMAP(paddr));
7759 mtx_lock_spin(&qframe_mtx);
7760 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7761 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7762 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7767 pmap_quick_remove_page(vm_offset_t addr)
7772 pte_store(vtopte(qframe), 0);
7774 mtx_unlock_spin(&qframe_mtx);
7778 pmap_pti_alloc_page(void)
7782 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7783 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_NOBUSY |
7784 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
7789 pmap_pti_free_page(vm_page_t m)
7792 KASSERT(m->wire_count > 0, ("page %p not wired", m));
7793 if (!vm_page_unwire_noq(m))
7795 vm_page_free_zero(m);
7809 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
7810 VM_OBJECT_WLOCK(pti_obj);
7811 pml4_pg = pmap_pti_alloc_page();
7812 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
7813 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
7814 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
7815 pdpe = pmap_pti_pdpe(va);
7816 pmap_pti_wire_pte(pdpe);
7818 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
7819 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
7820 pmap_pti_add_kva_locked((vm_offset_t)gdt, (vm_offset_t)gdt +
7821 sizeof(struct user_segment_descriptor) * NGDT * MAXCPU, false);
7822 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
7823 sizeof(struct gate_descriptor) * NIDT, false);
7824 pmap_pti_add_kva_locked((vm_offset_t)common_tss,
7825 (vm_offset_t)common_tss + sizeof(struct amd64tss) * MAXCPU, false);
7827 /* Doublefault stack IST 1 */
7828 va = common_tss[i].tss_ist1;
7829 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7830 /* NMI stack IST 2 */
7831 va = common_tss[i].tss_ist2 + sizeof(struct nmi_pcpu);
7832 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7833 /* MC# stack IST 3 */
7834 va = common_tss[i].tss_ist3 + sizeof(struct nmi_pcpu);
7835 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7837 pmap_pti_add_kva_locked((vm_offset_t)kernphys + KERNBASE,
7838 (vm_offset_t)etext, true);
7839 pti_finalized = true;
7840 VM_OBJECT_WUNLOCK(pti_obj);
7842 SYSINIT(pmap_pti, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_pti_init, NULL);
7844 static pdp_entry_t *
7845 pmap_pti_pdpe(vm_offset_t va)
7847 pml4_entry_t *pml4e;
7850 vm_pindex_t pml4_idx;
7853 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7855 pml4_idx = pmap_pml4e_index(va);
7856 pml4e = &pti_pml4[pml4_idx];
7860 panic("pml4 alloc after finalization\n");
7861 m = pmap_pti_alloc_page();
7863 pmap_pti_free_page(m);
7864 mphys = *pml4e & ~PAGE_MASK;
7866 mphys = VM_PAGE_TO_PHYS(m);
7867 *pml4e = mphys | X86_PG_RW | X86_PG_V;
7870 mphys = *pml4e & ~PAGE_MASK;
7872 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
7877 pmap_pti_wire_pte(void *pte)
7881 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7882 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7887 pmap_pti_unwire_pde(void *pde, bool only_ref)
7891 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7892 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
7893 MPASS(m->wire_count > 0);
7894 MPASS(only_ref || m->wire_count > 1);
7895 pmap_pti_free_page(m);
7899 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
7904 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7905 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7906 MPASS(m->wire_count > 0);
7907 if (pmap_pti_free_page(m)) {
7908 pde = pmap_pti_pde(va);
7909 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
7911 pmap_pti_unwire_pde(pde, false);
7916 pmap_pti_pde(vm_offset_t va)
7924 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7926 pdpe = pmap_pti_pdpe(va);
7928 m = pmap_pti_alloc_page();
7930 pmap_pti_free_page(m);
7931 MPASS((*pdpe & X86_PG_PS) == 0);
7932 mphys = *pdpe & ~PAGE_MASK;
7934 mphys = VM_PAGE_TO_PHYS(m);
7935 *pdpe = mphys | X86_PG_RW | X86_PG_V;
7938 MPASS((*pdpe & X86_PG_PS) == 0);
7939 mphys = *pdpe & ~PAGE_MASK;
7942 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
7943 pd_idx = pmap_pde_index(va);
7949 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
7956 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7958 pde = pmap_pti_pde(va);
7959 if (unwire_pde != NULL) {
7961 pmap_pti_wire_pte(pde);
7964 m = pmap_pti_alloc_page();
7966 pmap_pti_free_page(m);
7967 MPASS((*pde & X86_PG_PS) == 0);
7968 mphys = *pde & ~(PAGE_MASK | pg_nx);
7970 mphys = VM_PAGE_TO_PHYS(m);
7971 *pde = mphys | X86_PG_RW | X86_PG_V;
7972 if (unwire_pde != NULL)
7973 *unwire_pde = false;
7976 MPASS((*pde & X86_PG_PS) == 0);
7977 mphys = *pde & ~(PAGE_MASK | pg_nx);
7980 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
7981 pte += pmap_pte_index(va);
7987 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
7991 pt_entry_t *pte, ptev;
7994 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7996 sva = trunc_page(sva);
7997 MPASS(sva > VM_MAXUSER_ADDRESS);
7998 eva = round_page(eva);
8000 for (; sva < eva; sva += PAGE_SIZE) {
8001 pte = pmap_pti_pte(sva, &unwire_pde);
8002 pa = pmap_kextract(sva);
8003 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A |
8004 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
8005 VM_MEMATTR_DEFAULT, FALSE);
8007 pte_store(pte, ptev);
8008 pmap_pti_wire_pte(pte);
8010 KASSERT(!pti_finalized,
8011 ("pti overlap after fin %#lx %#lx %#lx",
8013 KASSERT(*pte == ptev,
8014 ("pti non-identical pte after fin %#lx %#lx %#lx",
8018 pde = pmap_pti_pde(sva);
8019 pmap_pti_unwire_pde(pde, true);
8025 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
8030 VM_OBJECT_WLOCK(pti_obj);
8031 pmap_pti_add_kva_locked(sva, eva, exec);
8032 VM_OBJECT_WUNLOCK(pti_obj);
8036 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
8043 sva = rounddown2(sva, PAGE_SIZE);
8044 MPASS(sva > VM_MAXUSER_ADDRESS);
8045 eva = roundup2(eva, PAGE_SIZE);
8047 VM_OBJECT_WLOCK(pti_obj);
8048 for (va = sva; va < eva; va += PAGE_SIZE) {
8049 pte = pmap_pti_pte(va, NULL);
8050 KASSERT((*pte & X86_PG_V) != 0,
8051 ("invalid pte va %#lx pte %#lx pt %#lx", va,
8052 (u_long)pte, *pte));
8054 pmap_pti_unwire_pte(pte, va);
8056 pmap_invalidate_range(kernel_pmap, sva, eva);
8057 VM_OBJECT_WUNLOCK(pti_obj);
8060 #include "opt_ddb.h"
8062 #include <sys/kdb.h>
8063 #include <ddb/ddb.h>
8065 DB_SHOW_COMMAND(pte, pmap_print_pte)
8071 pt_entry_t *pte, PG_V;
8075 db_printf("show pte addr\n");
8078 va = (vm_offset_t)addr;
8080 if (kdb_thread != NULL)
8081 pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
8083 pmap = PCPU_GET(curpmap);
8085 PG_V = pmap_valid_bit(pmap);
8086 pml4 = pmap_pml4e(pmap, va);
8087 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
8088 if ((*pml4 & PG_V) == 0) {
8092 pdp = pmap_pml4e_to_pdpe(pml4, va);
8093 db_printf(" pdpe %#016lx", *pdp);
8094 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
8098 pde = pmap_pdpe_to_pde(pdp, va);
8099 db_printf(" pde %#016lx", *pde);
8100 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
8104 pte = pmap_pde_to_pte(pde, va);
8105 db_printf(" pte %#016lx\n", *pte);
8108 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
8113 a = (vm_paddr_t)addr;
8114 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
8116 db_printf("show phys2dmap addr\n");