2 * Copyright (c) 1991 Regents of the University of California.
4 * Copyright (c) 1994 John S. Dyson
6 * Copyright (c) 1994 David Greenman
8 * Copyright (c) 2003 Peter Wemm
10 * Copyright (c) 2005-2010 Alan L. Cox <alc@cs.rice.edu>
11 * All rights reserved.
12 * Copyright (c) 2014-2018 The FreeBSD Foundation
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 * Portions of this software were developed by
20 * Konstantin Belousov <kib@FreeBSD.org> under sponsorship from
21 * the FreeBSD Foundation.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 * must display the following acknowledgement:
33 * This product includes software developed by the University of
34 * California, Berkeley and its contributors.
35 * 4. Neither the name of the University nor the names of its contributors
36 * may be used to endorse or promote products derived from this software
37 * without specific prior written permission.
39 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
40 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
42 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
43 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
44 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
45 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
46 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
47 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
48 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * from: @(#)pmap.c 7.7 (Berkeley) 5/12/91
54 * Copyright (c) 2003 Networks Associates Technology, Inc.
55 * All rights reserved.
57 * This software was developed for the FreeBSD Project by Jake Burkholder,
58 * Safeport Network Services, and Network Associates Laboratories, the
59 * Security Research Division of Network Associates, Inc. under
60 * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
61 * CHATS research program.
63 * Redistribution and use in source and binary forms, with or without
64 * modification, are permitted provided that the following conditions
66 * 1. Redistributions of source code must retain the above copyright
67 * notice, this list of conditions and the following disclaimer.
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in the
70 * documentation and/or other materials provided with the distribution.
72 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
73 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
74 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
75 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
76 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
77 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
78 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
79 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
80 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
81 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
85 #define AMD64_NPT_AWARE
87 #include <sys/cdefs.h>
88 __FBSDID("$FreeBSD$");
91 * Manages physical address maps.
93 * Since the information managed by this module is
94 * also stored by the logical address mapping module,
95 * this module may throw away valid virtual-to-physical
96 * mappings at almost any time. However, invalidations
97 * of virtual-to-physical mappings must be done as
100 * In order to cope with hardware architectures which
101 * make virtual-to-physical map invalidates expensive,
102 * this module may delay invalidate or reduced protection
103 * operations until such time as they are actually
104 * necessary. This module is given full information as
105 * to which processors are currently using which maps,
106 * and to when physical maps must be made correct.
109 #include "opt_pmap.h"
112 #include <sys/param.h>
113 #include <sys/bitstring.h>
115 #include <sys/systm.h>
116 #include <sys/kernel.h>
118 #include <sys/lock.h>
119 #include <sys/malloc.h>
120 #include <sys/mman.h>
121 #include <sys/mutex.h>
122 #include <sys/proc.h>
123 #include <sys/rwlock.h>
125 #include <sys/turnstile.h>
126 #include <sys/vmem.h>
127 #include <sys/vmmeter.h>
128 #include <sys/sched.h>
129 #include <sys/sysctl.h>
133 #include <vm/vm_param.h>
134 #include <vm/vm_kern.h>
135 #include <vm/vm_page.h>
136 #include <vm/vm_map.h>
137 #include <vm/vm_object.h>
138 #include <vm/vm_extern.h>
139 #include <vm/vm_pageout.h>
140 #include <vm/vm_pager.h>
141 #include <vm/vm_phys.h>
142 #include <vm/vm_radix.h>
143 #include <vm/vm_reserv.h>
146 #include <machine/intr_machdep.h>
147 #include <x86/apicvar.h>
148 #include <machine/cpu.h>
149 #include <machine/cputypes.h>
150 #include <machine/md_var.h>
151 #include <machine/pcb.h>
152 #include <machine/specialreg.h>
154 #include <machine/smp.h>
156 #include <machine/tss.h>
158 static __inline boolean_t
159 pmap_type_guest(pmap_t pmap)
162 return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
165 static __inline boolean_t
166 pmap_emulate_ad_bits(pmap_t pmap)
169 return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
172 static __inline pt_entry_t
173 pmap_valid_bit(pmap_t pmap)
177 switch (pmap->pm_type) {
183 if (pmap_emulate_ad_bits(pmap))
184 mask = EPT_PG_EMUL_V;
189 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
195 static __inline pt_entry_t
196 pmap_rw_bit(pmap_t pmap)
200 switch (pmap->pm_type) {
206 if (pmap_emulate_ad_bits(pmap))
207 mask = EPT_PG_EMUL_RW;
212 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
218 static pt_entry_t pg_g;
220 static __inline pt_entry_t
221 pmap_global_bit(pmap_t pmap)
225 switch (pmap->pm_type) {
234 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
240 static __inline pt_entry_t
241 pmap_accessed_bit(pmap_t pmap)
245 switch (pmap->pm_type) {
251 if (pmap_emulate_ad_bits(pmap))
257 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
263 static __inline pt_entry_t
264 pmap_modified_bit(pmap_t pmap)
268 switch (pmap->pm_type) {
274 if (pmap_emulate_ad_bits(pmap))
280 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
286 extern struct pcpu __pcpu[];
288 #if !defined(DIAGNOSTIC)
289 #ifdef __GNUC_GNU_INLINE__
290 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
292 #define PMAP_INLINE extern inline
299 #define PV_STAT(x) do { x ; } while (0)
301 #define PV_STAT(x) do { } while (0)
304 #define pa_index(pa) ((pa) >> PDRSHIFT)
305 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
307 #define NPV_LIST_LOCKS MAXCPU
309 #define PHYS_TO_PV_LIST_LOCK(pa) \
310 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
312 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
313 struct rwlock **_lockp = (lockp); \
314 struct rwlock *_new_lock; \
316 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
317 if (_new_lock != *_lockp) { \
318 if (*_lockp != NULL) \
319 rw_wunlock(*_lockp); \
320 *_lockp = _new_lock; \
325 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
326 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
328 #define RELEASE_PV_LIST_LOCK(lockp) do { \
329 struct rwlock **_lockp = (lockp); \
331 if (*_lockp != NULL) { \
332 rw_wunlock(*_lockp); \
337 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
338 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
340 struct pmap kernel_pmap_store;
342 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
343 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
346 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
347 "Number of kernel page table pages allocated on bootup");
350 vm_paddr_t dmaplimit;
351 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
354 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
356 static int pat_works = 1;
357 SYSCTL_INT(_vm_pmap, OID_AUTO, pat_works, CTLFLAG_RD, &pat_works, 1,
358 "Is page attribute table fully functional?");
360 static int pg_ps_enabled = 1;
361 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
362 &pg_ps_enabled, 0, "Are large page mappings enabled?");
364 #define PAT_INDEX_SIZE 8
365 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
367 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
368 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
369 u_int64_t KPDPphys; /* phys addr of kernel level 3 */
370 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
372 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
373 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
374 static int ndmpdpphys; /* number of DMPDPphys pages */
376 static vm_paddr_t KERNend; /* phys addr of end of bootstrap data */
379 * pmap_mapdev support pre initialization (i.e. console)
381 #define PMAP_PREINIT_MAPPING_COUNT 8
382 static struct pmap_preinit_mapping {
387 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
388 static int pmap_initialized;
391 * Data for the pv entry allocation mechanism.
392 * Updates to pv_invl_gen are protected by the pv_list_locks[]
393 * elements, but reads are not.
395 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
396 static struct mtx pv_chunks_mutex;
397 static struct rwlock pv_list_locks[NPV_LIST_LOCKS];
398 static u_long pv_invl_gen[NPV_LIST_LOCKS];
399 static struct md_page *pv_table;
400 static struct md_page pv_dummy;
403 * All those kernel PT submaps that BSD is so fond of
405 pt_entry_t *CMAP1 = NULL;
407 static vm_offset_t qframe = 0;
408 static struct mtx qframe_mtx;
410 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
412 int pmap_pcid_enabled = 1;
413 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
414 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
415 int invpcid_works = 0;
416 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
417 "Is the invpcid instruction available ?");
420 SYSCTL_INT(_vm_pmap, OID_AUTO, pti, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
422 "Page Table Isolation enabled");
423 static vm_object_t pti_obj;
424 static pml4_entry_t *pti_pml4;
425 static vm_pindex_t pti_pg_idx;
426 static bool pti_finalized;
429 pmap_pcid_save_cnt_proc(SYSCTL_HANDLER_ARGS)
436 res += cpuid_to_pcpu[i]->pc_pm_save_cnt;
438 return (sysctl_handle_64(oidp, &res, 0, req));
440 SYSCTL_PROC(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLTYPE_U64 | CTLFLAG_RW |
441 CTLFLAG_MPSAFE, NULL, 0, pmap_pcid_save_cnt_proc, "QU",
442 "Count of saved TLB context on switch");
444 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
445 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
446 static struct mtx invl_gen_mtx;
447 static u_long pmap_invl_gen = 0;
448 /* Fake lock object to satisfy turnstiles interface. */
449 static struct lock_object invl_gen_ts = {
457 return (curthread->td_md.md_invl_gen.gen == 0);
460 #define PMAP_ASSERT_NOT_IN_DI() \
461 KASSERT(pmap_not_in_di(), ("DI already started"))
464 * Start a new Delayed Invalidation (DI) block of code, executed by
465 * the current thread. Within a DI block, the current thread may
466 * destroy both the page table and PV list entries for a mapping and
467 * then release the corresponding PV list lock before ensuring that
468 * the mapping is flushed from the TLBs of any processors with the
472 pmap_delayed_invl_started(void)
474 struct pmap_invl_gen *invl_gen;
477 invl_gen = &curthread->td_md.md_invl_gen;
478 PMAP_ASSERT_NOT_IN_DI();
479 mtx_lock(&invl_gen_mtx);
480 if (LIST_EMPTY(&pmap_invl_gen_tracker))
481 currgen = pmap_invl_gen;
483 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
484 invl_gen->gen = currgen + 1;
485 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
486 mtx_unlock(&invl_gen_mtx);
490 * Finish the DI block, previously started by the current thread. All
491 * required TLB flushes for the pages marked by
492 * pmap_delayed_invl_page() must be finished before this function is
495 * This function works by bumping the global DI generation number to
496 * the generation number of the current thread's DI, unless there is a
497 * pending DI that started earlier. In the latter case, bumping the
498 * global DI generation number would incorrectly signal that the
499 * earlier DI had finished. Instead, this function bumps the earlier
500 * DI's generation number to match the generation number of the
501 * current thread's DI.
504 pmap_delayed_invl_finished(void)
506 struct pmap_invl_gen *invl_gen, *next;
507 struct turnstile *ts;
509 invl_gen = &curthread->td_md.md_invl_gen;
510 KASSERT(invl_gen->gen != 0, ("missed invl_started"));
511 mtx_lock(&invl_gen_mtx);
512 next = LIST_NEXT(invl_gen, link);
514 turnstile_chain_lock(&invl_gen_ts);
515 ts = turnstile_lookup(&invl_gen_ts);
516 pmap_invl_gen = invl_gen->gen;
518 turnstile_broadcast(ts, TS_SHARED_QUEUE);
519 turnstile_unpend(ts, TS_SHARED_LOCK);
521 turnstile_chain_unlock(&invl_gen_ts);
523 next->gen = invl_gen->gen;
525 LIST_REMOVE(invl_gen, link);
526 mtx_unlock(&invl_gen_mtx);
531 static long invl_wait;
532 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
533 "Number of times DI invalidation blocked pmap_remove_all/write");
537 pmap_delayed_invl_genp(vm_page_t m)
540 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
544 * Ensure that all currently executing DI blocks, that need to flush
545 * TLB for the given page m, actually flushed the TLB at the time the
546 * function returned. If the page m has an empty PV list and we call
547 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
548 * valid mapping for the page m in either its page table or TLB.
550 * This function works by blocking until the global DI generation
551 * number catches up with the generation number associated with the
552 * given page m and its PV list. Since this function's callers
553 * typically own an object lock and sometimes own a page lock, it
554 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
558 pmap_delayed_invl_wait(vm_page_t m)
560 struct turnstile *ts;
563 bool accounted = false;
566 m_gen = pmap_delayed_invl_genp(m);
567 while (*m_gen > pmap_invl_gen) {
570 atomic_add_long(&invl_wait, 1);
574 ts = turnstile_trywait(&invl_gen_ts);
575 if (*m_gen > pmap_invl_gen)
576 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
578 turnstile_cancel(ts);
583 * Mark the page m's PV list as participating in the current thread's
584 * DI block. Any threads concurrently using m's PV list to remove or
585 * restrict all mappings to m will wait for the current thread's DI
586 * block to complete before proceeding.
588 * The function works by setting the DI generation number for m's PV
589 * list to at least the DI generation number of the current thread.
590 * This forces a caller of pmap_delayed_invl_wait() to block until
591 * current thread calls pmap_delayed_invl_finished().
594 pmap_delayed_invl_page(vm_page_t m)
598 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
599 gen = curthread->td_md.md_invl_gen.gen;
602 m_gen = pmap_delayed_invl_genp(m);
610 static caddr_t crashdumpmap;
613 * Internal flags for pmap_enter()'s helper functions.
615 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
616 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
618 static void free_pv_chunk(struct pv_chunk *pc);
619 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
620 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
621 static int popcnt_pc_map_pq(uint64_t *map);
622 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
623 static void reserve_pv_entries(pmap_t pmap, int needed,
624 struct rwlock **lockp);
625 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
626 struct rwlock **lockp);
627 static bool pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
628 u_int flags, struct rwlock **lockp);
629 #if VM_NRESERVLEVEL > 0
630 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
631 struct rwlock **lockp);
633 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
634 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
637 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode);
638 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
639 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
640 vm_offset_t va, struct rwlock **lockp);
641 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
643 static bool pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
644 vm_prot_t prot, struct rwlock **lockp);
645 static int pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
646 u_int flags, vm_page_t m, struct rwlock **lockp);
647 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
648 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
649 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
650 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
651 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
653 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
654 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask);
655 #if VM_NRESERVLEVEL > 0
656 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
657 struct rwlock **lockp);
659 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
661 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
662 static void pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva,
664 static pdp_entry_t *pmap_pti_pdpe(vm_offset_t va);
665 static pd_entry_t *pmap_pti_pde(vm_offset_t va);
666 static void pmap_pti_wire_pte(void *pte);
667 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
668 struct spglist *free, struct rwlock **lockp);
669 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
670 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
671 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
672 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
673 struct spglist *free);
674 static bool pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
675 pd_entry_t *pde, struct spglist *free,
676 struct rwlock **lockp);
677 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
678 vm_page_t m, struct rwlock **lockp);
679 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
681 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
683 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
684 struct rwlock **lockp);
685 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
686 struct rwlock **lockp);
687 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
688 struct rwlock **lockp);
690 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
691 struct spglist *free);
692 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
694 /********************/
695 /* Inline functions */
696 /********************/
698 /* Return a non-clipped PD index for a given VA */
699 static __inline vm_pindex_t
700 pmap_pde_pindex(vm_offset_t va)
702 return (va >> PDRSHIFT);
706 /* Return a pointer to the PML4 slot that corresponds to a VA */
707 static __inline pml4_entry_t *
708 pmap_pml4e(pmap_t pmap, vm_offset_t va)
711 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
714 /* Return a pointer to the PDP slot that corresponds to a VA */
715 static __inline pdp_entry_t *
716 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
720 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
721 return (&pdpe[pmap_pdpe_index(va)]);
724 /* Return a pointer to the PDP slot that corresponds to a VA */
725 static __inline pdp_entry_t *
726 pmap_pdpe(pmap_t pmap, vm_offset_t va)
731 PG_V = pmap_valid_bit(pmap);
732 pml4e = pmap_pml4e(pmap, va);
733 if ((*pml4e & PG_V) == 0)
735 return (pmap_pml4e_to_pdpe(pml4e, va));
738 /* Return a pointer to the PD slot that corresponds to a VA */
739 static __inline pd_entry_t *
740 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
744 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
745 return (&pde[pmap_pde_index(va)]);
748 /* Return a pointer to the PD slot that corresponds to a VA */
749 static __inline pd_entry_t *
750 pmap_pde(pmap_t pmap, vm_offset_t va)
755 PG_V = pmap_valid_bit(pmap);
756 pdpe = pmap_pdpe(pmap, va);
757 if (pdpe == NULL || (*pdpe & PG_V) == 0)
759 return (pmap_pdpe_to_pde(pdpe, va));
762 /* Return a pointer to the PT slot that corresponds to a VA */
763 static __inline pt_entry_t *
764 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
768 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
769 return (&pte[pmap_pte_index(va)]);
772 /* Return a pointer to the PT slot that corresponds to a VA */
773 static __inline pt_entry_t *
774 pmap_pte(pmap_t pmap, vm_offset_t va)
779 PG_V = pmap_valid_bit(pmap);
780 pde = pmap_pde(pmap, va);
781 if (pde == NULL || (*pde & PG_V) == 0)
783 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
784 return ((pt_entry_t *)pde);
785 return (pmap_pde_to_pte(pde, va));
789 pmap_resident_count_inc(pmap_t pmap, int count)
792 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
793 pmap->pm_stats.resident_count += count;
797 pmap_resident_count_dec(pmap_t pmap, int count)
800 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
801 KASSERT(pmap->pm_stats.resident_count >= count,
802 ("pmap %p resident count underflow %ld %d", pmap,
803 pmap->pm_stats.resident_count, count));
804 pmap->pm_stats.resident_count -= count;
807 PMAP_INLINE pt_entry_t *
808 vtopte(vm_offset_t va)
810 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
812 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
814 return (PTmap + ((va >> PAGE_SHIFT) & mask));
817 static __inline pd_entry_t *
818 vtopde(vm_offset_t va)
820 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
822 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
824 return (PDmap + ((va >> PDRSHIFT) & mask));
828 allocpages(vm_paddr_t *firstaddr, int n)
833 bzero((void *)ret, n * PAGE_SIZE);
834 *firstaddr += n * PAGE_SIZE;
838 CTASSERT(powerof2(NDMPML4E));
840 /* number of kernel PDP slots */
841 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
844 nkpt_init(vm_paddr_t addr)
851 pt_pages = howmany(addr, 1 << PDRSHIFT);
852 pt_pages += NKPDPE(pt_pages);
855 * Add some slop beyond the bare minimum required for bootstrapping
858 * This is quite important when allocating KVA for kernel modules.
859 * The modules are required to be linked in the negative 2GB of
860 * the address space. If we run out of KVA in this region then
861 * pmap_growkernel() will need to allocate page table pages to map
862 * the entire 512GB of KVA space which is an unnecessary tax on
865 * Secondly, device memory mapped as part of setting up the low-
866 * level console(s) is taken from KVA, starting at virtual_avail.
867 * This is because cninit() is called after pmap_bootstrap() but
868 * before vm_init() and pmap_init(). 20MB for a frame buffer is
871 pt_pages += 32; /* 64MB additional slop. */
877 create_pagetables(vm_paddr_t *firstaddr)
879 int i, j, ndm1g, nkpdpe;
885 /* Allocate page table pages for the direct map */
886 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
887 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
889 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
890 if (ndmpdpphys > NDMPML4E) {
892 * Each NDMPML4E allows 512 GB, so limit to that,
893 * and then readjust ndmpdp and ndmpdpphys.
895 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
896 Maxmem = atop(NDMPML4E * NBPML4);
897 ndmpdpphys = NDMPML4E;
898 ndmpdp = NDMPML4E * NPDEPG;
900 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
902 if ((amd_feature & AMDID_PAGE1GB) != 0)
903 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
905 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
906 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
909 KPML4phys = allocpages(firstaddr, 1);
910 KPDPphys = allocpages(firstaddr, NKPML4E);
913 * Allocate the initial number of kernel page table pages required to
914 * bootstrap. We defer this until after all memory-size dependent
915 * allocations are done (e.g. direct map), so that we don't have to
916 * build in too much slop in our estimate.
918 * Note that when NKPML4E > 1, we have an empty page underneath
919 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
920 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
922 nkpt_init(*firstaddr);
923 nkpdpe = NKPDPE(nkpt);
925 KPTphys = allocpages(firstaddr, nkpt);
926 KPDphys = allocpages(firstaddr, nkpdpe);
928 /* Fill in the underlying page table pages */
929 /* Nominally read-only (but really R/W) from zero to physfree */
930 /* XXX not fully used, underneath 2M pages */
931 pt_p = (pt_entry_t *)KPTphys;
932 for (i = 0; ptoa(i) < *firstaddr; i++)
933 pt_p[i] = ptoa(i) | X86_PG_RW | X86_PG_V | pg_g;
935 /* Now map the page tables at their location within PTmap */
936 pd_p = (pd_entry_t *)KPDphys;
937 for (i = 0; i < nkpt; i++)
938 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
940 /* Map from zero to end of allocations under 2M pages */
941 /* This replaces some of the KPTphys entries above */
942 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
943 /* Preset PG_M and PG_A because demotion expects it. */
944 pd_p[i] = (i << PDRSHIFT) | X86_PG_RW | X86_PG_V | PG_PS |
945 X86_PG_M | X86_PG_A | pg_g;
948 * Because we map the physical blocks in 2M pages, adjust firstaddr
949 * to record the physical blocks we've actually mapped into kernel
950 * virtual address space.
952 *firstaddr = round_2mpage(*firstaddr);
954 /* And connect up the PD to the PDP (leaving room for L4 pages) */
955 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
956 for (i = 0; i < nkpdpe; i++)
957 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
960 * Now, set up the direct map region using 2MB and/or 1GB pages. If
961 * the end of physical memory is not aligned to a 1GB page boundary,
962 * then the residual physical memory is mapped with 2MB pages. Later,
963 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
964 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
965 * that are partially used.
967 pd_p = (pd_entry_t *)DMPDphys;
968 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
969 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
970 /* Preset PG_M and PG_A because demotion expects it. */
971 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
974 pdp_p = (pdp_entry_t *)DMPDPphys;
975 for (i = 0; i < ndm1g; i++) {
976 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
977 /* Preset PG_M and PG_A because demotion expects it. */
978 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
981 for (j = 0; i < ndmpdp; i++, j++) {
982 pdp_p[i] = DMPDphys + ptoa(j);
983 pdp_p[i] |= X86_PG_RW | X86_PG_V;
986 /* And recursively map PML4 to itself in order to get PTmap */
987 p4_p = (pml4_entry_t *)KPML4phys;
988 p4_p[PML4PML4I] = KPML4phys;
989 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | pg_nx;
991 /* Connect the Direct Map slot(s) up to the PML4. */
992 for (i = 0; i < ndmpdpphys; i++) {
993 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
994 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V;
997 /* Connect the KVA slots up to the PML4 */
998 for (i = 0; i < NKPML4E; i++) {
999 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
1000 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V;
1005 * Bootstrap the system enough to run with virtual memory.
1007 * On amd64 this is called after mapping has already been enabled
1008 * and just syncs the pmap module with what has already been done.
1009 * [We can't call it easily with mapping off since the kernel is not
1010 * mapped with PA == VA, hence we would have to relocate every address
1011 * from the linked base (virtual) address "KERNBASE" to the actual
1012 * (physical) address starting relative to 0]
1015 pmap_bootstrap(vm_paddr_t *firstaddr)
1021 KERNend = *firstaddr;
1027 * Create an initial set of page tables to run the kernel in.
1029 create_pagetables(firstaddr);
1032 * Add a physical memory segment (vm_phys_seg) corresponding to the
1033 * preallocated kernel page table pages so that vm_page structures
1034 * representing these pages will be created. The vm_page structures
1035 * are required for promotion of the corresponding kernel virtual
1036 * addresses to superpage mappings.
1038 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1040 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
1042 virtual_end = VM_MAX_KERNEL_ADDRESS;
1045 /* XXX do %cr0 as well */
1046 load_cr4(rcr4() | CR4_PGE);
1047 load_cr3(KPML4phys);
1048 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1049 load_cr4(rcr4() | CR4_SMEP);
1052 * Initialize the kernel pmap (which is statically allocated).
1054 PMAP_LOCK_INIT(kernel_pmap);
1055 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1056 kernel_pmap->pm_cr3 = KPML4phys;
1057 kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
1058 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1059 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1060 kernel_pmap->pm_flags = pmap_flags;
1063 * Initialize the TLB invalidations generation number lock.
1065 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1068 * Reserve some special page table entries/VA space for temporary
1071 #define SYSMAP(c, p, v, n) \
1072 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1078 * Crashdump maps. The first page is reused as CMAP1 for the
1081 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1082 CADDR1 = crashdumpmap;
1087 * Initialize the PAT MSR.
1088 * pmap_init_pat() clears and sets CR4_PGE, which, as a
1089 * side-effect, invalidates stale PG_G TLB entries that might
1090 * have been created in our pre-boot environment.
1094 /* Initialize TLB Context Id. */
1095 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1096 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1097 /* Check for INVPCID support */
1098 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1100 for (i = 0; i < MAXCPU; i++) {
1101 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1102 kernel_pmap->pm_pcids[i].pm_gen = 1;
1104 __pcpu[0].pc_pcid_next = PMAP_PCID_KERN + 1;
1105 __pcpu[0].pc_pcid_gen = 1;
1107 * pcpu area for APs is zeroed during AP startup.
1108 * pc_pcid_next and pc_pcid_gen are initialized by AP
1109 * during pcpu setup.
1111 load_cr4(rcr4() | CR4_PCIDE);
1113 pmap_pcid_enabled = 0;
1118 * Setup the PAT MSR.
1123 int pat_table[PAT_INDEX_SIZE];
1128 /* Bail if this CPU doesn't implement PAT. */
1129 if ((cpu_feature & CPUID_PAT) == 0)
1132 /* Set default PAT index table. */
1133 for (i = 0; i < PAT_INDEX_SIZE; i++)
1135 pat_table[PAT_WRITE_BACK] = 0;
1136 pat_table[PAT_WRITE_THROUGH] = 1;
1137 pat_table[PAT_UNCACHEABLE] = 3;
1138 pat_table[PAT_WRITE_COMBINING] = 3;
1139 pat_table[PAT_WRITE_PROTECTED] = 3;
1140 pat_table[PAT_UNCACHED] = 3;
1142 /* Initialize default PAT entries. */
1143 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1144 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1145 PAT_VALUE(2, PAT_UNCACHED) |
1146 PAT_VALUE(3, PAT_UNCACHEABLE) |
1147 PAT_VALUE(4, PAT_WRITE_BACK) |
1148 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1149 PAT_VALUE(6, PAT_UNCACHED) |
1150 PAT_VALUE(7, PAT_UNCACHEABLE);
1154 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1155 * Program 5 and 6 as WP and WC.
1156 * Leave 4 and 7 as WB and UC.
1158 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1159 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1160 PAT_VALUE(6, PAT_WRITE_COMBINING);
1161 pat_table[PAT_UNCACHED] = 2;
1162 pat_table[PAT_WRITE_PROTECTED] = 5;
1163 pat_table[PAT_WRITE_COMBINING] = 6;
1166 * Just replace PAT Index 2 with WC instead of UC-.
1168 pat_msr &= ~PAT_MASK(2);
1169 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1170 pat_table[PAT_WRITE_COMBINING] = 2;
1175 load_cr4(cr4 & ~CR4_PGE);
1177 /* Disable caches (CD = 1, NW = 0). */
1179 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1181 /* Flushes caches and TLBs. */
1185 /* Update PAT and index table. */
1186 wrmsr(MSR_PAT, pat_msr);
1187 for (i = 0; i < PAT_INDEX_SIZE; i++)
1188 pat_index[i] = pat_table[i];
1190 /* Flush caches and TLBs again. */
1194 /* Restore caches and PGE. */
1200 * Initialize a vm_page's machine-dependent fields.
1203 pmap_page_init(vm_page_t m)
1206 TAILQ_INIT(&m->md.pv_list);
1207 m->md.pat_mode = PAT_WRITE_BACK;
1211 * Initialize the pmap module.
1212 * Called by vm_init, to initialize any structures that the pmap
1213 * system needs to map virtual memory.
1218 struct pmap_preinit_mapping *ppim;
1221 int error, i, pv_npg, ret, skz63;
1223 /* L1TF, reserve page @0 unconditionally */
1224 vm_page_blacklist_add(0, bootverbose);
1226 /* Detect bare-metal Skylake Server and Skylake-X. */
1227 if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
1228 CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
1230 * Skylake-X errata SKZ63. Processor May Hang When
1231 * Executing Code In an HLE Transaction Region between
1232 * 40000000H and 403FFFFFH.
1234 * Mark the pages in the range as preallocated. It
1235 * seems to be impossible to distinguish between
1236 * Skylake Server and Skylake X.
1239 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
1242 printf("SKZ63: skipping 4M RAM starting "
1243 "at physical 1G\n");
1244 for (i = 0; i < atop(0x400000); i++) {
1245 ret = vm_page_blacklist_add(0x40000000 +
1247 if (!ret && bootverbose)
1248 printf("page at %#lx already used\n",
1249 0x40000000 + ptoa(i));
1255 * Initialize the vm page array entries for the kernel pmap's
1258 PMAP_LOCK(kernel_pmap);
1259 for (i = 0; i < nkpt; i++) {
1260 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1261 KASSERT(mpte >= vm_page_array &&
1262 mpte < &vm_page_array[vm_page_array_size],
1263 ("pmap_init: page table page is out of range"));
1264 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1265 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1266 mpte->wire_count = 1;
1267 if (i << PDRSHIFT < KERNend &&
1268 pmap_insert_pt_page(kernel_pmap, mpte))
1269 panic("pmap_init: pmap_insert_pt_page failed");
1271 PMAP_UNLOCK(kernel_pmap);
1272 atomic_add_int(&vm_cnt.v_wire_count, nkpt);
1275 * If the kernel is running on a virtual machine, then it must assume
1276 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1277 * be prepared for the hypervisor changing the vendor and family that
1278 * are reported by CPUID. Consequently, the workaround for AMD Family
1279 * 10h Erratum 383 is enabled if the processor's feature set does not
1280 * include at least one feature that is only supported by older Intel
1281 * or newer AMD processors.
1283 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1284 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1285 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1287 workaround_erratum383 = 1;
1290 * Are large page mappings enabled?
1292 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1293 if (pg_ps_enabled) {
1294 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1295 ("pmap_init: can't assign to pagesizes[1]"));
1296 pagesizes[1] = NBPDR;
1300 * Initialize the pv chunk list mutex.
1302 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1305 * Initialize the pool of pv list locks.
1307 for (i = 0; i < NPV_LIST_LOCKS; i++)
1308 rw_init(&pv_list_locks[i], "pmap pv list");
1311 * Calculate the size of the pv head table for superpages.
1313 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1316 * Allocate memory for the pv head table for superpages.
1318 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1320 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1322 for (i = 0; i < pv_npg; i++)
1323 TAILQ_INIT(&pv_table[i].pv_list);
1324 TAILQ_INIT(&pv_dummy.pv_list);
1326 pmap_initialized = 1;
1327 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1328 ppim = pmap_preinit_mapping + i;
1331 /* Make the direct map consistent */
1332 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1333 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1334 ppim->sz, ppim->mode);
1338 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1339 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1342 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1343 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1344 (vmem_addr_t *)&qframe);
1346 panic("qframe allocation failed");
1349 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1350 "2MB page mapping counters");
1352 static u_long pmap_pde_demotions;
1353 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1354 &pmap_pde_demotions, 0, "2MB page demotions");
1356 static u_long pmap_pde_mappings;
1357 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1358 &pmap_pde_mappings, 0, "2MB page mappings");
1360 static u_long pmap_pde_p_failures;
1361 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1362 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1364 static u_long pmap_pde_promotions;
1365 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1366 &pmap_pde_promotions, 0, "2MB page promotions");
1368 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1369 "1GB page mapping counters");
1371 static u_long pmap_pdpe_demotions;
1372 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1373 &pmap_pdpe_demotions, 0, "1GB page demotions");
1375 /***************************************************
1376 * Low level helper routines.....
1377 ***************************************************/
1380 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1382 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1384 switch (pmap->pm_type) {
1387 /* Verify that both PAT bits are not set at the same time */
1388 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1389 ("Invalid PAT bits in entry %#lx", entry));
1391 /* Swap the PAT bits if one of them is set */
1392 if ((entry & x86_pat_bits) != 0)
1393 entry ^= x86_pat_bits;
1397 * Nothing to do - the memory attributes are represented
1398 * the same way for regular pages and superpages.
1402 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1409 * Determine the appropriate bits to set in a PTE or PDE for a specified
1413 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1415 int cache_bits, pat_flag, pat_idx;
1417 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1418 panic("Unknown caching mode %d\n", mode);
1420 switch (pmap->pm_type) {
1423 /* The PAT bit is different for PTE's and PDE's. */
1424 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1426 /* Map the caching mode to a PAT index. */
1427 pat_idx = pat_index[mode];
1429 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1432 cache_bits |= pat_flag;
1434 cache_bits |= PG_NC_PCD;
1436 cache_bits |= PG_NC_PWT;
1440 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1444 panic("unsupported pmap type %d", pmap->pm_type);
1447 return (cache_bits);
1451 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1455 switch (pmap->pm_type) {
1458 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1461 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1464 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1471 pmap_ps_enabled(pmap_t pmap)
1474 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1478 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1481 switch (pmap->pm_type) {
1488 * This is a little bogus since the generation number is
1489 * supposed to be bumped up when a region of the address
1490 * space is invalidated in the page tables.
1492 * In this case the old PDE entry is valid but yet we want
1493 * to make sure that any mappings using the old entry are
1494 * invalidated in the TLB.
1496 * The reason this works as expected is because we rendezvous
1497 * "all" host cpus and force any vcpu context to exit as a
1500 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1503 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1505 pde_store(pde, newpde);
1509 * After changing the page size for the specified virtual address in the page
1510 * table, flush the corresponding entries from the processor's TLB. Only the
1511 * calling processor's TLB is affected.
1513 * The calling thread must be pinned to a processor.
1516 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1520 if (pmap_type_guest(pmap))
1523 KASSERT(pmap->pm_type == PT_X86,
1524 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1526 PG_G = pmap_global_bit(pmap);
1528 if ((newpde & PG_PS) == 0)
1529 /* Demotion: flush a specific 2MB page mapping. */
1531 else if ((newpde & PG_G) == 0)
1533 * Promotion: flush every 4KB page mapping from the TLB
1534 * because there are too many to flush individually.
1539 * Promotion: flush every 4KB page mapping from the TLB,
1540 * including any global (PG_G) mappings.
1548 * For SMP, these functions have to use the IPI mechanism for coherence.
1550 * N.B.: Before calling any of the following TLB invalidation functions,
1551 * the calling processor must ensure that all stores updating a non-
1552 * kernel page table are globally performed. Otherwise, another
1553 * processor could cache an old, pre-update entry without being
1554 * invalidated. This can happen one of two ways: (1) The pmap becomes
1555 * active on another processor after its pm_active field is checked by
1556 * one of the following functions but before a store updating the page
1557 * table is globally performed. (2) The pmap becomes active on another
1558 * processor before its pm_active field is checked but due to
1559 * speculative loads one of the following functions stills reads the
1560 * pmap as inactive on the other processor.
1562 * The kernel page table is exempt because its pm_active field is
1563 * immutable. The kernel page table is always active on every
1568 * Interrupt the cpus that are executing in the guest context.
1569 * This will force the vcpu to exit and the cached EPT mappings
1570 * will be invalidated by the host before the next vmresume.
1572 static __inline void
1573 pmap_invalidate_ept(pmap_t pmap)
1578 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1579 ("pmap_invalidate_ept: absurd pm_active"));
1582 * The TLB mappings associated with a vcpu context are not
1583 * flushed each time a different vcpu is chosen to execute.
1585 * This is in contrast with a process's vtop mappings that
1586 * are flushed from the TLB on each context switch.
1588 * Therefore we need to do more than just a TLB shootdown on
1589 * the active cpus in 'pmap->pm_active'. To do this we keep
1590 * track of the number of invalidations performed on this pmap.
1592 * Each vcpu keeps a cache of this counter and compares it
1593 * just before a vmresume. If the counter is out-of-date an
1594 * invept will be done to flush stale mappings from the TLB.
1596 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1599 * Force the vcpu to exit and trap back into the hypervisor.
1601 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1602 ipi_selected(pmap->pm_active, ipinum);
1607 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1610 struct invpcid_descr d;
1611 uint64_t kcr3, ucr3;
1615 if (pmap_type_guest(pmap)) {
1616 pmap_invalidate_ept(pmap);
1620 KASSERT(pmap->pm_type == PT_X86,
1621 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1624 if (pmap == kernel_pmap) {
1628 cpuid = PCPU_GET(cpuid);
1629 if (pmap == PCPU_GET(curpmap)) {
1631 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1633 * Disable context switching. pm_pcid
1634 * is recalculated on switch, which
1635 * might make us use wrong pcid below.
1638 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1640 if (invpcid_works) {
1641 d.pcid = pcid | PMAP_PCID_USER_PT;
1644 invpcid(&d, INVPCID_ADDR);
1646 kcr3 = pmap->pm_cr3 | pcid |
1648 ucr3 = pmap->pm_ucr3 | pcid |
1649 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1650 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1654 } else if (pmap_pcid_enabled)
1655 pmap->pm_pcids[cpuid].pm_gen = 0;
1656 if (pmap_pcid_enabled) {
1659 pmap->pm_pcids[i].pm_gen = 0;
1663 * The fence is between stores to pm_gen and the read of
1664 * the pm_active mask. We need to ensure that it is
1665 * impossible for us to miss the bit update in pm_active
1666 * and simultaneously observe a non-zero pm_gen in
1667 * pmap_activate_sw(), otherwise TLB update is missed.
1668 * Without the fence, IA32 allows such an outcome.
1669 * Note that pm_active is updated by a locked operation,
1670 * which provides the reciprocal fence.
1672 atomic_thread_fence_seq_cst();
1674 mask = &pmap->pm_active;
1676 smp_masked_invlpg(*mask, va, pmap);
1680 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1681 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1684 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1687 struct invpcid_descr d;
1689 uint64_t kcr3, ucr3;
1693 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1694 pmap_invalidate_all(pmap);
1698 if (pmap_type_guest(pmap)) {
1699 pmap_invalidate_ept(pmap);
1703 KASSERT(pmap->pm_type == PT_X86,
1704 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1707 cpuid = PCPU_GET(cpuid);
1708 if (pmap == kernel_pmap) {
1709 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1713 if (pmap == PCPU_GET(curpmap)) {
1714 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1716 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1718 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1719 if (invpcid_works) {
1720 d.pcid = pcid | PMAP_PCID_USER_PT;
1723 for (; d.addr < eva; d.addr +=
1725 invpcid(&d, INVPCID_ADDR);
1727 kcr3 = pmap->pm_cr3 | pcid |
1729 ucr3 = pmap->pm_ucr3 | pcid |
1730 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1731 pmap_pti_pcid_invlrng(ucr3, kcr3, sva,
1736 } else if (pmap_pcid_enabled) {
1737 pmap->pm_pcids[cpuid].pm_gen = 0;
1739 if (pmap_pcid_enabled) {
1742 pmap->pm_pcids[i].pm_gen = 0;
1744 /* See the comment in pmap_invalidate_page(). */
1745 atomic_thread_fence_seq_cst();
1747 mask = &pmap->pm_active;
1749 smp_masked_invlpg_range(*mask, sva, eva, pmap);
1754 pmap_invalidate_all(pmap_t pmap)
1757 struct invpcid_descr d;
1758 uint64_t kcr3, ucr3;
1762 if (pmap_type_guest(pmap)) {
1763 pmap_invalidate_ept(pmap);
1767 KASSERT(pmap->pm_type == PT_X86,
1768 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1771 if (pmap == kernel_pmap) {
1772 if (pmap_pcid_enabled && invpcid_works) {
1773 bzero(&d, sizeof(d));
1774 invpcid(&d, INVPCID_CTXGLOB);
1780 cpuid = PCPU_GET(cpuid);
1781 if (pmap == PCPU_GET(curpmap)) {
1782 if (pmap_pcid_enabled) {
1784 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1785 if (invpcid_works) {
1789 invpcid(&d, INVPCID_CTX);
1790 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1791 d.pcid |= PMAP_PCID_USER_PT;
1792 invpcid(&d, INVPCID_CTX);
1795 kcr3 = pmap->pm_cr3 | pcid;
1796 ucr3 = pmap->pm_ucr3;
1797 if (ucr3 != PMAP_NO_CR3) {
1798 ucr3 |= pcid | PMAP_PCID_USER_PT;
1799 pmap_pti_pcid_invalidate(ucr3,
1809 } else if (pmap_pcid_enabled) {
1810 pmap->pm_pcids[cpuid].pm_gen = 0;
1812 if (pmap_pcid_enabled) {
1815 pmap->pm_pcids[i].pm_gen = 0;
1817 /* See the comment in pmap_invalidate_page(). */
1818 atomic_thread_fence_seq_cst();
1820 mask = &pmap->pm_active;
1822 smp_masked_invltlb(*mask, pmap);
1827 pmap_invalidate_cache(void)
1837 cpuset_t invalidate; /* processors that invalidate their TLB */
1842 u_int store; /* processor that updates the PDE */
1846 pmap_update_pde_action(void *arg)
1848 struct pde_action *act = arg;
1850 if (act->store == PCPU_GET(cpuid))
1851 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1855 pmap_update_pde_teardown(void *arg)
1857 struct pde_action *act = arg;
1859 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1860 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1864 * Change the page size for the specified virtual address in a way that
1865 * prevents any possibility of the TLB ever having two entries that map the
1866 * same virtual address using different page sizes. This is the recommended
1867 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1868 * machine check exception for a TLB state that is improperly diagnosed as a
1872 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1874 struct pde_action act;
1875 cpuset_t active, other_cpus;
1879 cpuid = PCPU_GET(cpuid);
1880 other_cpus = all_cpus;
1881 CPU_CLR(cpuid, &other_cpus);
1882 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1885 active = pmap->pm_active;
1887 if (CPU_OVERLAP(&active, &other_cpus)) {
1889 act.invalidate = active;
1893 act.newpde = newpde;
1894 CPU_SET(cpuid, &active);
1895 smp_rendezvous_cpus(active,
1896 smp_no_rendezvous_barrier, pmap_update_pde_action,
1897 pmap_update_pde_teardown, &act);
1899 pmap_update_pde_store(pmap, pde, newpde);
1900 if (CPU_ISSET(cpuid, &active))
1901 pmap_update_pde_invalidate(pmap, va, newpde);
1907 * Normal, non-SMP, invalidation functions.
1910 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1912 struct invpcid_descr d;
1913 uint64_t kcr3, ucr3;
1916 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1920 KASSERT(pmap->pm_type == PT_X86,
1921 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1923 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1925 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
1926 pmap->pm_ucr3 != PMAP_NO_CR3) {
1928 pcid = pmap->pm_pcids[0].pm_pcid;
1929 if (invpcid_works) {
1930 d.pcid = pcid | PMAP_PCID_USER_PT;
1933 invpcid(&d, INVPCID_ADDR);
1935 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
1936 ucr3 = pmap->pm_ucr3 | pcid |
1937 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1938 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1942 } else if (pmap_pcid_enabled)
1943 pmap->pm_pcids[0].pm_gen = 0;
1947 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1949 struct invpcid_descr d;
1951 uint64_t kcr3, ucr3;
1953 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1957 KASSERT(pmap->pm_type == PT_X86,
1958 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1960 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1961 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1963 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
1964 pmap->pm_ucr3 != PMAP_NO_CR3) {
1966 if (invpcid_works) {
1967 d.pcid = pmap->pm_pcids[0].pm_pcid |
1971 for (; d.addr < eva; d.addr += PAGE_SIZE)
1972 invpcid(&d, INVPCID_ADDR);
1974 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].
1975 pm_pcid | CR3_PCID_SAVE;
1976 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[0].
1977 pm_pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1978 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
1982 } else if (pmap_pcid_enabled) {
1983 pmap->pm_pcids[0].pm_gen = 0;
1988 pmap_invalidate_all(pmap_t pmap)
1990 struct invpcid_descr d;
1991 uint64_t kcr3, ucr3;
1993 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1997 KASSERT(pmap->pm_type == PT_X86,
1998 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
2000 if (pmap == kernel_pmap) {
2001 if (pmap_pcid_enabled && invpcid_works) {
2002 bzero(&d, sizeof(d));
2003 invpcid(&d, INVPCID_CTXGLOB);
2007 } else if (pmap == PCPU_GET(curpmap)) {
2008 if (pmap_pcid_enabled) {
2010 if (invpcid_works) {
2011 d.pcid = pmap->pm_pcids[0].pm_pcid;
2014 invpcid(&d, INVPCID_CTX);
2015 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2016 d.pcid |= PMAP_PCID_USER_PT;
2017 invpcid(&d, INVPCID_CTX);
2020 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].pm_pcid;
2021 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2022 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[
2023 0].pm_pcid | PMAP_PCID_USER_PT;
2024 pmap_pti_pcid_invalidate(ucr3, kcr3);
2032 } else if (pmap_pcid_enabled) {
2033 pmap->pm_pcids[0].pm_gen = 0;
2038 pmap_invalidate_cache(void)
2045 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
2048 pmap_update_pde_store(pmap, pde, newpde);
2049 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
2050 pmap_update_pde_invalidate(pmap, va, newpde);
2052 pmap->pm_pcids[0].pm_gen = 0;
2057 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
2061 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
2062 * by a promotion that did not invalidate the 512 4KB page mappings
2063 * that might exist in the TLB. Consequently, at this point, the TLB
2064 * may hold both 4KB and 2MB page mappings for the address range [va,
2065 * va + NBPDR). Therefore, the entire range must be invalidated here.
2066 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
2067 * 4KB page mappings for the address range [va, va + NBPDR), and so a
2068 * single INVLPG suffices to invalidate the 2MB page mapping from the
2071 if ((pde & PG_PROMOTED) != 0)
2072 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
2074 pmap_invalidate_page(pmap, va);
2077 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
2080 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
2084 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
2086 KASSERT((sva & PAGE_MASK) == 0,
2087 ("pmap_invalidate_cache_range: sva not page-aligned"));
2088 KASSERT((eva & PAGE_MASK) == 0,
2089 ("pmap_invalidate_cache_range: eva not page-aligned"));
2092 if ((cpu_feature & CPUID_SS) != 0 && !force)
2093 ; /* If "Self Snoop" is supported and allowed, do nothing. */
2094 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
2095 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2097 * XXX: Some CPUs fault, hang, or trash the local APIC
2098 * registers if we use CLFLUSH on the local APIC
2099 * range. The local APIC is always uncached, so we
2100 * don't need to flush for that range anyway.
2102 if (pmap_kextract(sva) == lapic_paddr)
2106 * Otherwise, do per-cache line flush. Use the sfence
2107 * instruction to insure that previous stores are
2108 * included in the write-back. The processor
2109 * propagates flush to other processors in the cache
2113 for (; sva < eva; sva += cpu_clflush_line_size)
2116 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
2117 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2118 if (pmap_kextract(sva) == lapic_paddr)
2121 * Writes are ordered by CLFLUSH on Intel CPUs.
2123 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2125 for (; sva < eva; sva += cpu_clflush_line_size)
2127 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2132 * No targeted cache flush methods are supported by CPU,
2133 * or the supplied range is bigger than 2MB.
2134 * Globally invalidate cache.
2136 pmap_invalidate_cache();
2141 * Remove the specified set of pages from the data and instruction caches.
2143 * In contrast to pmap_invalidate_cache_range(), this function does not
2144 * rely on the CPU's self-snoop feature, because it is intended for use
2145 * when moving pages into a different cache domain.
2148 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
2150 vm_offset_t daddr, eva;
2154 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
2155 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
2156 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
2157 pmap_invalidate_cache();
2161 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2163 for (i = 0; i < count; i++) {
2164 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
2165 eva = daddr + PAGE_SIZE;
2166 for (; daddr < eva; daddr += cpu_clflush_line_size) {
2175 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2181 * Routine: pmap_extract
2183 * Extract the physical page address associated
2184 * with the given map/virtual_address pair.
2187 pmap_extract(pmap_t pmap, vm_offset_t va)
2191 pt_entry_t *pte, PG_V;
2195 PG_V = pmap_valid_bit(pmap);
2197 pdpe = pmap_pdpe(pmap, va);
2198 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2199 if ((*pdpe & PG_PS) != 0)
2200 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
2202 pde = pmap_pdpe_to_pde(pdpe, va);
2203 if ((*pde & PG_V) != 0) {
2204 if ((*pde & PG_PS) != 0) {
2205 pa = (*pde & PG_PS_FRAME) |
2208 pte = pmap_pde_to_pte(pde, va);
2209 pa = (*pte & PG_FRAME) |
2220 * Routine: pmap_extract_and_hold
2222 * Atomically extract and hold the physical page
2223 * with the given pmap and virtual address pair
2224 * if that mapping permits the given protection.
2227 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
2229 pd_entry_t pde, *pdep;
2230 pt_entry_t pte, PG_RW, PG_V;
2236 PG_RW = pmap_rw_bit(pmap);
2237 PG_V = pmap_valid_bit(pmap);
2240 pdep = pmap_pde(pmap, va);
2241 if (pdep != NULL && (pde = *pdep)) {
2243 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2244 if (vm_page_pa_tryrelock(pmap, (pde &
2245 PG_PS_FRAME) | (va & PDRMASK), &pa))
2247 m = PHYS_TO_VM_PAGE(pa);
2250 pte = *pmap_pde_to_pte(pdep, va);
2252 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2253 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2256 m = PHYS_TO_VM_PAGE(pa);
2268 pmap_kextract(vm_offset_t va)
2273 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2274 pa = DMAP_TO_PHYS(va);
2278 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2281 * Beware of a concurrent promotion that changes the
2282 * PDE at this point! For example, vtopte() must not
2283 * be used to access the PTE because it would use the
2284 * new PDE. It is, however, safe to use the old PDE
2285 * because the page table page is preserved by the
2288 pa = *pmap_pde_to_pte(&pde, va);
2289 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2295 /***************************************************
2296 * Low level mapping routines.....
2297 ***************************************************/
2300 * Add a wired page to the kva.
2301 * Note: not SMP coherent.
2304 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2309 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g);
2312 static __inline void
2313 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2319 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2320 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | cache_bits);
2324 * Remove a page from the kernel pagetables.
2325 * Note: not SMP coherent.
2328 pmap_kremove(vm_offset_t va)
2337 * Used to map a range of physical addresses into kernel
2338 * virtual address space.
2340 * The value passed in '*virt' is a suggested virtual address for
2341 * the mapping. Architectures which can support a direct-mapped
2342 * physical to virtual region can return the appropriate address
2343 * within that region, leaving '*virt' unchanged. Other
2344 * architectures should map the pages starting at '*virt' and
2345 * update '*virt' with the first usable address after the mapped
2349 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2351 return PHYS_TO_DMAP(start);
2356 * Add a list of wired pages to the kva
2357 * this routine is only used for temporary
2358 * kernel mappings that do not need to have
2359 * page modification or references recorded.
2360 * Note that old mappings are simply written
2361 * over. The page *must* be wired.
2362 * Note: SMP coherent. Uses a ranged shootdown IPI.
2365 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2367 pt_entry_t *endpte, oldpte, pa, *pte;
2373 endpte = pte + count;
2374 while (pte < endpte) {
2376 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2377 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2378 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2380 pte_store(pte, pa | pg_g | X86_PG_RW | X86_PG_V);
2384 if (__predict_false((oldpte & X86_PG_V) != 0))
2385 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2390 * This routine tears out page mappings from the
2391 * kernel -- it is meant only for temporary mappings.
2392 * Note: SMP coherent. Uses a ranged shootdown IPI.
2395 pmap_qremove(vm_offset_t sva, int count)
2400 while (count-- > 0) {
2401 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2405 pmap_invalidate_range(kernel_pmap, sva, va);
2408 /***************************************************
2409 * Page table page management routines.....
2410 ***************************************************/
2411 static __inline void
2412 pmap_free_zero_pages(struct spglist *free)
2417 for (count = 0; (m = SLIST_FIRST(free)) != NULL; count++) {
2418 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2419 /* Preserve the page's PG_ZERO setting. */
2420 vm_page_free_toq(m);
2422 atomic_subtract_int(&vm_cnt.v_wire_count, count);
2426 * Schedule the specified unused page table page to be freed. Specifically,
2427 * add the page to the specified list of pages that will be released to the
2428 * physical memory manager after the TLB has been updated.
2430 static __inline void
2431 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2432 boolean_t set_PG_ZERO)
2436 m->flags |= PG_ZERO;
2438 m->flags &= ~PG_ZERO;
2439 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2443 * Inserts the specified page table page into the specified pmap's collection
2444 * of idle page table pages. Each of a pmap's page table pages is responsible
2445 * for mapping a distinct range of virtual addresses. The pmap's collection is
2446 * ordered by this virtual address range.
2449 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2452 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2453 return (vm_radix_insert(&pmap->pm_root, mpte));
2457 * Removes the page table page mapping the specified virtual address from the
2458 * specified pmap's collection of idle page table pages, and returns it.
2459 * Otherwise, returns NULL if there is no page table page corresponding to the
2460 * specified virtual address.
2462 static __inline vm_page_t
2463 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
2466 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2467 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
2471 * Decrements a page table page's wire count, which is used to record the
2472 * number of valid page table entries within the page. If the wire count
2473 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2474 * page table page was unmapped and FALSE otherwise.
2476 static inline boolean_t
2477 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2481 if (m->wire_count == 0) {
2482 _pmap_unwire_ptp(pmap, va, m, free);
2489 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2492 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2494 * unmap the page table page
2496 if (m->pindex >= (NUPDE + NUPDPE)) {
2499 pml4 = pmap_pml4e(pmap, va);
2501 if (pmap->pm_pml4u != NULL && va <= VM_MAXUSER_ADDRESS) {
2502 pml4 = &pmap->pm_pml4u[pmap_pml4e_index(va)];
2505 } else if (m->pindex >= NUPDE) {
2508 pdp = pmap_pdpe(pmap, va);
2513 pd = pmap_pde(pmap, va);
2516 pmap_resident_count_dec(pmap, 1);
2517 if (m->pindex < NUPDE) {
2518 /* We just released a PT, unhold the matching PD */
2521 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2522 pmap_unwire_ptp(pmap, va, pdpg, free);
2524 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2525 /* We just released a PD, unhold the matching PDP */
2528 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2529 pmap_unwire_ptp(pmap, va, pdppg, free);
2533 * Put page on a list so that it is released after
2534 * *ALL* TLB shootdown is done
2536 pmap_add_delayed_free_list(m, free, TRUE);
2540 * After removing a page table entry, this routine is used to
2541 * conditionally free the page, and manage the hold/wire counts.
2544 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2545 struct spglist *free)
2549 if (va >= VM_MAXUSER_ADDRESS)
2551 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2552 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2553 return (pmap_unwire_ptp(pmap, va, mpte, free));
2557 pmap_pinit0(pmap_t pmap)
2561 PMAP_LOCK_INIT(pmap);
2562 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2563 pmap->pm_pml4u = NULL;
2564 pmap->pm_cr3 = KPML4phys;
2565 /* hack to keep pmap_pti_pcid_invalidate() alive */
2566 pmap->pm_ucr3 = PMAP_NO_CR3;
2567 pmap->pm_root.rt_root = 0;
2568 CPU_ZERO(&pmap->pm_active);
2569 TAILQ_INIT(&pmap->pm_pvchunk);
2570 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2571 pmap->pm_flags = pmap_flags;
2573 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2574 pmap->pm_pcids[i].pm_gen = 0;
2576 __pcpu[i].pc_kcr3 = PMAP_NO_CR3;
2577 __pcpu[i].pc_ucr3 = PMAP_NO_CR3;
2580 PCPU_SET(curpmap, kernel_pmap);
2581 pmap_activate(curthread);
2582 CPU_FILL(&kernel_pmap->pm_active);
2586 pmap_pinit_pml4(vm_page_t pml4pg)
2588 pml4_entry_t *pm_pml4;
2591 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2593 /* Wire in kernel global address entries. */
2594 for (i = 0; i < NKPML4E; i++) {
2595 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2598 for (i = 0; i < ndmpdpphys; i++) {
2599 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2603 /* install self-referential address mapping entry(s) */
2604 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2605 X86_PG_A | X86_PG_M;
2609 pmap_pinit_pml4_pti(vm_page_t pml4pg)
2611 pml4_entry_t *pm_pml4;
2614 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2615 for (i = 0; i < NPML4EPG; i++)
2616 pm_pml4[i] = pti_pml4[i];
2620 * Initialize a preallocated and zeroed pmap structure,
2621 * such as one in a vmspace structure.
2624 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2626 vm_page_t pml4pg, pml4pgu;
2627 vm_paddr_t pml4phys;
2631 * allocate the page directory page
2633 pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
2634 VM_ALLOC_WIRED | VM_ALLOC_ZERO | VM_ALLOC_WAITOK);
2636 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2637 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2639 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2640 pmap->pm_pcids[i].pm_gen = 0;
2642 pmap->pm_cr3 = PMAP_NO_CR3; /* initialize to an invalid value */
2643 pmap->pm_ucr3 = PMAP_NO_CR3;
2644 pmap->pm_pml4u = NULL;
2646 pmap->pm_type = pm_type;
2647 if ((pml4pg->flags & PG_ZERO) == 0)
2648 pagezero(pmap->pm_pml4);
2651 * Do not install the host kernel mappings in the nested page
2652 * tables. These mappings are meaningless in the guest physical
2654 * Install minimal kernel mappings in PTI case.
2656 if (pm_type == PT_X86) {
2657 pmap->pm_cr3 = pml4phys;
2658 pmap_pinit_pml4(pml4pg);
2660 pml4pgu = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2661 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2662 pmap->pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(
2663 VM_PAGE_TO_PHYS(pml4pgu));
2664 pmap_pinit_pml4_pti(pml4pgu);
2665 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pml4pgu);
2669 pmap->pm_root.rt_root = 0;
2670 CPU_ZERO(&pmap->pm_active);
2671 TAILQ_INIT(&pmap->pm_pvchunk);
2672 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2673 pmap->pm_flags = flags;
2674 pmap->pm_eptgen = 0;
2680 pmap_pinit(pmap_t pmap)
2683 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2687 * This routine is called if the desired page table page does not exist.
2689 * If page table page allocation fails, this routine may sleep before
2690 * returning NULL. It sleeps only if a lock pointer was given.
2692 * Note: If a page allocation fails at page table level two or three,
2693 * one or two pages may be held during the wait, only to be released
2694 * afterwards. This conservative approach is easily argued to avoid
2698 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2700 vm_page_t m, pdppg, pdpg;
2701 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2703 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2705 PG_A = pmap_accessed_bit(pmap);
2706 PG_M = pmap_modified_bit(pmap);
2707 PG_V = pmap_valid_bit(pmap);
2708 PG_RW = pmap_rw_bit(pmap);
2711 * Allocate a page table page.
2713 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2714 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2715 if (lockp != NULL) {
2716 RELEASE_PV_LIST_LOCK(lockp);
2718 PMAP_ASSERT_NOT_IN_DI();
2724 * Indicate the need to retry. While waiting, the page table
2725 * page may have been allocated.
2729 if ((m->flags & PG_ZERO) == 0)
2733 * Map the pagetable page into the process address space, if
2734 * it isn't already there.
2737 if (ptepindex >= (NUPDE + NUPDPE)) {
2738 pml4_entry_t *pml4, *pml4u;
2739 vm_pindex_t pml4index;
2741 /* Wire up a new PDPE page */
2742 pml4index = ptepindex - (NUPDE + NUPDPE);
2743 pml4 = &pmap->pm_pml4[pml4index];
2744 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2745 if (pmap->pm_pml4u != NULL && pml4index < NUPML4E) {
2747 * PTI: Make all user-space mappings in the
2748 * kernel-mode page table no-execute so that
2749 * we detect any programming errors that leave
2750 * the kernel-mode page table active on return
2753 if (pmap->pm_ucr3 != PMAP_NO_CR3)
2756 pml4u = &pmap->pm_pml4u[pml4index];
2757 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
2761 } else if (ptepindex >= NUPDE) {
2762 vm_pindex_t pml4index;
2763 vm_pindex_t pdpindex;
2767 /* Wire up a new PDE page */
2768 pdpindex = ptepindex - NUPDE;
2769 pml4index = pdpindex >> NPML4EPGSHIFT;
2771 pml4 = &pmap->pm_pml4[pml4index];
2772 if ((*pml4 & PG_V) == 0) {
2773 /* Have to allocate a new pdp, recurse */
2774 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2777 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2778 vm_page_free_zero(m);
2782 /* Add reference to pdp page */
2783 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2784 pdppg->wire_count++;
2786 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2788 /* Now find the pdp page */
2789 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2790 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2793 vm_pindex_t pml4index;
2794 vm_pindex_t pdpindex;
2799 /* Wire up a new PTE page */
2800 pdpindex = ptepindex >> NPDPEPGSHIFT;
2801 pml4index = pdpindex >> NPML4EPGSHIFT;
2803 /* First, find the pdp and check that its valid. */
2804 pml4 = &pmap->pm_pml4[pml4index];
2805 if ((*pml4 & PG_V) == 0) {
2806 /* Have to allocate a new pd, recurse */
2807 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2810 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2811 vm_page_free_zero(m);
2814 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2815 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2817 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2818 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2819 if ((*pdp & PG_V) == 0) {
2820 /* Have to allocate a new pd, recurse */
2821 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2824 atomic_subtract_int(&vm_cnt.v_wire_count,
2826 vm_page_free_zero(m);
2830 /* Add reference to the pd page */
2831 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2835 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2837 /* Now we know where the page directory page is */
2838 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2839 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2842 pmap_resident_count_inc(pmap, 1);
2848 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2850 vm_pindex_t pdpindex, ptepindex;
2851 pdp_entry_t *pdpe, PG_V;
2854 PG_V = pmap_valid_bit(pmap);
2857 pdpe = pmap_pdpe(pmap, va);
2858 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2859 /* Add a reference to the pd page. */
2860 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2863 /* Allocate a pd page. */
2864 ptepindex = pmap_pde_pindex(va);
2865 pdpindex = ptepindex >> NPDPEPGSHIFT;
2866 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2867 if (pdpg == NULL && lockp != NULL)
2874 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2876 vm_pindex_t ptepindex;
2877 pd_entry_t *pd, PG_V;
2880 PG_V = pmap_valid_bit(pmap);
2883 * Calculate pagetable page index
2885 ptepindex = pmap_pde_pindex(va);
2888 * Get the page directory entry
2890 pd = pmap_pde(pmap, va);
2893 * This supports switching from a 2MB page to a
2896 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2897 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2899 * Invalidation of the 2MB page mapping may have caused
2900 * the deallocation of the underlying PD page.
2907 * If the page table page is mapped, we just increment the
2908 * hold count, and activate it.
2910 if (pd != NULL && (*pd & PG_V) != 0) {
2911 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2915 * Here if the pte page isn't mapped, or if it has been
2918 m = _pmap_allocpte(pmap, ptepindex, lockp);
2919 if (m == NULL && lockp != NULL)
2926 /***************************************************
2927 * Pmap allocation/deallocation routines.
2928 ***************************************************/
2931 * Release any resources held by the given physical map.
2932 * Called when a pmap initialized by pmap_pinit is being released.
2933 * Should only be called if the map contains no valid mappings.
2936 pmap_release(pmap_t pmap)
2941 KASSERT(pmap->pm_stats.resident_count == 0,
2942 ("pmap_release: pmap resident count %ld != 0",
2943 pmap->pm_stats.resident_count));
2944 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2945 ("pmap_release: pmap has reserved page table page(s)"));
2946 KASSERT(CPU_EMPTY(&pmap->pm_active),
2947 ("releasing active pmap %p", pmap));
2949 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2951 for (i = 0; i < NKPML4E; i++) /* KVA */
2952 pmap->pm_pml4[KPML4BASE + i] = 0;
2953 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
2954 pmap->pm_pml4[DMPML4I + i] = 0;
2955 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
2958 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2959 vm_page_free_zero(m);
2961 if (pmap->pm_pml4u != NULL) {
2962 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4u));
2964 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2970 kvm_size(SYSCTL_HANDLER_ARGS)
2972 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2974 return sysctl_handle_long(oidp, &ksize, 0, req);
2976 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2977 0, 0, kvm_size, "LU", "Size of KVM");
2980 kvm_free(SYSCTL_HANDLER_ARGS)
2982 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2984 return sysctl_handle_long(oidp, &kfree, 0, req);
2986 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2987 0, 0, kvm_free, "LU", "Amount of KVM free");
2990 * grow the number of kernel page table entries, if needed
2993 pmap_growkernel(vm_offset_t addr)
2997 pd_entry_t *pde, newpdir;
3000 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
3003 * Return if "addr" is within the range of kernel page table pages
3004 * that were preallocated during pmap bootstrap. Moreover, leave
3005 * "kernel_vm_end" and the kernel page table as they were.
3007 * The correctness of this action is based on the following
3008 * argument: vm_map_insert() allocates contiguous ranges of the
3009 * kernel virtual address space. It calls this function if a range
3010 * ends after "kernel_vm_end". If the kernel is mapped between
3011 * "kernel_vm_end" and "addr", then the range cannot begin at
3012 * "kernel_vm_end". In fact, its beginning address cannot be less
3013 * than the kernel. Thus, there is no immediate need to allocate
3014 * any new kernel page table pages between "kernel_vm_end" and
3017 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
3020 addr = roundup2(addr, NBPDR);
3021 if (addr - 1 >= kernel_map->max_offset)
3022 addr = kernel_map->max_offset;
3023 while (kernel_vm_end < addr) {
3024 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
3025 if ((*pdpe & X86_PG_V) == 0) {
3026 /* We need a new PDP entry */
3027 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
3028 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
3029 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
3031 panic("pmap_growkernel: no memory to grow kernel");
3032 if ((nkpg->flags & PG_ZERO) == 0)
3033 pmap_zero_page(nkpg);
3034 paddr = VM_PAGE_TO_PHYS(nkpg);
3035 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
3036 X86_PG_A | X86_PG_M);
3037 continue; /* try again */
3039 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
3040 if ((*pde & X86_PG_V) != 0) {
3041 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3042 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
3043 kernel_vm_end = kernel_map->max_offset;
3049 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
3050 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
3053 panic("pmap_growkernel: no memory to grow kernel");
3054 if ((nkpg->flags & PG_ZERO) == 0)
3055 pmap_zero_page(nkpg);
3056 paddr = VM_PAGE_TO_PHYS(nkpg);
3057 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
3058 pde_store(pde, newpdir);
3060 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3061 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
3062 kernel_vm_end = kernel_map->max_offset;
3069 /***************************************************
3070 * page management routines.
3071 ***************************************************/
3073 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
3074 CTASSERT(_NPCM == 3);
3075 CTASSERT(_NPCPV == 168);
3077 static __inline struct pv_chunk *
3078 pv_to_chunk(pv_entry_t pv)
3081 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
3084 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
3086 #define PC_FREE0 0xfffffffffffffffful
3087 #define PC_FREE1 0xfffffffffffffffful
3088 #define PC_FREE2 0x000000fffffffffful
3090 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
3093 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
3095 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
3096 "Current number of pv entry chunks");
3097 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
3098 "Current number of pv entry chunks allocated");
3099 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
3100 "Current number of pv entry chunks frees");
3101 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
3102 "Number of times tried to get a chunk page but failed.");
3104 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
3105 static int pv_entry_spare;
3107 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
3108 "Current number of pv entry frees");
3109 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
3110 "Current number of pv entry allocs");
3111 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
3112 "Current number of pv entries");
3113 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
3114 "Current number of spare pv entries");
3118 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
3123 pmap_invalidate_all(pmap);
3124 if (pmap != locked_pmap)
3127 pmap_delayed_invl_finished();
3131 * We are in a serious low memory condition. Resort to
3132 * drastic measures to free some pages so we can allocate
3133 * another pv entry chunk.
3135 * Returns NULL if PV entries were reclaimed from the specified pmap.
3137 * We do not, however, unmap 2mpages because subsequent accesses will
3138 * allocate per-page pv entries until repromotion occurs, thereby
3139 * exacerbating the shortage of free pv entries.
3142 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
3144 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
3145 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
3146 struct md_page *pvh;
3148 pmap_t next_pmap, pmap;
3149 pt_entry_t *pte, tpte;
3150 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3154 struct spglist free;
3156 int bit, field, freed;
3158 static int active_reclaims = 0;
3160 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
3161 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
3164 PG_G = PG_A = PG_M = PG_RW = 0;
3166 bzero(&pc_marker_b, sizeof(pc_marker_b));
3167 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
3168 pc_marker = (struct pv_chunk *)&pc_marker_b;
3169 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
3172 * A delayed invalidation block should already be active if
3173 * pmap_advise() or pmap_remove() called this function by way
3174 * of pmap_demote_pde_locked().
3176 start_di = pmap_not_in_di();
3178 mtx_lock(&pv_chunks_mutex);
3180 TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
3181 TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
3182 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
3183 SLIST_EMPTY(&free)) {
3184 next_pmap = pc->pc_pmap;
3185 if (next_pmap == NULL) {
3187 * The next chunk is a marker. However, it is
3188 * not our marker, so active_reclaims must be
3189 * > 1. Consequently, the next_chunk code
3190 * will not rotate the pv_chunks list.
3194 mtx_unlock(&pv_chunks_mutex);
3197 * A pv_chunk can only be removed from the pc_lru list
3198 * when both pc_chunks_mutex is owned and the
3199 * corresponding pmap is locked.
3201 if (pmap != next_pmap) {
3202 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
3205 /* Avoid deadlock and lock recursion. */
3206 if (pmap > locked_pmap) {
3207 RELEASE_PV_LIST_LOCK(lockp);
3210 pmap_delayed_invl_started();
3211 mtx_lock(&pv_chunks_mutex);
3213 } else if (pmap != locked_pmap) {
3214 if (PMAP_TRYLOCK(pmap)) {
3216 pmap_delayed_invl_started();
3217 mtx_lock(&pv_chunks_mutex);
3220 pmap = NULL; /* pmap is not locked */
3221 mtx_lock(&pv_chunks_mutex);
3222 pc = TAILQ_NEXT(pc_marker, pc_lru);
3224 pc->pc_pmap != next_pmap)
3228 } else if (start_di)
3229 pmap_delayed_invl_started();
3230 PG_G = pmap_global_bit(pmap);
3231 PG_A = pmap_accessed_bit(pmap);
3232 PG_M = pmap_modified_bit(pmap);
3233 PG_RW = pmap_rw_bit(pmap);
3237 * Destroy every non-wired, 4 KB page mapping in the chunk.
3240 for (field = 0; field < _NPCM; field++) {
3241 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
3242 inuse != 0; inuse &= ~(1UL << bit)) {
3244 pv = &pc->pc_pventry[field * 64 + bit];
3246 pde = pmap_pde(pmap, va);
3247 if ((*pde & PG_PS) != 0)
3249 pte = pmap_pde_to_pte(pde, va);
3250 if ((*pte & PG_W) != 0)
3252 tpte = pte_load_clear(pte);
3253 if ((tpte & PG_G) != 0)
3254 pmap_invalidate_page(pmap, va);
3255 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3256 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3258 if ((tpte & PG_A) != 0)
3259 vm_page_aflag_set(m, PGA_REFERENCED);
3260 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3261 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3263 if (TAILQ_EMPTY(&m->md.pv_list) &&
3264 (m->flags & PG_FICTITIOUS) == 0) {
3265 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3266 if (TAILQ_EMPTY(&pvh->pv_list)) {
3267 vm_page_aflag_clear(m,
3271 pmap_delayed_invl_page(m);
3272 pc->pc_map[field] |= 1UL << bit;
3273 pmap_unuse_pt(pmap, va, *pde, &free);
3278 mtx_lock(&pv_chunks_mutex);
3281 /* Every freed mapping is for a 4 KB page. */
3282 pmap_resident_count_dec(pmap, freed);
3283 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
3284 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
3285 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
3286 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3287 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
3288 pc->pc_map[2] == PC_FREE2) {
3289 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3290 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3291 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3292 /* Entire chunk is free; return it. */
3293 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3294 dump_drop_page(m_pc->phys_addr);
3295 mtx_lock(&pv_chunks_mutex);
3296 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3299 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3300 mtx_lock(&pv_chunks_mutex);
3301 /* One freed pv entry in locked_pmap is sufficient. */
3302 if (pmap == locked_pmap)
3305 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3306 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
3307 if (active_reclaims == 1 && pmap != NULL) {
3309 * Rotate the pv chunks list so that we do not
3310 * scan the same pv chunks that could not be
3311 * freed (because they contained a wired
3312 * and/or superpage mapping) on every
3313 * invocation of reclaim_pv_chunk().
3315 while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
3316 MPASS(pc->pc_pmap != NULL);
3317 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3318 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3322 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3323 TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
3325 mtx_unlock(&pv_chunks_mutex);
3326 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
3327 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
3328 m_pc = SLIST_FIRST(&free);
3329 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3330 /* Recycle a freed page table page. */
3331 m_pc->wire_count = 1;
3333 pmap_free_zero_pages(&free);
3338 * free the pv_entry back to the free list
3341 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3343 struct pv_chunk *pc;
3344 int idx, field, bit;
3346 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3347 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3348 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3349 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3350 pc = pv_to_chunk(pv);
3351 idx = pv - &pc->pc_pventry[0];
3354 pc->pc_map[field] |= 1ul << bit;
3355 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3356 pc->pc_map[2] != PC_FREE2) {
3357 /* 98% of the time, pc is already at the head of the list. */
3358 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3359 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3360 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3364 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3369 free_pv_chunk(struct pv_chunk *pc)
3373 mtx_lock(&pv_chunks_mutex);
3374 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3375 mtx_unlock(&pv_chunks_mutex);
3376 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3377 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3378 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3379 /* entire chunk is free, return it */
3380 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3381 dump_drop_page(m->phys_addr);
3382 vm_page_unwire(m, PQ_NONE);
3387 * Returns a new PV entry, allocating a new PV chunk from the system when
3388 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3389 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3392 * The given PV list lock may be released.
3395 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3399 struct pv_chunk *pc;
3402 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3403 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3405 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3407 for (field = 0; field < _NPCM; field++) {
3408 if (pc->pc_map[field]) {
3409 bit = bsfq(pc->pc_map[field]);
3413 if (field < _NPCM) {
3414 pv = &pc->pc_pventry[field * 64 + bit];
3415 pc->pc_map[field] &= ~(1ul << bit);
3416 /* If this was the last item, move it to tail */
3417 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3418 pc->pc_map[2] == 0) {
3419 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3420 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3423 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3424 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3428 /* No free items, allocate another chunk */
3429 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3432 if (lockp == NULL) {
3433 PV_STAT(pc_chunk_tryfail++);
3436 m = reclaim_pv_chunk(pmap, lockp);
3440 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3441 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3442 dump_add_page(m->phys_addr);
3443 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3445 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3446 pc->pc_map[1] = PC_FREE1;
3447 pc->pc_map[2] = PC_FREE2;
3448 mtx_lock(&pv_chunks_mutex);
3449 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3450 mtx_unlock(&pv_chunks_mutex);
3451 pv = &pc->pc_pventry[0];
3452 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3453 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3454 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3459 * Returns the number of one bits within the given PV chunk map.
3461 * The erratas for Intel processors state that "POPCNT Instruction May
3462 * Take Longer to Execute Than Expected". It is believed that the
3463 * issue is the spurious dependency on the destination register.
3464 * Provide a hint to the register rename logic that the destination
3465 * value is overwritten, by clearing it, as suggested in the
3466 * optimization manual. It should be cheap for unaffected processors
3469 * Reference numbers for erratas are
3470 * 4th Gen Core: HSD146
3471 * 5th Gen Core: BDM85
3472 * 6th Gen Core: SKL029
3475 popcnt_pc_map_pq(uint64_t *map)
3479 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3480 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3481 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3482 : "=&r" (result), "=&r" (tmp)
3483 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3488 * Ensure that the number of spare PV entries in the specified pmap meets or
3489 * exceeds the given count, "needed".
3491 * The given PV list lock may be released.
3494 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3496 struct pch new_tail;
3497 struct pv_chunk *pc;
3502 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3503 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3506 * Newly allocated PV chunks must be stored in a private list until
3507 * the required number of PV chunks have been allocated. Otherwise,
3508 * reclaim_pv_chunk() could recycle one of these chunks. In
3509 * contrast, these chunks must be added to the pmap upon allocation.
3511 TAILQ_INIT(&new_tail);
3514 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3516 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3517 bit_count((bitstr_t *)pc->pc_map, 0,
3518 sizeof(pc->pc_map) * NBBY, &free);
3521 free = popcnt_pc_map_pq(pc->pc_map);
3525 if (avail >= needed)
3528 for (reclaimed = false; avail < needed; avail += _NPCPV) {
3529 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3532 m = reclaim_pv_chunk(pmap, lockp);
3537 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3538 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3539 dump_add_page(m->phys_addr);
3540 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3542 pc->pc_map[0] = PC_FREE0;
3543 pc->pc_map[1] = PC_FREE1;
3544 pc->pc_map[2] = PC_FREE2;
3545 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3546 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3547 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3550 * The reclaim might have freed a chunk from the current pmap.
3551 * If that chunk contained available entries, we need to
3552 * re-count the number of available entries.
3557 if (!TAILQ_EMPTY(&new_tail)) {
3558 mtx_lock(&pv_chunks_mutex);
3559 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3560 mtx_unlock(&pv_chunks_mutex);
3565 * First find and then remove the pv entry for the specified pmap and virtual
3566 * address from the specified pv list. Returns the pv entry if found and NULL
3567 * otherwise. This operation can be performed on pv lists for either 4KB or
3568 * 2MB page mappings.
3570 static __inline pv_entry_t
3571 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3575 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3576 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3577 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3586 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3587 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3588 * entries for each of the 4KB page mappings.
3591 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3592 struct rwlock **lockp)
3594 struct md_page *pvh;
3595 struct pv_chunk *pc;
3597 vm_offset_t va_last;
3601 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3602 KASSERT((pa & PDRMASK) == 0,
3603 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3604 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3607 * Transfer the 2mpage's pv entry for this mapping to the first
3608 * page's pv list. Once this transfer begins, the pv list lock
3609 * must not be released until the last pv entry is reinstantiated.
3611 pvh = pa_to_pvh(pa);
3612 va = trunc_2mpage(va);
3613 pv = pmap_pvh_remove(pvh, pmap, va);
3614 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3615 m = PHYS_TO_VM_PAGE(pa);
3616 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3618 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3619 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3620 va_last = va + NBPDR - PAGE_SIZE;
3622 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3623 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3624 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3625 for (field = 0; field < _NPCM; field++) {
3626 while (pc->pc_map[field]) {
3627 bit = bsfq(pc->pc_map[field]);
3628 pc->pc_map[field] &= ~(1ul << bit);
3629 pv = &pc->pc_pventry[field * 64 + bit];
3633 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3634 ("pmap_pv_demote_pde: page %p is not managed", m));
3635 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3641 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3642 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3645 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3646 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3647 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3649 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3650 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3653 #if VM_NRESERVLEVEL > 0
3655 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3656 * replace the many pv entries for the 4KB page mappings by a single pv entry
3657 * for the 2MB page mapping.
3660 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3661 struct rwlock **lockp)
3663 struct md_page *pvh;
3665 vm_offset_t va_last;
3668 KASSERT((pa & PDRMASK) == 0,
3669 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3670 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3673 * Transfer the first page's pv entry for this mapping to the 2mpage's
3674 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3675 * a transfer avoids the possibility that get_pv_entry() calls
3676 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3677 * mappings that is being promoted.
3679 m = PHYS_TO_VM_PAGE(pa);
3680 va = trunc_2mpage(va);
3681 pv = pmap_pvh_remove(&m->md, pmap, va);
3682 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3683 pvh = pa_to_pvh(pa);
3684 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3686 /* Free the remaining NPTEPG - 1 pv entries. */
3687 va_last = va + NBPDR - PAGE_SIZE;
3691 pmap_pvh_free(&m->md, pmap, va);
3692 } while (va < va_last);
3694 #endif /* VM_NRESERVLEVEL > 0 */
3697 * First find and then destroy the pv entry for the specified pmap and virtual
3698 * address. This operation can be performed on pv lists for either 4KB or 2MB
3702 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3706 pv = pmap_pvh_remove(pvh, pmap, va);
3707 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3708 free_pv_entry(pmap, pv);
3712 * Conditionally create the PV entry for a 4KB page mapping if the required
3713 * memory can be allocated without resorting to reclamation.
3716 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3717 struct rwlock **lockp)
3721 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3722 /* Pass NULL instead of the lock pointer to disable reclamation. */
3723 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3725 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3726 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3734 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3735 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3736 * false if the PV entry cannot be allocated without resorting to reclamation.
3739 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
3740 struct rwlock **lockp)
3742 struct md_page *pvh;
3746 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3747 /* Pass NULL instead of the lock pointer to disable reclamation. */
3748 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3749 NULL : lockp)) == NULL)
3752 pa = pde & PG_PS_FRAME;
3753 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3754 pvh = pa_to_pvh(pa);
3755 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3761 * Fills a page table page with mappings to consecutive physical pages.
3764 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3768 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3770 newpte += PAGE_SIZE;
3775 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3776 * mapping is invalidated.
3779 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3781 struct rwlock *lock;
3785 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3792 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3793 struct rwlock **lockp)
3795 pd_entry_t newpde, oldpde;
3796 pt_entry_t *firstpte, newpte;
3797 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3800 struct spglist free;
3804 PG_G = pmap_global_bit(pmap);
3805 PG_A = pmap_accessed_bit(pmap);
3806 PG_M = pmap_modified_bit(pmap);
3807 PG_RW = pmap_rw_bit(pmap);
3808 PG_V = pmap_valid_bit(pmap);
3809 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3811 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3813 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3814 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3815 if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
3817 KASSERT((oldpde & PG_W) == 0,
3818 ("pmap_demote_pde: page table page for a wired mapping"
3822 * Invalidate the 2MB page mapping and return "failure" if the
3823 * mapping was never accessed or the allocation of the new
3824 * page table page fails. If the 2MB page mapping belongs to
3825 * the direct map region of the kernel's address space, then
3826 * the page allocation request specifies the highest possible
3827 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3828 * normal. Page table pages are preallocated for every other
3829 * part of the kernel address space, so the direct map region
3830 * is the only part of the kernel address space that must be
3833 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3834 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3835 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3836 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3838 sva = trunc_2mpage(va);
3839 pmap_remove_pde(pmap, pde, sva, &free, lockp);
3840 if ((oldpde & PG_G) == 0)
3841 pmap_invalidate_pde_page(pmap, sva, oldpde);
3842 pmap_free_zero_pages(&free);
3843 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3844 " in pmap %p", va, pmap);
3847 if (va < VM_MAXUSER_ADDRESS)
3848 pmap_resident_count_inc(pmap, 1);
3850 mptepa = VM_PAGE_TO_PHYS(mpte);
3851 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3852 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3853 KASSERT((oldpde & PG_A) != 0,
3854 ("pmap_demote_pde: oldpde is missing PG_A"));
3855 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3856 ("pmap_demote_pde: oldpde is missing PG_M"));
3857 newpte = oldpde & ~PG_PS;
3858 newpte = pmap_swap_pat(pmap, newpte);
3861 * If the page table page is new, initialize it.
3863 if (mpte->wire_count == 1) {
3864 mpte->wire_count = NPTEPG;
3865 pmap_fill_ptp(firstpte, newpte);
3867 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3868 ("pmap_demote_pde: firstpte and newpte map different physical"
3872 * If the mapping has changed attributes, update the page table
3875 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3876 pmap_fill_ptp(firstpte, newpte);
3879 * The spare PV entries must be reserved prior to demoting the
3880 * mapping, that is, prior to changing the PDE. Otherwise, the state
3881 * of the PDE and the PV lists will be inconsistent, which can result
3882 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3883 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3884 * PV entry for the 2MB page mapping that is being demoted.
3886 if ((oldpde & PG_MANAGED) != 0)
3887 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3890 * Demote the mapping. This pmap is locked. The old PDE has
3891 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3892 * set. Thus, there is no danger of a race with another
3893 * processor changing the setting of PG_A and/or PG_M between
3894 * the read above and the store below.
3896 if (workaround_erratum383)
3897 pmap_update_pde(pmap, va, pde, newpde);
3899 pde_store(pde, newpde);
3902 * Invalidate a stale recursive mapping of the page table page.
3904 if (va >= VM_MAXUSER_ADDRESS)
3905 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3908 * Demote the PV entry.
3910 if ((oldpde & PG_MANAGED) != 0)
3911 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3913 atomic_add_long(&pmap_pde_demotions, 1);
3914 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3915 " in pmap %p", va, pmap);
3920 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3923 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3929 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3930 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3931 mpte = pmap_remove_pt_page(pmap, va);
3933 panic("pmap_remove_kernel_pde: Missing pt page.");
3935 mptepa = VM_PAGE_TO_PHYS(mpte);
3936 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3939 * Initialize the page table page.
3941 pagezero((void *)PHYS_TO_DMAP(mptepa));
3944 * Demote the mapping.
3946 if (workaround_erratum383)
3947 pmap_update_pde(pmap, va, pde, newpde);
3949 pde_store(pde, newpde);
3952 * Invalidate a stale recursive mapping of the page table page.
3954 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3958 * pmap_remove_pde: do the things to unmap a superpage in a process
3961 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
3962 struct spglist *free, struct rwlock **lockp)
3964 struct md_page *pvh;
3966 vm_offset_t eva, va;
3968 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3970 PG_G = pmap_global_bit(pmap);
3971 PG_A = pmap_accessed_bit(pmap);
3972 PG_M = pmap_modified_bit(pmap);
3973 PG_RW = pmap_rw_bit(pmap);
3975 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3976 KASSERT((sva & PDRMASK) == 0,
3977 ("pmap_remove_pde: sva is not 2mpage aligned"));
3978 oldpde = pte_load_clear(pdq);
3980 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
3981 if ((oldpde & PG_G) != 0)
3982 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
3983 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
3984 if (oldpde & PG_MANAGED) {
3985 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
3986 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
3987 pmap_pvh_free(pvh, pmap, sva);
3989 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3990 va < eva; va += PAGE_SIZE, m++) {
3991 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3994 vm_page_aflag_set(m, PGA_REFERENCED);
3995 if (TAILQ_EMPTY(&m->md.pv_list) &&
3996 TAILQ_EMPTY(&pvh->pv_list))
3997 vm_page_aflag_clear(m, PGA_WRITEABLE);
3998 pmap_delayed_invl_page(m);
4001 if (pmap == kernel_pmap) {
4002 pmap_remove_kernel_pde(pmap, pdq, sva);
4004 mpte = pmap_remove_pt_page(pmap, sva);
4006 pmap_resident_count_dec(pmap, 1);
4007 KASSERT(mpte->wire_count == NPTEPG,
4008 ("pmap_remove_pde: pte page wire count error"));
4009 mpte->wire_count = 0;
4010 pmap_add_delayed_free_list(mpte, free, FALSE);
4013 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
4017 * pmap_remove_pte: do the things to unmap a page in a process
4020 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
4021 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
4023 struct md_page *pvh;
4024 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
4027 PG_A = pmap_accessed_bit(pmap);
4028 PG_M = pmap_modified_bit(pmap);
4029 PG_RW = pmap_rw_bit(pmap);
4031 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4032 oldpte = pte_load_clear(ptq);
4034 pmap->pm_stats.wired_count -= 1;
4035 pmap_resident_count_dec(pmap, 1);
4036 if (oldpte & PG_MANAGED) {
4037 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
4038 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4041 vm_page_aflag_set(m, PGA_REFERENCED);
4042 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
4043 pmap_pvh_free(&m->md, pmap, va);
4044 if (TAILQ_EMPTY(&m->md.pv_list) &&
4045 (m->flags & PG_FICTITIOUS) == 0) {
4046 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4047 if (TAILQ_EMPTY(&pvh->pv_list))
4048 vm_page_aflag_clear(m, PGA_WRITEABLE);
4050 pmap_delayed_invl_page(m);
4052 return (pmap_unuse_pt(pmap, va, ptepde, free));
4056 * Remove a single page from a process address space
4059 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
4060 struct spglist *free)
4062 struct rwlock *lock;
4063 pt_entry_t *pte, PG_V;
4065 PG_V = pmap_valid_bit(pmap);
4066 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4067 if ((*pde & PG_V) == 0)
4069 pte = pmap_pde_to_pte(pde, va);
4070 if ((*pte & PG_V) == 0)
4073 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
4076 pmap_invalidate_page(pmap, va);
4080 * Removes the specified range of addresses from the page table page.
4083 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
4084 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
4086 pt_entry_t PG_G, *pte;
4090 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4091 PG_G = pmap_global_bit(pmap);
4094 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
4098 pmap_invalidate_range(pmap, va, sva);
4103 if ((*pte & PG_G) == 0)
4107 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
4113 pmap_invalidate_range(pmap, va, sva);
4118 * Remove the given range of addresses from the specified map.
4120 * It is assumed that the start and end are properly
4121 * rounded to the page size.
4124 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4126 struct rwlock *lock;
4127 vm_offset_t va_next;
4128 pml4_entry_t *pml4e;
4130 pd_entry_t ptpaddr, *pde;
4131 pt_entry_t PG_G, PG_V;
4132 struct spglist free;
4135 PG_G = pmap_global_bit(pmap);
4136 PG_V = pmap_valid_bit(pmap);
4139 * Perform an unsynchronized read. This is, however, safe.
4141 if (pmap->pm_stats.resident_count == 0)
4147 pmap_delayed_invl_started();
4151 * special handling of removing one page. a very
4152 * common operation and easy to short circuit some
4155 if (sva + PAGE_SIZE == eva) {
4156 pde = pmap_pde(pmap, sva);
4157 if (pde && (*pde & PG_PS) == 0) {
4158 pmap_remove_page(pmap, sva, pde, &free);
4164 for (; sva < eva; sva = va_next) {
4166 if (pmap->pm_stats.resident_count == 0)
4169 pml4e = pmap_pml4e(pmap, sva);
4170 if ((*pml4e & PG_V) == 0) {
4171 va_next = (sva + NBPML4) & ~PML4MASK;
4177 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4178 if ((*pdpe & PG_V) == 0) {
4179 va_next = (sva + NBPDP) & ~PDPMASK;
4186 * Calculate index for next page table.
4188 va_next = (sva + NBPDR) & ~PDRMASK;
4192 pde = pmap_pdpe_to_pde(pdpe, sva);
4196 * Weed out invalid mappings.
4202 * Check for large page.
4204 if ((ptpaddr & PG_PS) != 0) {
4206 * Are we removing the entire large page? If not,
4207 * demote the mapping and fall through.
4209 if (sva + NBPDR == va_next && eva >= va_next) {
4211 * The TLB entry for a PG_G mapping is
4212 * invalidated by pmap_remove_pde().
4214 if ((ptpaddr & PG_G) == 0)
4216 pmap_remove_pde(pmap, pde, sva, &free, &lock);
4218 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
4220 /* The large page mapping was destroyed. */
4227 * Limit our scan to either the end of the va represented
4228 * by the current page table page, or to the end of the
4229 * range being removed.
4234 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
4241 pmap_invalidate_all(pmap);
4243 pmap_delayed_invl_finished();
4244 pmap_free_zero_pages(&free);
4248 * Routine: pmap_remove_all
4250 * Removes this physical page from
4251 * all physical maps in which it resides.
4252 * Reflects back modify bits to the pager.
4255 * Original versions of this routine were very
4256 * inefficient because they iteratively called
4257 * pmap_remove (slow...)
4261 pmap_remove_all(vm_page_t m)
4263 struct md_page *pvh;
4266 struct rwlock *lock;
4267 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
4270 struct spglist free;
4271 int pvh_gen, md_gen;
4273 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4274 ("pmap_remove_all: page %p is not managed", m));
4276 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4277 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
4278 pa_to_pvh(VM_PAGE_TO_PHYS(m));
4281 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
4283 if (!PMAP_TRYLOCK(pmap)) {
4284 pvh_gen = pvh->pv_gen;
4288 if (pvh_gen != pvh->pv_gen) {
4295 pde = pmap_pde(pmap, va);
4296 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
4299 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4301 if (!PMAP_TRYLOCK(pmap)) {
4302 pvh_gen = pvh->pv_gen;
4303 md_gen = m->md.pv_gen;
4307 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
4313 PG_A = pmap_accessed_bit(pmap);
4314 PG_M = pmap_modified_bit(pmap);
4315 PG_RW = pmap_rw_bit(pmap);
4316 pmap_resident_count_dec(pmap, 1);
4317 pde = pmap_pde(pmap, pv->pv_va);
4318 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
4319 " a 2mpage in page %p's pv list", m));
4320 pte = pmap_pde_to_pte(pde, pv->pv_va);
4321 tpte = pte_load_clear(pte);
4323 pmap->pm_stats.wired_count--;
4325 vm_page_aflag_set(m, PGA_REFERENCED);
4328 * Update the vm_page_t clean and reference bits.
4330 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4332 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
4333 pmap_invalidate_page(pmap, pv->pv_va);
4334 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4336 free_pv_entry(pmap, pv);
4339 vm_page_aflag_clear(m, PGA_WRITEABLE);
4341 pmap_delayed_invl_wait(m);
4342 pmap_free_zero_pages(&free);
4346 * pmap_protect_pde: do the things to protect a 2mpage in a process
4349 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
4351 pd_entry_t newpde, oldpde;
4352 vm_offset_t eva, va;
4354 boolean_t anychanged;
4355 pt_entry_t PG_G, PG_M, PG_RW;
4357 PG_G = pmap_global_bit(pmap);
4358 PG_M = pmap_modified_bit(pmap);
4359 PG_RW = pmap_rw_bit(pmap);
4361 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4362 KASSERT((sva & PDRMASK) == 0,
4363 ("pmap_protect_pde: sva is not 2mpage aligned"));
4366 oldpde = newpde = *pde;
4367 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4368 (PG_MANAGED | PG_M | PG_RW)) {
4370 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4371 va < eva; va += PAGE_SIZE, m++)
4374 if ((prot & VM_PROT_WRITE) == 0)
4375 newpde &= ~(PG_RW | PG_M);
4376 if ((prot & VM_PROT_EXECUTE) == 0)
4378 if (newpde != oldpde) {
4380 * As an optimization to future operations on this PDE, clear
4381 * PG_PROMOTED. The impending invalidation will remove any
4382 * lingering 4KB page mappings from the TLB.
4384 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
4386 if ((oldpde & PG_G) != 0)
4387 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4391 return (anychanged);
4395 * Set the physical protection on the
4396 * specified range of this map as requested.
4399 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4401 vm_offset_t va_next;
4402 pml4_entry_t *pml4e;
4404 pd_entry_t ptpaddr, *pde;
4405 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4406 boolean_t anychanged;
4408 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4409 if (prot == VM_PROT_NONE) {
4410 pmap_remove(pmap, sva, eva);
4414 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4415 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4418 PG_G = pmap_global_bit(pmap);
4419 PG_M = pmap_modified_bit(pmap);
4420 PG_V = pmap_valid_bit(pmap);
4421 PG_RW = pmap_rw_bit(pmap);
4425 * Although this function delays and batches the invalidation
4426 * of stale TLB entries, it does not need to call
4427 * pmap_delayed_invl_started() and
4428 * pmap_delayed_invl_finished(), because it does not
4429 * ordinarily destroy mappings. Stale TLB entries from
4430 * protection-only changes need only be invalidated before the
4431 * pmap lock is released, because protection-only changes do
4432 * not destroy PV entries. Even operations that iterate over
4433 * a physical page's PV list of mappings, like
4434 * pmap_remove_write(), acquire the pmap lock for each
4435 * mapping. Consequently, for protection-only changes, the
4436 * pmap lock suffices to synchronize both page table and TLB
4439 * This function only destroys a mapping if pmap_demote_pde()
4440 * fails. In that case, stale TLB entries are immediately
4445 for (; sva < eva; sva = va_next) {
4447 pml4e = pmap_pml4e(pmap, sva);
4448 if ((*pml4e & PG_V) == 0) {
4449 va_next = (sva + NBPML4) & ~PML4MASK;
4455 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4456 if ((*pdpe & PG_V) == 0) {
4457 va_next = (sva + NBPDP) & ~PDPMASK;
4463 va_next = (sva + NBPDR) & ~PDRMASK;
4467 pde = pmap_pdpe_to_pde(pdpe, sva);
4471 * Weed out invalid mappings.
4477 * Check for large page.
4479 if ((ptpaddr & PG_PS) != 0) {
4481 * Are we protecting the entire large page? If not,
4482 * demote the mapping and fall through.
4484 if (sva + NBPDR == va_next && eva >= va_next) {
4486 * The TLB entry for a PG_G mapping is
4487 * invalidated by pmap_protect_pde().
4489 if (pmap_protect_pde(pmap, pde, sva, prot))
4492 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4494 * The large page mapping was destroyed.
4503 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4505 pt_entry_t obits, pbits;
4509 obits = pbits = *pte;
4510 if ((pbits & PG_V) == 0)
4513 if ((prot & VM_PROT_WRITE) == 0) {
4514 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4515 (PG_MANAGED | PG_M | PG_RW)) {
4516 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4519 pbits &= ~(PG_RW | PG_M);
4521 if ((prot & VM_PROT_EXECUTE) == 0)
4524 if (pbits != obits) {
4525 if (!atomic_cmpset_long(pte, obits, pbits))
4528 pmap_invalidate_page(pmap, sva);
4535 pmap_invalidate_all(pmap);
4539 #if VM_NRESERVLEVEL > 0
4541 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4542 * single page table page (PTP) to a single 2MB page mapping. For promotion
4543 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4544 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4545 * identical characteristics.
4548 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4549 struct rwlock **lockp)
4552 pt_entry_t *firstpte, oldpte, pa, *pte;
4553 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4557 PG_A = pmap_accessed_bit(pmap);
4558 PG_G = pmap_global_bit(pmap);
4559 PG_M = pmap_modified_bit(pmap);
4560 PG_V = pmap_valid_bit(pmap);
4561 PG_RW = pmap_rw_bit(pmap);
4562 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4564 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4567 * Examine the first PTE in the specified PTP. Abort if this PTE is
4568 * either invalid, unused, or does not map the first 4KB physical page
4569 * within a 2MB page.
4571 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4574 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4575 atomic_add_long(&pmap_pde_p_failures, 1);
4576 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4577 " in pmap %p", va, pmap);
4580 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4582 * When PG_M is already clear, PG_RW can be cleared without
4583 * a TLB invalidation.
4585 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4591 * Examine each of the other PTEs in the specified PTP. Abort if this
4592 * PTE maps an unexpected 4KB physical page or does not have identical
4593 * characteristics to the first PTE.
4595 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4596 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4599 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4600 atomic_add_long(&pmap_pde_p_failures, 1);
4601 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4602 " in pmap %p", va, pmap);
4605 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4607 * When PG_M is already clear, PG_RW can be cleared
4608 * without a TLB invalidation.
4610 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4613 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4614 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4615 (va & ~PDRMASK), pmap);
4617 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4618 atomic_add_long(&pmap_pde_p_failures, 1);
4619 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4620 " in pmap %p", va, pmap);
4627 * Save the page table page in its current state until the PDE
4628 * mapping the superpage is demoted by pmap_demote_pde() or
4629 * destroyed by pmap_remove_pde().
4631 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4632 KASSERT(mpte >= vm_page_array &&
4633 mpte < &vm_page_array[vm_page_array_size],
4634 ("pmap_promote_pde: page table page is out of range"));
4635 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4636 ("pmap_promote_pde: page table page's pindex is wrong"));
4637 if (pmap_insert_pt_page(pmap, mpte)) {
4638 atomic_add_long(&pmap_pde_p_failures, 1);
4640 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4646 * Promote the pv entries.
4648 if ((newpde & PG_MANAGED) != 0)
4649 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4652 * Propagate the PAT index to its proper position.
4654 newpde = pmap_swap_pat(pmap, newpde);
4657 * Map the superpage.
4659 if (workaround_erratum383)
4660 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4662 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
4664 atomic_add_long(&pmap_pde_promotions, 1);
4665 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4666 " in pmap %p", va, pmap);
4668 #endif /* VM_NRESERVLEVEL > 0 */
4671 * Insert the given physical page (p) at
4672 * the specified virtual address (v) in the
4673 * target physical map with the protection requested.
4675 * If specified, the page will be wired down, meaning
4676 * that the related pte can not be reclaimed.
4678 * NB: This is the only routine which MAY NOT lazy-evaluate
4679 * or lose information. That is, this routine must actually
4680 * insert this page into the given map NOW.
4682 * When destroying both a page table and PV entry, this function
4683 * performs the TLB invalidation before releasing the PV list
4684 * lock, so we do not need pmap_delayed_invl_page() calls here.
4687 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4688 u_int flags, int8_t psind)
4690 struct rwlock *lock;
4692 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4693 pt_entry_t newpte, origpte;
4700 PG_A = pmap_accessed_bit(pmap);
4701 PG_G = pmap_global_bit(pmap);
4702 PG_M = pmap_modified_bit(pmap);
4703 PG_V = pmap_valid_bit(pmap);
4704 PG_RW = pmap_rw_bit(pmap);
4706 va = trunc_page(va);
4707 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4708 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4709 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4711 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4712 va >= kmi.clean_eva,
4713 ("pmap_enter: managed mapping within the clean submap"));
4714 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4715 VM_OBJECT_ASSERT_LOCKED(m->object);
4716 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
4717 ("pmap_enter: flags %u has reserved bits set", flags));
4718 pa = VM_PAGE_TO_PHYS(m);
4719 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4720 if ((flags & VM_PROT_WRITE) != 0)
4722 if ((prot & VM_PROT_WRITE) != 0)
4724 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4725 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4726 if ((prot & VM_PROT_EXECUTE) == 0)
4728 if ((flags & PMAP_ENTER_WIRED) != 0)
4730 if (va < VM_MAXUSER_ADDRESS)
4732 if (pmap == kernel_pmap)
4734 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
4737 * Set modified bit gratuitously for writeable mappings if
4738 * the page is unmanaged. We do not want to take a fault
4739 * to do the dirty bit accounting for these mappings.
4741 if ((m->oflags & VPO_UNMANAGED) != 0) {
4742 if ((newpte & PG_RW) != 0)
4745 newpte |= PG_MANAGED;
4750 /* Assert the required virtual and physical alignment. */
4751 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
4752 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4753 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
4759 * In the case that a page table page is not
4760 * resident, we are creating it here.
4763 pde = pmap_pde(pmap, va);
4764 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4765 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4766 pte = pmap_pde_to_pte(pde, va);
4767 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4768 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4771 } else if (va < VM_MAXUSER_ADDRESS) {
4773 * Here if the pte page isn't mapped, or if it has been
4776 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4777 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4778 nosleep ? NULL : &lock);
4779 if (mpte == NULL && nosleep) {
4780 rv = KERN_RESOURCE_SHORTAGE;
4785 panic("pmap_enter: invalid page directory va=%#lx", va);
4791 * Is the specified virtual address already mapped?
4793 if ((origpte & PG_V) != 0) {
4795 * Wiring change, just update stats. We don't worry about
4796 * wiring PT pages as they remain resident as long as there
4797 * are valid mappings in them. Hence, if a user page is wired,
4798 * the PT page will be also.
4800 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4801 pmap->pm_stats.wired_count++;
4802 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4803 pmap->pm_stats.wired_count--;
4806 * Remove the extra PT page reference.
4810 KASSERT(mpte->wire_count > 0,
4811 ("pmap_enter: missing reference to page table page,"
4816 * Has the physical page changed?
4818 opa = origpte & PG_FRAME;
4821 * No, might be a protection or wiring change.
4823 if ((origpte & PG_MANAGED) != 0 &&
4824 (newpte & PG_RW) != 0)
4825 vm_page_aflag_set(m, PGA_WRITEABLE);
4826 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4832 * The physical page has changed. Temporarily invalidate
4833 * the mapping. This ensures that all threads sharing the
4834 * pmap keep a consistent view of the mapping, which is
4835 * necessary for the correct handling of COW faults. It
4836 * also permits reuse of the old mapping's PV entry,
4837 * avoiding an allocation.
4839 * For consistency, handle unmanaged mappings the same way.
4841 origpte = pte_load_clear(pte);
4842 KASSERT((origpte & PG_FRAME) == opa,
4843 ("pmap_enter: unexpected pa update for %#lx", va));
4844 if ((origpte & PG_MANAGED) != 0) {
4845 om = PHYS_TO_VM_PAGE(opa);
4848 * The pmap lock is sufficient to synchronize with
4849 * concurrent calls to pmap_page_test_mappings() and
4850 * pmap_ts_referenced().
4852 if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4854 if ((origpte & PG_A) != 0)
4855 vm_page_aflag_set(om, PGA_REFERENCED);
4856 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4857 pv = pmap_pvh_remove(&om->md, pmap, va);
4858 if ((newpte & PG_MANAGED) == 0)
4859 free_pv_entry(pmap, pv);
4860 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4861 TAILQ_EMPTY(&om->md.pv_list) &&
4862 ((om->flags & PG_FICTITIOUS) != 0 ||
4863 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4864 vm_page_aflag_clear(om, PGA_WRITEABLE);
4866 if ((origpte & PG_A) != 0)
4867 pmap_invalidate_page(pmap, va);
4871 * Increment the counters.
4873 if ((newpte & PG_W) != 0)
4874 pmap->pm_stats.wired_count++;
4875 pmap_resident_count_inc(pmap, 1);
4879 * Enter on the PV list if part of our managed memory.
4881 if ((newpte & PG_MANAGED) != 0) {
4883 pv = get_pv_entry(pmap, &lock);
4886 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4887 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4889 if ((newpte & PG_RW) != 0)
4890 vm_page_aflag_set(m, PGA_WRITEABLE);
4896 if ((origpte & PG_V) != 0) {
4898 origpte = pte_load_store(pte, newpte);
4899 KASSERT((origpte & PG_FRAME) == pa,
4900 ("pmap_enter: unexpected pa update for %#lx", va));
4901 if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
4903 if ((origpte & PG_MANAGED) != 0)
4907 * Although the PTE may still have PG_RW set, TLB
4908 * invalidation may nonetheless be required because
4909 * the PTE no longer has PG_M set.
4911 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4913 * This PTE change does not require TLB invalidation.
4917 if ((origpte & PG_A) != 0)
4918 pmap_invalidate_page(pmap, va);
4920 pte_store(pte, newpte);
4924 #if VM_NRESERVLEVEL > 0
4926 * If both the page table page and the reservation are fully
4927 * populated, then attempt promotion.
4929 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4930 pmap_ps_enabled(pmap) &&
4931 (m->flags & PG_FICTITIOUS) == 0 &&
4932 vm_reserv_level_iffullpop(m) == 0)
4933 pmap_promote_pde(pmap, pde, va, &lock);
4945 * Tries to create a read- and/or execute-only 2MB page mapping. Returns true
4946 * if successful. Returns false if (1) a page table page cannot be allocated
4947 * without sleeping, (2) a mapping already exists at the specified virtual
4948 * address, or (3) a PV entry cannot be allocated without reclaiming another
4952 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4953 struct rwlock **lockp)
4958 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4959 PG_V = pmap_valid_bit(pmap);
4960 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
4962 if ((m->oflags & VPO_UNMANAGED) == 0)
4963 newpde |= PG_MANAGED;
4964 if ((prot & VM_PROT_EXECUTE) == 0)
4966 if (va < VM_MAXUSER_ADDRESS)
4968 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
4969 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
4974 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
4975 * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
4976 * otherwise. Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
4977 * a mapping already exists at the specified virtual address. Returns
4978 * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
4979 * page allocation failed. Returns KERN_RESOURCE_SHORTAGE if
4980 * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
4982 * The parameter "m" is only used when creating a managed, writeable mapping.
4985 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
4986 vm_page_t m, struct rwlock **lockp)
4988 struct spglist free;
4989 pd_entry_t oldpde, *pde;
4990 pt_entry_t PG_G, PG_RW, PG_V;
4993 PG_G = pmap_global_bit(pmap);
4994 PG_RW = pmap_rw_bit(pmap);
4995 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
4996 ("pmap_enter_pde: newpde is missing PG_M"));
4997 PG_V = pmap_valid_bit(pmap);
4998 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5000 if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
5001 NULL : lockp)) == NULL) {
5002 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5003 " in pmap %p", va, pmap);
5004 return (KERN_RESOURCE_SHORTAGE);
5006 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5007 pde = &pde[pmap_pde_index(va)];
5009 if ((oldpde & PG_V) != 0) {
5010 KASSERT(pdpg->wire_count > 1,
5011 ("pmap_enter_pde: pdpg's wire count is too low"));
5012 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
5014 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5015 " in pmap %p", va, pmap);
5016 return (KERN_FAILURE);
5018 /* Break the existing mapping(s). */
5020 if ((oldpde & PG_PS) != 0) {
5022 * The reference to the PD page that was acquired by
5023 * pmap_allocpde() ensures that it won't be freed.
5024 * However, if the PDE resulted from a promotion, then
5025 * a reserved PT page could be freed.
5027 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
5028 if ((oldpde & PG_G) == 0)
5029 pmap_invalidate_pde_page(pmap, va, oldpde);
5031 pmap_delayed_invl_started();
5032 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
5034 pmap_invalidate_all(pmap);
5035 pmap_delayed_invl_finished();
5037 pmap_free_zero_pages(&free);
5038 if (va >= VM_MAXUSER_ADDRESS) {
5039 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
5040 if (pmap_insert_pt_page(pmap, mt)) {
5042 * XXX Currently, this can't happen because
5043 * we do not perform pmap_enter(psind == 1)
5044 * on the kernel pmap.
5046 panic("pmap_enter_pde: trie insert failed");
5049 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
5052 if ((newpde & PG_MANAGED) != 0) {
5054 * Abort this mapping if its PV entry could not be created.
5056 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
5058 if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
5060 * Although "va" is not mapped, paging-
5061 * structure caches could nonetheless have
5062 * entries that refer to the freed page table
5063 * pages. Invalidate those entries.
5065 pmap_invalidate_page(pmap, va);
5066 pmap_free_zero_pages(&free);
5068 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5069 " in pmap %p", va, pmap);
5070 return (KERN_RESOURCE_SHORTAGE);
5072 if ((newpde & PG_RW) != 0) {
5073 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5074 vm_page_aflag_set(mt, PGA_WRITEABLE);
5079 * Increment counters.
5081 if ((newpde & PG_W) != 0)
5082 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
5083 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5086 * Map the superpage. (This is not a promoted mapping; there will not
5087 * be any lingering 4KB page mappings in the TLB.)
5089 pde_store(pde, newpde);
5091 atomic_add_long(&pmap_pde_mappings, 1);
5092 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
5093 " in pmap %p", va, pmap);
5094 return (KERN_SUCCESS);
5098 * Maps a sequence of resident pages belonging to the same object.
5099 * The sequence begins with the given page m_start. This page is
5100 * mapped at the given virtual address start. Each subsequent page is
5101 * mapped at a virtual address that is offset from start by the same
5102 * amount as the page is offset from m_start within the object. The
5103 * last page in the sequence is the page with the largest offset from
5104 * m_start that can be mapped at a virtual address less than the given
5105 * virtual address end. Not every virtual page between start and end
5106 * is mapped; only those for which a resident page exists with the
5107 * corresponding offset from m_start are mapped.
5110 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
5111 vm_page_t m_start, vm_prot_t prot)
5113 struct rwlock *lock;
5116 vm_pindex_t diff, psize;
5118 VM_OBJECT_ASSERT_LOCKED(m_start->object);
5120 psize = atop(end - start);
5125 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
5126 va = start + ptoa(diff);
5127 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
5128 m->psind == 1 && pmap_ps_enabled(pmap) &&
5129 pmap_enter_2mpage(pmap, va, m, prot, &lock))
5130 m = &m[NBPDR / PAGE_SIZE - 1];
5132 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
5134 m = TAILQ_NEXT(m, listq);
5142 * this code makes some *MAJOR* assumptions:
5143 * 1. Current pmap & pmap exists.
5146 * 4. No page table pages.
5147 * but is *MUCH* faster than pmap_enter...
5151 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
5153 struct rwlock *lock;
5157 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
5164 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
5165 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
5167 struct spglist free;
5168 pt_entry_t *pte, PG_V;
5171 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
5172 (m->oflags & VPO_UNMANAGED) != 0,
5173 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
5174 PG_V = pmap_valid_bit(pmap);
5175 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5178 * In the case that a page table page is not
5179 * resident, we are creating it here.
5181 if (va < VM_MAXUSER_ADDRESS) {
5182 vm_pindex_t ptepindex;
5186 * Calculate pagetable page index
5188 ptepindex = pmap_pde_pindex(va);
5189 if (mpte && (mpte->pindex == ptepindex)) {
5193 * Get the page directory entry
5195 ptepa = pmap_pde(pmap, va);
5198 * If the page table page is mapped, we just increment
5199 * the hold count, and activate it. Otherwise, we
5200 * attempt to allocate a page table page. If this
5201 * attempt fails, we don't retry. Instead, we give up.
5203 if (ptepa && (*ptepa & PG_V) != 0) {
5206 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
5210 * Pass NULL instead of the PV list lock
5211 * pointer, because we don't intend to sleep.
5213 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
5218 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
5219 pte = &pte[pmap_pte_index(va)];
5233 * Enter on the PV list if part of our managed memory.
5235 if ((m->oflags & VPO_UNMANAGED) == 0 &&
5236 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
5239 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
5241 * Although "va" is not mapped, paging-
5242 * structure caches could nonetheless have
5243 * entries that refer to the freed page table
5244 * pages. Invalidate those entries.
5246 pmap_invalidate_page(pmap, va);
5247 pmap_free_zero_pages(&free);
5255 * Increment counters
5257 pmap_resident_count_inc(pmap, 1);
5259 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
5260 if ((prot & VM_PROT_EXECUTE) == 0)
5264 * Now validate mapping with RO protection
5266 if ((m->oflags & VPO_UNMANAGED) != 0)
5267 pte_store(pte, pa | PG_V | PG_U);
5269 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
5274 * Make a temporary mapping for a physical address. This is only intended
5275 * to be used for panic dumps.
5278 pmap_kenter_temporary(vm_paddr_t pa, int i)
5282 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
5283 pmap_kenter(va, pa);
5285 return ((void *)crashdumpmap);
5289 * This code maps large physical mmap regions into the
5290 * processor address space. Note that some shortcuts
5291 * are taken, but the code works.
5294 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
5295 vm_pindex_t pindex, vm_size_t size)
5298 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5299 vm_paddr_t pa, ptepa;
5303 PG_A = pmap_accessed_bit(pmap);
5304 PG_M = pmap_modified_bit(pmap);
5305 PG_V = pmap_valid_bit(pmap);
5306 PG_RW = pmap_rw_bit(pmap);
5308 VM_OBJECT_ASSERT_WLOCKED(object);
5309 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
5310 ("pmap_object_init_pt: non-device object"));
5311 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
5312 if (!pmap_ps_enabled(pmap))
5314 if (!vm_object_populate(object, pindex, pindex + atop(size)))
5316 p = vm_page_lookup(object, pindex);
5317 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5318 ("pmap_object_init_pt: invalid page %p", p));
5319 pat_mode = p->md.pat_mode;
5322 * Abort the mapping if the first page is not physically
5323 * aligned to a 2MB page boundary.
5325 ptepa = VM_PAGE_TO_PHYS(p);
5326 if (ptepa & (NBPDR - 1))
5330 * Skip the first page. Abort the mapping if the rest of
5331 * the pages are not physically contiguous or have differing
5332 * memory attributes.
5334 p = TAILQ_NEXT(p, listq);
5335 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
5337 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5338 ("pmap_object_init_pt: invalid page %p", p));
5339 if (pa != VM_PAGE_TO_PHYS(p) ||
5340 pat_mode != p->md.pat_mode)
5342 p = TAILQ_NEXT(p, listq);
5346 * Map using 2MB pages. Since "ptepa" is 2M aligned and
5347 * "size" is a multiple of 2M, adding the PAT setting to "pa"
5348 * will not affect the termination of this loop.
5351 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
5352 pa < ptepa + size; pa += NBPDR) {
5353 pdpg = pmap_allocpde(pmap, addr, NULL);
5356 * The creation of mappings below is only an
5357 * optimization. If a page directory page
5358 * cannot be allocated without blocking,
5359 * continue on to the next mapping rather than
5365 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5366 pde = &pde[pmap_pde_index(addr)];
5367 if ((*pde & PG_V) == 0) {
5368 pde_store(pde, pa | PG_PS | PG_M | PG_A |
5369 PG_U | PG_RW | PG_V);
5370 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5371 atomic_add_long(&pmap_pde_mappings, 1);
5373 /* Continue on if the PDE is already valid. */
5375 KASSERT(pdpg->wire_count > 0,
5376 ("pmap_object_init_pt: missing reference "
5377 "to page directory page, va: 0x%lx", addr));
5386 * Clear the wired attribute from the mappings for the specified range of
5387 * addresses in the given pmap. Every valid mapping within that range
5388 * must have the wired attribute set. In contrast, invalid mappings
5389 * cannot have the wired attribute set, so they are ignored.
5391 * The wired attribute of the page table entry is not a hardware
5392 * feature, so there is no need to invalidate any TLB entries.
5393 * Since pmap_demote_pde() for the wired entry must never fail,
5394 * pmap_delayed_invl_started()/finished() calls around the
5395 * function are not needed.
5398 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5400 vm_offset_t va_next;
5401 pml4_entry_t *pml4e;
5404 pt_entry_t *pte, PG_V;
5406 PG_V = pmap_valid_bit(pmap);
5408 for (; sva < eva; sva = va_next) {
5409 pml4e = pmap_pml4e(pmap, sva);
5410 if ((*pml4e & PG_V) == 0) {
5411 va_next = (sva + NBPML4) & ~PML4MASK;
5416 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5417 if ((*pdpe & PG_V) == 0) {
5418 va_next = (sva + NBPDP) & ~PDPMASK;
5423 va_next = (sva + NBPDR) & ~PDRMASK;
5426 pde = pmap_pdpe_to_pde(pdpe, sva);
5427 if ((*pde & PG_V) == 0)
5429 if ((*pde & PG_PS) != 0) {
5430 if ((*pde & PG_W) == 0)
5431 panic("pmap_unwire: pde %#jx is missing PG_W",
5435 * Are we unwiring the entire large page? If not,
5436 * demote the mapping and fall through.
5438 if (sva + NBPDR == va_next && eva >= va_next) {
5439 atomic_clear_long(pde, PG_W);
5440 pmap->pm_stats.wired_count -= NBPDR /
5443 } else if (!pmap_demote_pde(pmap, pde, sva))
5444 panic("pmap_unwire: demotion failed");
5448 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
5450 if ((*pte & PG_V) == 0)
5452 if ((*pte & PG_W) == 0)
5453 panic("pmap_unwire: pte %#jx is missing PG_W",
5457 * PG_W must be cleared atomically. Although the pmap
5458 * lock synchronizes access to PG_W, another processor
5459 * could be setting PG_M and/or PG_A concurrently.
5461 atomic_clear_long(pte, PG_W);
5462 pmap->pm_stats.wired_count--;
5469 * Copy the range specified by src_addr/len
5470 * from the source map to the range dst_addr/len
5471 * in the destination map.
5473 * This routine is only advisory and need not do anything.
5477 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5478 vm_offset_t src_addr)
5480 struct rwlock *lock;
5481 struct spglist free;
5483 vm_offset_t end_addr = src_addr + len;
5484 vm_offset_t va_next;
5485 vm_page_t dst_pdpg, dstmpte, srcmpte;
5486 pt_entry_t PG_A, PG_M, PG_V;
5488 if (dst_addr != src_addr)
5491 if (dst_pmap->pm_type != src_pmap->pm_type)
5495 * EPT page table entries that require emulation of A/D bits are
5496 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5497 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5498 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5499 * implementations flag an EPT misconfiguration for exec-only
5500 * mappings we skip this function entirely for emulated pmaps.
5502 if (pmap_emulate_ad_bits(dst_pmap))
5506 if (dst_pmap < src_pmap) {
5507 PMAP_LOCK(dst_pmap);
5508 PMAP_LOCK(src_pmap);
5510 PMAP_LOCK(src_pmap);
5511 PMAP_LOCK(dst_pmap);
5514 PG_A = pmap_accessed_bit(dst_pmap);
5515 PG_M = pmap_modified_bit(dst_pmap);
5516 PG_V = pmap_valid_bit(dst_pmap);
5518 for (addr = src_addr; addr < end_addr; addr = va_next) {
5519 pt_entry_t *src_pte, *dst_pte;
5520 pml4_entry_t *pml4e;
5522 pd_entry_t srcptepaddr, *pde;
5524 KASSERT(addr < UPT_MIN_ADDRESS,
5525 ("pmap_copy: invalid to pmap_copy page tables"));
5527 pml4e = pmap_pml4e(src_pmap, addr);
5528 if ((*pml4e & PG_V) == 0) {
5529 va_next = (addr + NBPML4) & ~PML4MASK;
5535 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5536 if ((*pdpe & PG_V) == 0) {
5537 va_next = (addr + NBPDP) & ~PDPMASK;
5543 va_next = (addr + NBPDR) & ~PDRMASK;
5547 pde = pmap_pdpe_to_pde(pdpe, addr);
5549 if (srcptepaddr == 0)
5552 if (srcptepaddr & PG_PS) {
5553 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5555 dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
5556 if (dst_pdpg == NULL)
5558 pde = (pd_entry_t *)
5559 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
5560 pde = &pde[pmap_pde_index(addr)];
5561 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5562 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
5563 PMAP_ENTER_NORECLAIM, &lock))) {
5564 *pde = srcptepaddr & ~PG_W;
5565 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5566 atomic_add_long(&pmap_pde_mappings, 1);
5568 dst_pdpg->wire_count--;
5572 srcptepaddr &= PG_FRAME;
5573 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5574 KASSERT(srcmpte->wire_count > 0,
5575 ("pmap_copy: source page table page is unused"));
5577 if (va_next > end_addr)
5580 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5581 src_pte = &src_pte[pmap_pte_index(addr)];
5583 while (addr < va_next) {
5587 * we only virtual copy managed pages
5589 if ((ptetemp & PG_MANAGED) != 0) {
5590 if (dstmpte != NULL &&
5591 dstmpte->pindex == pmap_pde_pindex(addr))
5592 dstmpte->wire_count++;
5593 else if ((dstmpte = pmap_allocpte(dst_pmap,
5594 addr, NULL)) == NULL)
5596 dst_pte = (pt_entry_t *)
5597 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5598 dst_pte = &dst_pte[pmap_pte_index(addr)];
5599 if (*dst_pte == 0 &&
5600 pmap_try_insert_pv_entry(dst_pmap, addr,
5601 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5604 * Clear the wired, modified, and
5605 * accessed (referenced) bits
5608 *dst_pte = ptetemp & ~(PG_W | PG_M |
5610 pmap_resident_count_inc(dst_pmap, 1);
5613 if (pmap_unwire_ptp(dst_pmap, addr,
5616 * Although "addr" is not
5617 * mapped, paging-structure
5618 * caches could nonetheless
5619 * have entries that refer to
5620 * the freed page table pages.
5621 * Invalidate those entries.
5623 pmap_invalidate_page(dst_pmap,
5625 pmap_free_zero_pages(&free);
5629 if (dstmpte->wire_count >= srcmpte->wire_count)
5639 PMAP_UNLOCK(src_pmap);
5640 PMAP_UNLOCK(dst_pmap);
5644 * pmap_zero_page zeros the specified hardware page by mapping
5645 * the page into KVM and using bzero to clear its contents.
5648 pmap_zero_page(vm_page_t m)
5650 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5652 pagezero((void *)va);
5656 * pmap_zero_page_area zeros the specified hardware page by mapping
5657 * the page into KVM and using bzero to clear its contents.
5659 * off and size may not cover an area beyond a single hardware page.
5662 pmap_zero_page_area(vm_page_t m, int off, int size)
5664 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5666 if (off == 0 && size == PAGE_SIZE)
5667 pagezero((void *)va);
5669 bzero((char *)va + off, size);
5673 * pmap_zero_page_idle zeros the specified hardware page by mapping
5674 * the page into KVM and using bzero to clear its contents. This
5675 * is intended to be called from the vm_pagezero process only and
5679 pmap_zero_page_idle(vm_page_t m)
5681 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5683 pagezero((void *)va);
5687 * pmap_copy_page copies the specified (machine independent)
5688 * page by mapping the page into virtual memory and using
5689 * bcopy to copy the page, one machine dependent page at a
5693 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5695 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5696 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5698 pagecopy((void *)src, (void *)dst);
5701 int unmapped_buf_allowed = 1;
5704 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5705 vm_offset_t b_offset, int xfersize)
5709 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5713 while (xfersize > 0) {
5714 a_pg_offset = a_offset & PAGE_MASK;
5715 pages[0] = ma[a_offset >> PAGE_SHIFT];
5716 b_pg_offset = b_offset & PAGE_MASK;
5717 pages[1] = mb[b_offset >> PAGE_SHIFT];
5718 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5719 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5720 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5721 a_cp = (char *)vaddr[0] + a_pg_offset;
5722 b_cp = (char *)vaddr[1] + b_pg_offset;
5723 bcopy(a_cp, b_cp, cnt);
5724 if (__predict_false(mapped))
5725 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5733 * Returns true if the pmap's pv is one of the first
5734 * 16 pvs linked to from this page. This count may
5735 * be changed upwards or downwards in the future; it
5736 * is only necessary that true be returned for a small
5737 * subset of pmaps for proper page aging.
5740 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5742 struct md_page *pvh;
5743 struct rwlock *lock;
5748 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5749 ("pmap_page_exists_quick: page %p is not managed", m));
5751 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5753 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5754 if (PV_PMAP(pv) == pmap) {
5762 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5763 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5764 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5765 if (PV_PMAP(pv) == pmap) {
5779 * pmap_page_wired_mappings:
5781 * Return the number of managed mappings to the given physical page
5785 pmap_page_wired_mappings(vm_page_t m)
5787 struct rwlock *lock;
5788 struct md_page *pvh;
5792 int count, md_gen, pvh_gen;
5794 if ((m->oflags & VPO_UNMANAGED) != 0)
5796 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5800 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5802 if (!PMAP_TRYLOCK(pmap)) {
5803 md_gen = m->md.pv_gen;
5807 if (md_gen != m->md.pv_gen) {
5812 pte = pmap_pte(pmap, pv->pv_va);
5813 if ((*pte & PG_W) != 0)
5817 if ((m->flags & PG_FICTITIOUS) == 0) {
5818 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5819 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5821 if (!PMAP_TRYLOCK(pmap)) {
5822 md_gen = m->md.pv_gen;
5823 pvh_gen = pvh->pv_gen;
5827 if (md_gen != m->md.pv_gen ||
5828 pvh_gen != pvh->pv_gen) {
5833 pte = pmap_pde(pmap, pv->pv_va);
5834 if ((*pte & PG_W) != 0)
5844 * Returns TRUE if the given page is mapped individually or as part of
5845 * a 2mpage. Otherwise, returns FALSE.
5848 pmap_page_is_mapped(vm_page_t m)
5850 struct rwlock *lock;
5853 if ((m->oflags & VPO_UNMANAGED) != 0)
5855 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5857 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5858 ((m->flags & PG_FICTITIOUS) == 0 &&
5859 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5865 * Destroy all managed, non-wired mappings in the given user-space
5866 * pmap. This pmap cannot be active on any processor besides the
5869 * This function cannot be applied to the kernel pmap. Moreover, it
5870 * is not intended for general use. It is only to be used during
5871 * process termination. Consequently, it can be implemented in ways
5872 * that make it faster than pmap_remove(). First, it can more quickly
5873 * destroy mappings by iterating over the pmap's collection of PV
5874 * entries, rather than searching the page table. Second, it doesn't
5875 * have to test and clear the page table entries atomically, because
5876 * no processor is currently accessing the user address space. In
5877 * particular, a page table entry's dirty bit won't change state once
5878 * this function starts.
5880 * Although this function destroys all of the pmap's managed,
5881 * non-wired mappings, it can delay and batch the invalidation of TLB
5882 * entries without calling pmap_delayed_invl_started() and
5883 * pmap_delayed_invl_finished(). Because the pmap is not active on
5884 * any other processor, none of these TLB entries will ever be used
5885 * before their eventual invalidation. Consequently, there is no need
5886 * for either pmap_remove_all() or pmap_remove_write() to wait for
5887 * that eventual TLB invalidation.
5890 pmap_remove_pages(pmap_t pmap)
5893 pt_entry_t *pte, tpte;
5894 pt_entry_t PG_M, PG_RW, PG_V;
5895 struct spglist free;
5896 vm_page_t m, mpte, mt;
5898 struct md_page *pvh;
5899 struct pv_chunk *pc, *npc;
5900 struct rwlock *lock;
5902 uint64_t inuse, bitmask;
5903 int allfree, field, freed, idx;
5904 boolean_t superpage;
5908 * Assert that the given pmap is only active on the current
5909 * CPU. Unfortunately, we cannot block another CPU from
5910 * activating the pmap while this function is executing.
5912 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5915 cpuset_t other_cpus;
5917 other_cpus = all_cpus;
5919 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5920 CPU_AND(&other_cpus, &pmap->pm_active);
5922 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5927 PG_M = pmap_modified_bit(pmap);
5928 PG_V = pmap_valid_bit(pmap);
5929 PG_RW = pmap_rw_bit(pmap);
5933 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5936 for (field = 0; field < _NPCM; field++) {
5937 inuse = ~pc->pc_map[field] & pc_freemask[field];
5938 while (inuse != 0) {
5940 bitmask = 1UL << bit;
5941 idx = field * 64 + bit;
5942 pv = &pc->pc_pventry[idx];
5945 pte = pmap_pdpe(pmap, pv->pv_va);
5947 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5949 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5952 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5954 pte = &pte[pmap_pte_index(pv->pv_va)];
5958 * Keep track whether 'tpte' is a
5959 * superpage explicitly instead of
5960 * relying on PG_PS being set.
5962 * This is because PG_PS is numerically
5963 * identical to PG_PTE_PAT and thus a
5964 * regular page could be mistaken for
5970 if ((tpte & PG_V) == 0) {
5971 panic("bad pte va %lx pte %lx",
5976 * We cannot remove wired pages from a process' mapping at this time
5984 pa = tpte & PG_PS_FRAME;
5986 pa = tpte & PG_FRAME;
5988 m = PHYS_TO_VM_PAGE(pa);
5989 KASSERT(m->phys_addr == pa,
5990 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5991 m, (uintmax_t)m->phys_addr,
5994 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5995 m < &vm_page_array[vm_page_array_size],
5996 ("pmap_remove_pages: bad tpte %#jx",
6002 * Update the vm_page_t clean/reference bits.
6004 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6006 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6012 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
6015 pc->pc_map[field] |= bitmask;
6017 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
6018 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
6019 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6021 if (TAILQ_EMPTY(&pvh->pv_list)) {
6022 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6023 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
6024 TAILQ_EMPTY(&mt->md.pv_list))
6025 vm_page_aflag_clear(mt, PGA_WRITEABLE);
6027 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
6029 pmap_resident_count_dec(pmap, 1);
6030 KASSERT(mpte->wire_count == NPTEPG,
6031 ("pmap_remove_pages: pte page wire count error"));
6032 mpte->wire_count = 0;
6033 pmap_add_delayed_free_list(mpte, &free, FALSE);
6036 pmap_resident_count_dec(pmap, 1);
6037 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6039 if ((m->aflags & PGA_WRITEABLE) != 0 &&
6040 TAILQ_EMPTY(&m->md.pv_list) &&
6041 (m->flags & PG_FICTITIOUS) == 0) {
6042 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6043 if (TAILQ_EMPTY(&pvh->pv_list))
6044 vm_page_aflag_clear(m, PGA_WRITEABLE);
6047 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
6051 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
6052 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
6053 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
6055 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
6061 pmap_invalidate_all(pmap);
6063 pmap_free_zero_pages(&free);
6067 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
6069 struct rwlock *lock;
6071 struct md_page *pvh;
6072 pt_entry_t *pte, mask;
6073 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6075 int md_gen, pvh_gen;
6079 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6082 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6084 if (!PMAP_TRYLOCK(pmap)) {
6085 md_gen = m->md.pv_gen;
6089 if (md_gen != m->md.pv_gen) {
6094 pte = pmap_pte(pmap, pv->pv_va);
6097 PG_M = pmap_modified_bit(pmap);
6098 PG_RW = pmap_rw_bit(pmap);
6099 mask |= PG_RW | PG_M;
6102 PG_A = pmap_accessed_bit(pmap);
6103 PG_V = pmap_valid_bit(pmap);
6104 mask |= PG_V | PG_A;
6106 rv = (*pte & mask) == mask;
6111 if ((m->flags & PG_FICTITIOUS) == 0) {
6112 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6113 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
6115 if (!PMAP_TRYLOCK(pmap)) {
6116 md_gen = m->md.pv_gen;
6117 pvh_gen = pvh->pv_gen;
6121 if (md_gen != m->md.pv_gen ||
6122 pvh_gen != pvh->pv_gen) {
6127 pte = pmap_pde(pmap, pv->pv_va);
6130 PG_M = pmap_modified_bit(pmap);
6131 PG_RW = pmap_rw_bit(pmap);
6132 mask |= PG_RW | PG_M;
6135 PG_A = pmap_accessed_bit(pmap);
6136 PG_V = pmap_valid_bit(pmap);
6137 mask |= PG_V | PG_A;
6139 rv = (*pte & mask) == mask;
6153 * Return whether or not the specified physical page was modified
6154 * in any physical maps.
6157 pmap_is_modified(vm_page_t m)
6160 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6161 ("pmap_is_modified: page %p is not managed", m));
6164 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6165 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
6166 * is clear, no PTEs can have PG_M set.
6168 VM_OBJECT_ASSERT_WLOCKED(m->object);
6169 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6171 return (pmap_page_test_mappings(m, FALSE, TRUE));
6175 * pmap_is_prefaultable:
6177 * Return whether or not the specified virtual address is eligible
6181 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
6184 pt_entry_t *pte, PG_V;
6187 PG_V = pmap_valid_bit(pmap);
6190 pde = pmap_pde(pmap, addr);
6191 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
6192 pte = pmap_pde_to_pte(pde, addr);
6193 rv = (*pte & PG_V) == 0;
6200 * pmap_is_referenced:
6202 * Return whether or not the specified physical page was referenced
6203 * in any physical maps.
6206 pmap_is_referenced(vm_page_t m)
6209 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6210 ("pmap_is_referenced: page %p is not managed", m));
6211 return (pmap_page_test_mappings(m, TRUE, FALSE));
6215 * Clear the write and modified bits in each of the given page's mappings.
6218 pmap_remove_write(vm_page_t m)
6220 struct md_page *pvh;
6222 struct rwlock *lock;
6223 pv_entry_t next_pv, pv;
6225 pt_entry_t oldpte, *pte, PG_M, PG_RW;
6227 int pvh_gen, md_gen;
6229 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6230 ("pmap_remove_write: page %p is not managed", m));
6233 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6234 * set by another thread while the object is locked. Thus,
6235 * if PGA_WRITEABLE is clear, no page table entries need updating.
6237 VM_OBJECT_ASSERT_WLOCKED(m->object);
6238 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6240 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6241 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6242 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6245 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6247 if (!PMAP_TRYLOCK(pmap)) {
6248 pvh_gen = pvh->pv_gen;
6252 if (pvh_gen != pvh->pv_gen) {
6258 PG_RW = pmap_rw_bit(pmap);
6260 pde = pmap_pde(pmap, va);
6261 if ((*pde & PG_RW) != 0)
6262 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6263 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6264 ("inconsistent pv lock %p %p for page %p",
6265 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6268 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6270 if (!PMAP_TRYLOCK(pmap)) {
6271 pvh_gen = pvh->pv_gen;
6272 md_gen = m->md.pv_gen;
6276 if (pvh_gen != pvh->pv_gen ||
6277 md_gen != m->md.pv_gen) {
6283 PG_M = pmap_modified_bit(pmap);
6284 PG_RW = pmap_rw_bit(pmap);
6285 pde = pmap_pde(pmap, pv->pv_va);
6286 KASSERT((*pde & PG_PS) == 0,
6287 ("pmap_remove_write: found a 2mpage in page %p's pv list",
6289 pte = pmap_pde_to_pte(pde, pv->pv_va);
6292 if (oldpte & PG_RW) {
6293 if (!atomic_cmpset_long(pte, oldpte, oldpte &
6296 if ((oldpte & PG_M) != 0)
6298 pmap_invalidate_page(pmap, pv->pv_va);
6303 vm_page_aflag_clear(m, PGA_WRITEABLE);
6304 pmap_delayed_invl_wait(m);
6307 static __inline boolean_t
6308 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
6311 if (!pmap_emulate_ad_bits(pmap))
6314 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
6317 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
6318 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
6319 * if the EPT_PG_WRITE bit is set.
6321 if ((pte & EPT_PG_WRITE) != 0)
6325 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
6327 if ((pte & EPT_PG_EXECUTE) == 0 ||
6328 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
6335 * pmap_ts_referenced:
6337 * Return a count of reference bits for a page, clearing those bits.
6338 * It is not necessary for every reference bit to be cleared, but it
6339 * is necessary that 0 only be returned when there are truly no
6340 * reference bits set.
6342 * As an optimization, update the page's dirty field if a modified bit is
6343 * found while counting reference bits. This opportunistic update can be
6344 * performed at low cost and can eliminate the need for some future calls
6345 * to pmap_is_modified(). However, since this function stops after
6346 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
6347 * dirty pages. Those dirty pages will only be detected by a future call
6348 * to pmap_is_modified().
6350 * A DI block is not needed within this function, because
6351 * invalidations are performed before the PV list lock is
6355 pmap_ts_referenced(vm_page_t m)
6357 struct md_page *pvh;
6360 struct rwlock *lock;
6361 pd_entry_t oldpde, *pde;
6362 pt_entry_t *pte, PG_A, PG_M, PG_RW;
6365 int cleared, md_gen, not_cleared, pvh_gen;
6366 struct spglist free;
6369 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6370 ("pmap_ts_referenced: page %p is not managed", m));
6373 pa = VM_PAGE_TO_PHYS(m);
6374 lock = PHYS_TO_PV_LIST_LOCK(pa);
6375 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
6379 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6380 goto small_mappings;
6386 if (!PMAP_TRYLOCK(pmap)) {
6387 pvh_gen = pvh->pv_gen;
6391 if (pvh_gen != pvh->pv_gen) {
6396 PG_A = pmap_accessed_bit(pmap);
6397 PG_M = pmap_modified_bit(pmap);
6398 PG_RW = pmap_rw_bit(pmap);
6400 pde = pmap_pde(pmap, pv->pv_va);
6402 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6404 * Although "oldpde" is mapping a 2MB page, because
6405 * this function is called at a 4KB page granularity,
6406 * we only update the 4KB page under test.
6410 if ((oldpde & PG_A) != 0) {
6412 * Since this reference bit is shared by 512 4KB
6413 * pages, it should not be cleared every time it is
6414 * tested. Apply a simple "hash" function on the
6415 * physical page number, the virtual superpage number,
6416 * and the pmap address to select one 4KB page out of
6417 * the 512 on which testing the reference bit will
6418 * result in clearing that reference bit. This
6419 * function is designed to avoid the selection of the
6420 * same 4KB page for every 2MB page mapping.
6422 * On demotion, a mapping that hasn't been referenced
6423 * is simply destroyed. To avoid the possibility of a
6424 * subsequent page fault on a demoted wired mapping,
6425 * always leave its reference bit set. Moreover,
6426 * since the superpage is wired, the current state of
6427 * its reference bit won't affect page replacement.
6429 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
6430 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
6431 (oldpde & PG_W) == 0) {
6432 if (safe_to_clear_referenced(pmap, oldpde)) {
6433 atomic_clear_long(pde, PG_A);
6434 pmap_invalidate_page(pmap, pv->pv_va);
6436 } else if (pmap_demote_pde_locked(pmap, pde,
6437 pv->pv_va, &lock)) {
6439 * Remove the mapping to a single page
6440 * so that a subsequent access may
6441 * repromote. Since the underlying
6442 * page table page is fully populated,
6443 * this removal never frees a page
6447 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6449 pte = pmap_pde_to_pte(pde, va);
6450 pmap_remove_pte(pmap, pte, va, *pde,
6452 pmap_invalidate_page(pmap, va);
6458 * The superpage mapping was removed
6459 * entirely and therefore 'pv' is no
6467 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6468 ("inconsistent pv lock %p %p for page %p",
6469 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6474 /* Rotate the PV list if it has more than one entry. */
6475 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6476 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6477 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6480 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6482 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6484 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6491 if (!PMAP_TRYLOCK(pmap)) {
6492 pvh_gen = pvh->pv_gen;
6493 md_gen = m->md.pv_gen;
6497 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6502 PG_A = pmap_accessed_bit(pmap);
6503 PG_M = pmap_modified_bit(pmap);
6504 PG_RW = pmap_rw_bit(pmap);
6505 pde = pmap_pde(pmap, pv->pv_va);
6506 KASSERT((*pde & PG_PS) == 0,
6507 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6509 pte = pmap_pde_to_pte(pde, pv->pv_va);
6510 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6512 if ((*pte & PG_A) != 0) {
6513 if (safe_to_clear_referenced(pmap, *pte)) {
6514 atomic_clear_long(pte, PG_A);
6515 pmap_invalidate_page(pmap, pv->pv_va);
6517 } else if ((*pte & PG_W) == 0) {
6519 * Wired pages cannot be paged out so
6520 * doing accessed bit emulation for
6521 * them is wasted effort. We do the
6522 * hard work for unwired pages only.
6524 pmap_remove_pte(pmap, pte, pv->pv_va,
6525 *pde, &free, &lock);
6526 pmap_invalidate_page(pmap, pv->pv_va);
6531 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6532 ("inconsistent pv lock %p %p for page %p",
6533 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6538 /* Rotate the PV list if it has more than one entry. */
6539 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6540 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6541 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6544 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6545 not_cleared < PMAP_TS_REFERENCED_MAX);
6548 pmap_free_zero_pages(&free);
6549 return (cleared + not_cleared);
6553 * Apply the given advice to the specified range of addresses within the
6554 * given pmap. Depending on the advice, clear the referenced and/or
6555 * modified flags in each mapping and set the mapped page's dirty field.
6558 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6560 struct rwlock *lock;
6561 pml4_entry_t *pml4e;
6563 pd_entry_t oldpde, *pde;
6564 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6565 vm_offset_t va, va_next;
6567 boolean_t anychanged;
6569 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6573 * A/D bit emulation requires an alternate code path when clearing
6574 * the modified and accessed bits below. Since this function is
6575 * advisory in nature we skip it entirely for pmaps that require
6576 * A/D bit emulation.
6578 if (pmap_emulate_ad_bits(pmap))
6581 PG_A = pmap_accessed_bit(pmap);
6582 PG_G = pmap_global_bit(pmap);
6583 PG_M = pmap_modified_bit(pmap);
6584 PG_V = pmap_valid_bit(pmap);
6585 PG_RW = pmap_rw_bit(pmap);
6587 pmap_delayed_invl_started();
6589 for (; sva < eva; sva = va_next) {
6590 pml4e = pmap_pml4e(pmap, sva);
6591 if ((*pml4e & PG_V) == 0) {
6592 va_next = (sva + NBPML4) & ~PML4MASK;
6597 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6598 if ((*pdpe & PG_V) == 0) {
6599 va_next = (sva + NBPDP) & ~PDPMASK;
6604 va_next = (sva + NBPDR) & ~PDRMASK;
6607 pde = pmap_pdpe_to_pde(pdpe, sva);
6609 if ((oldpde & PG_V) == 0)
6611 else if ((oldpde & PG_PS) != 0) {
6612 if ((oldpde & PG_MANAGED) == 0)
6615 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6620 * The large page mapping was destroyed.
6626 * Unless the page mappings are wired, remove the
6627 * mapping to a single page so that a subsequent
6628 * access may repromote. Since the underlying page
6629 * table page is fully populated, this removal never
6630 * frees a page table page.
6632 if ((oldpde & PG_W) == 0) {
6633 pte = pmap_pde_to_pte(pde, sva);
6634 KASSERT((*pte & PG_V) != 0,
6635 ("pmap_advise: invalid PTE"));
6636 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6646 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6648 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6650 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6651 if (advice == MADV_DONTNEED) {
6653 * Future calls to pmap_is_modified()
6654 * can be avoided by making the page
6657 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6660 atomic_clear_long(pte, PG_M | PG_A);
6661 } else if ((*pte & PG_A) != 0)
6662 atomic_clear_long(pte, PG_A);
6666 if ((*pte & PG_G) != 0) {
6673 if (va != va_next) {
6674 pmap_invalidate_range(pmap, va, sva);
6679 pmap_invalidate_range(pmap, va, sva);
6682 pmap_invalidate_all(pmap);
6684 pmap_delayed_invl_finished();
6688 * Clear the modify bits on the specified physical page.
6691 pmap_clear_modify(vm_page_t m)
6693 struct md_page *pvh;
6695 pv_entry_t next_pv, pv;
6696 pd_entry_t oldpde, *pde;
6697 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6698 struct rwlock *lock;
6700 int md_gen, pvh_gen;
6702 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6703 ("pmap_clear_modify: page %p is not managed", m));
6704 VM_OBJECT_ASSERT_WLOCKED(m->object);
6705 KASSERT(!vm_page_xbusied(m),
6706 ("pmap_clear_modify: page %p is exclusive busied", m));
6709 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6710 * If the object containing the page is locked and the page is not
6711 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6713 if ((m->aflags & PGA_WRITEABLE) == 0)
6715 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6716 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6717 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6720 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6722 if (!PMAP_TRYLOCK(pmap)) {
6723 pvh_gen = pvh->pv_gen;
6727 if (pvh_gen != pvh->pv_gen) {
6732 PG_M = pmap_modified_bit(pmap);
6733 PG_V = pmap_valid_bit(pmap);
6734 PG_RW = pmap_rw_bit(pmap);
6736 pde = pmap_pde(pmap, va);
6738 if ((oldpde & PG_RW) != 0) {
6739 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6740 if ((oldpde & PG_W) == 0) {
6742 * Write protect the mapping to a
6743 * single page so that a subsequent
6744 * write access may repromote.
6746 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6748 pte = pmap_pde_to_pte(pde, va);
6750 if ((oldpte & PG_V) != 0) {
6751 while (!atomic_cmpset_long(pte,
6753 oldpte & ~(PG_M | PG_RW)))
6756 pmap_invalidate_page(pmap, va);
6763 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6765 if (!PMAP_TRYLOCK(pmap)) {
6766 md_gen = m->md.pv_gen;
6767 pvh_gen = pvh->pv_gen;
6771 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6776 PG_M = pmap_modified_bit(pmap);
6777 PG_RW = pmap_rw_bit(pmap);
6778 pde = pmap_pde(pmap, pv->pv_va);
6779 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6780 " a 2mpage in page %p's pv list", m));
6781 pte = pmap_pde_to_pte(pde, pv->pv_va);
6782 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6783 atomic_clear_long(pte, PG_M);
6784 pmap_invalidate_page(pmap, pv->pv_va);
6792 * Miscellaneous support routines follow
6795 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6796 static __inline void
6797 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6802 * The cache mode bits are all in the low 32-bits of the
6803 * PTE, so we can just spin on updating the low 32-bits.
6806 opte = *(u_int *)pte;
6807 npte = opte & ~mask;
6809 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6812 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6813 static __inline void
6814 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6819 * The cache mode bits are all in the low 32-bits of the
6820 * PDE, so we can just spin on updating the low 32-bits.
6823 opde = *(u_int *)pde;
6824 npde = opde & ~mask;
6826 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6830 * Map a set of physical memory pages into the kernel virtual
6831 * address space. Return a pointer to where it is mapped. This
6832 * routine is intended to be used for mapping device memory,
6836 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6838 struct pmap_preinit_mapping *ppim;
6839 vm_offset_t va, offset;
6843 offset = pa & PAGE_MASK;
6844 size = round_page(offset + size);
6845 pa = trunc_page(pa);
6847 if (!pmap_initialized) {
6849 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6850 ppim = pmap_preinit_mapping + i;
6851 if (ppim->va == 0) {
6855 ppim->va = virtual_avail;
6856 virtual_avail += size;
6862 panic("%s: too many preinit mappings", __func__);
6865 * If we have a preinit mapping, re-use it.
6867 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6868 ppim = pmap_preinit_mapping + i;
6869 if (ppim->pa == pa && ppim->sz == size &&
6871 return ((void *)(ppim->va + offset));
6874 * If the specified range of physical addresses fits within
6875 * the direct map window, use the direct map.
6877 if (pa < dmaplimit && pa + size < dmaplimit) {
6878 va = PHYS_TO_DMAP(pa);
6879 if (!pmap_change_attr(va, size, mode))
6880 return ((void *)(va + offset));
6882 va = kva_alloc(size);
6884 panic("%s: Couldn't allocate KVA", __func__);
6886 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6887 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6888 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6889 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6890 return ((void *)(va + offset));
6894 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6897 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6901 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6904 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6908 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6910 struct pmap_preinit_mapping *ppim;
6914 /* If we gave a direct map region in pmap_mapdev, do nothing */
6915 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6917 offset = va & PAGE_MASK;
6918 size = round_page(offset + size);
6919 va = trunc_page(va);
6920 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6921 ppim = pmap_preinit_mapping + i;
6922 if (ppim->va == va && ppim->sz == size) {
6923 if (pmap_initialized)
6929 if (va + size == virtual_avail)
6934 if (pmap_initialized)
6939 * Tries to demote a 1GB page mapping.
6942 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6944 pdp_entry_t newpdpe, oldpdpe;
6945 pd_entry_t *firstpde, newpde, *pde;
6946 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6950 PG_A = pmap_accessed_bit(pmap);
6951 PG_M = pmap_modified_bit(pmap);
6952 PG_V = pmap_valid_bit(pmap);
6953 PG_RW = pmap_rw_bit(pmap);
6955 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6957 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6958 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6959 if ((pdpg = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6960 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6961 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6962 " in pmap %p", va, pmap);
6965 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
6966 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
6967 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6968 KASSERT((oldpdpe & PG_A) != 0,
6969 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6970 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6971 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
6975 * Initialize the page directory page.
6977 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
6983 * Demote the mapping.
6988 * Invalidate a stale recursive mapping of the page directory page.
6990 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
6992 pmap_pdpe_demotions++;
6993 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
6994 " in pmap %p", va, pmap);
6999 * Sets the memory attribute for the specified page.
7002 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
7005 m->md.pat_mode = ma;
7008 * If "m" is a normal page, update its direct mapping. This update
7009 * can be relied upon to perform any cache operations that are
7010 * required for data coherence.
7012 if ((m->flags & PG_FICTITIOUS) == 0 &&
7013 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
7015 panic("memory attribute change on the direct map failed");
7019 * Changes the specified virtual address range's memory type to that given by
7020 * the parameter "mode". The specified virtual address range must be
7021 * completely contained within either the direct map or the kernel map. If
7022 * the virtual address range is contained within the kernel map, then the
7023 * memory type for each of the corresponding ranges of the direct map is also
7024 * changed. (The corresponding ranges of the direct map are those ranges that
7025 * map the same physical pages as the specified virtual address range.) These
7026 * changes to the direct map are necessary because Intel describes the
7027 * behavior of their processors as "undefined" if two or more mappings to the
7028 * same physical page have different memory types.
7030 * Returns zero if the change completed successfully, and either EINVAL or
7031 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
7032 * of the virtual address range was not mapped, and ENOMEM is returned if
7033 * there was insufficient memory available to complete the change. In the
7034 * latter case, the memory type may have been changed on some part of the
7035 * virtual address range or the direct map.
7038 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
7042 PMAP_LOCK(kernel_pmap);
7043 error = pmap_change_attr_locked(va, size, mode);
7044 PMAP_UNLOCK(kernel_pmap);
7049 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
7051 vm_offset_t base, offset, tmpva;
7052 vm_paddr_t pa_start, pa_end, pa_end1;
7056 int cache_bits_pte, cache_bits_pde, error;
7059 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
7060 base = trunc_page(va);
7061 offset = va & PAGE_MASK;
7062 size = round_page(offset + size);
7065 * Only supported on kernel virtual addresses, including the direct
7066 * map but excluding the recursive map.
7068 if (base < DMAP_MIN_ADDRESS)
7071 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
7072 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
7076 * Pages that aren't mapped aren't supported. Also break down 2MB pages
7077 * into 4KB pages if required.
7079 for (tmpva = base; tmpva < base + size; ) {
7080 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7081 if (pdpe == NULL || *pdpe == 0)
7083 if (*pdpe & PG_PS) {
7085 * If the current 1GB page already has the required
7086 * memory type, then we need not demote this page. Just
7087 * increment tmpva to the next 1GB page frame.
7089 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
7090 tmpva = trunc_1gpage(tmpva) + NBPDP;
7095 * If the current offset aligns with a 1GB page frame
7096 * and there is at least 1GB left within the range, then
7097 * we need not break down this page into 2MB pages.
7099 if ((tmpva & PDPMASK) == 0 &&
7100 tmpva + PDPMASK < base + size) {
7104 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
7107 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7112 * If the current 2MB page already has the required
7113 * memory type, then we need not demote this page. Just
7114 * increment tmpva to the next 2MB page frame.
7116 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
7117 tmpva = trunc_2mpage(tmpva) + NBPDR;
7122 * If the current offset aligns with a 2MB page frame
7123 * and there is at least 2MB left within the range, then
7124 * we need not break down this page into 4KB pages.
7126 if ((tmpva & PDRMASK) == 0 &&
7127 tmpva + PDRMASK < base + size) {
7131 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
7134 pte = pmap_pde_to_pte(pde, tmpva);
7142 * Ok, all the pages exist, so run through them updating their
7143 * cache mode if required.
7145 pa_start = pa_end = 0;
7146 for (tmpva = base; tmpva < base + size; ) {
7147 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7148 if (*pdpe & PG_PS) {
7149 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
7150 pmap_pde_attr(pdpe, cache_bits_pde,
7154 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7155 (*pdpe & PG_PS_FRAME) < dmaplimit) {
7156 if (pa_start == pa_end) {
7157 /* Start physical address run. */
7158 pa_start = *pdpe & PG_PS_FRAME;
7159 pa_end = pa_start + NBPDP;
7160 } else if (pa_end == (*pdpe & 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 = *pdpe & PG_PS_FRAME;
7171 pa_end = pa_start + NBPDP;
7174 tmpva = trunc_1gpage(tmpva) + NBPDP;
7177 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7179 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
7180 pmap_pde_attr(pde, cache_bits_pde,
7184 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7185 (*pde & PG_PS_FRAME) < dmaplimit) {
7186 if (pa_start == pa_end) {
7187 /* Start physical address run. */
7188 pa_start = *pde & PG_PS_FRAME;
7189 pa_end = pa_start + NBPDR;
7190 } else if (pa_end == (*pde & PG_PS_FRAME))
7193 /* Run ended, update direct map. */
7194 error = pmap_change_attr_locked(
7195 PHYS_TO_DMAP(pa_start),
7196 pa_end - pa_start, mode);
7199 /* Start physical address run. */
7200 pa_start = *pde & PG_PS_FRAME;
7201 pa_end = pa_start + NBPDR;
7204 tmpva = trunc_2mpage(tmpva) + NBPDR;
7206 pte = pmap_pde_to_pte(pde, tmpva);
7207 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
7208 pmap_pte_attr(pte, cache_bits_pte,
7212 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7213 (*pte & PG_FRAME) < dmaplimit) {
7214 if (pa_start == pa_end) {
7215 /* Start physical address run. */
7216 pa_start = *pte & PG_FRAME;
7217 pa_end = pa_start + PAGE_SIZE;
7218 } else if (pa_end == (*pte & PG_FRAME))
7219 pa_end += PAGE_SIZE;
7221 /* Run ended, update direct map. */
7222 error = pmap_change_attr_locked(
7223 PHYS_TO_DMAP(pa_start),
7224 pa_end - pa_start, mode);
7227 /* Start physical address run. */
7228 pa_start = *pte & PG_FRAME;
7229 pa_end = pa_start + PAGE_SIZE;
7235 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
7236 pa_end1 = MIN(pa_end, dmaplimit);
7237 if (pa_start != pa_end1)
7238 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
7239 pa_end1 - pa_start, mode);
7243 * Flush CPU caches if required to make sure any data isn't cached that
7244 * shouldn't be, etc.
7247 pmap_invalidate_range(kernel_pmap, base, tmpva);
7248 pmap_invalidate_cache_range(base, tmpva, FALSE);
7254 * Demotes any mapping within the direct map region that covers more than the
7255 * specified range of physical addresses. This range's size must be a power
7256 * of two and its starting address must be a multiple of its size. Since the
7257 * demotion does not change any attributes of the mapping, a TLB invalidation
7258 * is not mandatory. The caller may, however, request a TLB invalidation.
7261 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
7270 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
7271 KASSERT((base & (len - 1)) == 0,
7272 ("pmap_demote_DMAP: base is not a multiple of len"));
7273 if (len < NBPDP && base < dmaplimit) {
7274 va = PHYS_TO_DMAP(base);
7276 PMAP_LOCK(kernel_pmap);
7277 pdpe = pmap_pdpe(kernel_pmap, va);
7278 if ((*pdpe & X86_PG_V) == 0)
7279 panic("pmap_demote_DMAP: invalid PDPE");
7280 if ((*pdpe & PG_PS) != 0) {
7281 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
7282 panic("pmap_demote_DMAP: PDPE failed");
7286 pde = pmap_pdpe_to_pde(pdpe, va);
7287 if ((*pde & X86_PG_V) == 0)
7288 panic("pmap_demote_DMAP: invalid PDE");
7289 if ((*pde & PG_PS) != 0) {
7290 if (!pmap_demote_pde(kernel_pmap, pde, va))
7291 panic("pmap_demote_DMAP: PDE failed");
7295 if (changed && invalidate)
7296 pmap_invalidate_page(kernel_pmap, va);
7297 PMAP_UNLOCK(kernel_pmap);
7302 * perform the pmap work for mincore
7305 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
7308 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
7312 PG_A = pmap_accessed_bit(pmap);
7313 PG_M = pmap_modified_bit(pmap);
7314 PG_V = pmap_valid_bit(pmap);
7315 PG_RW = pmap_rw_bit(pmap);
7319 pdep = pmap_pde(pmap, addr);
7320 if (pdep != NULL && (*pdep & PG_V)) {
7321 if (*pdep & PG_PS) {
7323 /* Compute the physical address of the 4KB page. */
7324 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
7326 val = MINCORE_SUPER;
7328 pte = *pmap_pde_to_pte(pdep, addr);
7329 pa = pte & PG_FRAME;
7337 if ((pte & PG_V) != 0) {
7338 val |= MINCORE_INCORE;
7339 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7340 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
7341 if ((pte & PG_A) != 0)
7342 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
7344 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
7345 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
7346 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
7347 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
7348 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
7351 PA_UNLOCK_COND(*locked_pa);
7357 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
7359 uint32_t gen, new_gen, pcid_next;
7361 CRITICAL_ASSERT(curthread);
7362 gen = PCPU_GET(pcid_gen);
7363 if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN)
7364 return (pti ? 0 : CR3_PCID_SAVE);
7365 if (pmap->pm_pcids[cpuid].pm_gen == gen)
7366 return (CR3_PCID_SAVE);
7367 pcid_next = PCPU_GET(pcid_next);
7368 KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
7369 (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
7370 ("cpu %d pcid_next %#x", cpuid, pcid_next));
7371 if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
7372 (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
7376 PCPU_SET(pcid_gen, new_gen);
7377 pcid_next = PMAP_PCID_KERN + 1;
7381 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
7382 pmap->pm_pcids[cpuid].pm_gen = new_gen;
7383 PCPU_SET(pcid_next, pcid_next + 1);
7388 pmap_activate_sw(struct thread *td)
7390 pmap_t oldpmap, pmap;
7391 struct invpcid_descr d;
7392 uint64_t cached, cr3, kcr3, kern_pti_cached, rsp0, ucr3;
7395 struct amd64tss *tssp;
7397 oldpmap = PCPU_GET(curpmap);
7398 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7399 if (oldpmap == pmap)
7401 cpuid = PCPU_GET(cpuid);
7403 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7405 CPU_SET(cpuid, &pmap->pm_active);
7408 if (pmap_pcid_enabled) {
7409 cached = pmap_pcid_alloc(pmap, cpuid);
7410 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
7411 pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
7412 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
7413 pmap->pm_pcids[cpuid].pm_pcid));
7414 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
7415 pmap == kernel_pmap,
7416 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
7417 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
7420 * If the INVPCID instruction is not available,
7421 * invltlb_pcid_handler() is used for handle
7422 * invalidate_all IPI, which checks for curpmap ==
7423 * smp_tlb_pmap. Below operations sequence has a
7424 * window where %CR3 is loaded with the new pmap's
7425 * PML4 address, but curpmap value is not yet updated.
7426 * This causes invltlb IPI handler, called between the
7427 * updates, to execute as NOP, which leaves stale TLB
7430 * Note that the most typical use of
7431 * pmap_activate_sw(), from the context switch, is
7432 * immune to this race, because interrupts are
7433 * disabled (while the thread lock is owned), and IPI
7434 * happends after curpmap is updated. Protect other
7435 * callers in a similar way, by disabling interrupts
7436 * around the %cr3 register reload and curpmap
7440 rflags = intr_disable();
7442 kern_pti_cached = pti ? 0 : cached;
7443 if (!kern_pti_cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
7444 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
7447 PCPU_SET(curpmap, pmap);
7449 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid;
7450 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[cpuid].pm_pcid |
7453 if (!cached && pmap->pm_ucr3 != PMAP_NO_CR3) {
7455 * Manually invalidate translations cached
7456 * from the user page table. They are not
7457 * flushed by reload of cr3 with the kernel
7458 * page table pointer above.
7460 if (invpcid_works) {
7461 d.pcid = PMAP_PCID_USER_PT |
7462 pmap->pm_pcids[cpuid].pm_pcid;
7465 invpcid(&d, INVPCID_CTX);
7467 pmap_pti_pcid_invalidate(ucr3, kcr3);
7471 PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
7472 PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
7475 intr_restore(rflags);
7477 PCPU_INC(pm_save_cnt);
7478 } else if (cr3 != pmap->pm_cr3) {
7479 load_cr3(pmap->pm_cr3);
7480 PCPU_SET(curpmap, pmap);
7482 PCPU_SET(kcr3, pmap->pm_cr3);
7483 PCPU_SET(ucr3, pmap->pm_ucr3);
7486 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
7487 rsp0 = ((vm_offset_t)PCPU_PTR(pti_stack) +
7488 PC_PTI_STACK_SZ * sizeof(uint64_t)) & ~0xful;
7489 tssp = PCPU_GET(tssp);
7490 tssp->tss_rsp0 = rsp0;
7493 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
7495 CPU_CLR(cpuid, &oldpmap->pm_active);
7500 pmap_activate(struct thread *td)
7504 pmap_activate_sw(td);
7509 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
7514 * Increase the starting virtual address of the given mapping if a
7515 * different alignment might result in more superpage mappings.
7518 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7519 vm_offset_t *addr, vm_size_t size)
7521 vm_offset_t superpage_offset;
7525 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7526 offset += ptoa(object->pg_color);
7527 superpage_offset = offset & PDRMASK;
7528 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
7529 (*addr & PDRMASK) == superpage_offset)
7531 if ((*addr & PDRMASK) < superpage_offset)
7532 *addr = (*addr & ~PDRMASK) + superpage_offset;
7534 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
7538 static unsigned long num_dirty_emulations;
7539 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
7540 &num_dirty_emulations, 0, NULL);
7542 static unsigned long num_accessed_emulations;
7543 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
7544 &num_accessed_emulations, 0, NULL);
7546 static unsigned long num_superpage_accessed_emulations;
7547 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7548 &num_superpage_accessed_emulations, 0, NULL);
7550 static unsigned long ad_emulation_superpage_promotions;
7551 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7552 &ad_emulation_superpage_promotions, 0, NULL);
7553 #endif /* INVARIANTS */
7556 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7559 struct rwlock *lock;
7560 #if VM_NRESERVLEVEL > 0
7564 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7566 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7567 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7569 if (!pmap_emulate_ad_bits(pmap))
7572 PG_A = pmap_accessed_bit(pmap);
7573 PG_M = pmap_modified_bit(pmap);
7574 PG_V = pmap_valid_bit(pmap);
7575 PG_RW = pmap_rw_bit(pmap);
7581 pde = pmap_pde(pmap, va);
7582 if (pde == NULL || (*pde & PG_V) == 0)
7585 if ((*pde & PG_PS) != 0) {
7586 if (ftype == VM_PROT_READ) {
7588 atomic_add_long(&num_superpage_accessed_emulations, 1);
7596 pte = pmap_pde_to_pte(pde, va);
7597 if ((*pte & PG_V) == 0)
7600 if (ftype == VM_PROT_WRITE) {
7601 if ((*pte & PG_RW) == 0)
7604 * Set the modified and accessed bits simultaneously.
7606 * Intel EPT PTEs that do software emulation of A/D bits map
7607 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7608 * An EPT misconfiguration is triggered if the PTE is writable
7609 * but not readable (WR=10). This is avoided by setting PG_A
7610 * and PG_M simultaneously.
7612 *pte |= PG_M | PG_A;
7617 #if VM_NRESERVLEVEL > 0
7618 /* try to promote the mapping */
7619 if (va < VM_MAXUSER_ADDRESS)
7620 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7624 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7626 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7627 pmap_ps_enabled(pmap) &&
7628 (m->flags & PG_FICTITIOUS) == 0 &&
7629 vm_reserv_level_iffullpop(m) == 0) {
7630 pmap_promote_pde(pmap, pde, va, &lock);
7632 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7638 if (ftype == VM_PROT_WRITE)
7639 atomic_add_long(&num_dirty_emulations, 1);
7641 atomic_add_long(&num_accessed_emulations, 1);
7643 rv = 0; /* success */
7652 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7657 pt_entry_t *pte, PG_V;
7661 PG_V = pmap_valid_bit(pmap);
7664 pml4 = pmap_pml4e(pmap, va);
7666 if ((*pml4 & PG_V) == 0)
7669 pdp = pmap_pml4e_to_pdpe(pml4, va);
7671 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7674 pde = pmap_pdpe_to_pde(pdp, va);
7676 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7679 pte = pmap_pde_to_pte(pde, va);
7688 * Get the kernel virtual address of a set of physical pages. If there are
7689 * physical addresses not covered by the DMAP perform a transient mapping
7690 * that will be removed when calling pmap_unmap_io_transient.
7692 * \param page The pages the caller wishes to obtain the virtual
7693 * address on the kernel memory map.
7694 * \param vaddr On return contains the kernel virtual memory address
7695 * of the pages passed in the page parameter.
7696 * \param count Number of pages passed in.
7697 * \param can_fault TRUE if the thread using the mapped pages can take
7698 * page faults, FALSE otherwise.
7700 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7701 * finished or FALSE otherwise.
7705 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7706 boolean_t can_fault)
7709 boolean_t needs_mapping;
7711 int cache_bits, error, i;
7714 * Allocate any KVA space that we need, this is done in a separate
7715 * loop to prevent calling vmem_alloc while pinned.
7717 needs_mapping = FALSE;
7718 for (i = 0; i < count; i++) {
7719 paddr = VM_PAGE_TO_PHYS(page[i]);
7720 if (__predict_false(paddr >= dmaplimit)) {
7721 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7722 M_BESTFIT | M_WAITOK, &vaddr[i]);
7723 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7724 needs_mapping = TRUE;
7726 vaddr[i] = PHYS_TO_DMAP(paddr);
7730 /* Exit early if everything is covered by the DMAP */
7735 * NB: The sequence of updating a page table followed by accesses
7736 * to the corresponding pages used in the !DMAP case is subject to
7737 * the situation described in the "AMD64 Architecture Programmer's
7738 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7739 * Coherency Considerations". Therefore, issuing the INVLPG right
7740 * after modifying the PTE bits is crucial.
7744 for (i = 0; i < count; i++) {
7745 paddr = VM_PAGE_TO_PHYS(page[i]);
7746 if (paddr >= dmaplimit) {
7749 * Slow path, since we can get page faults
7750 * while mappings are active don't pin the
7751 * thread to the CPU and instead add a global
7752 * mapping visible to all CPUs.
7754 pmap_qenter(vaddr[i], &page[i], 1);
7756 pte = vtopte(vaddr[i]);
7757 cache_bits = pmap_cache_bits(kernel_pmap,
7758 page[i]->md.pat_mode, 0);
7759 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7766 return (needs_mapping);
7770 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7771 boolean_t can_fault)
7778 for (i = 0; i < count; i++) {
7779 paddr = VM_PAGE_TO_PHYS(page[i]);
7780 if (paddr >= dmaplimit) {
7782 pmap_qremove(vaddr[i], 1);
7783 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7789 pmap_quick_enter_page(vm_page_t m)
7793 paddr = VM_PAGE_TO_PHYS(m);
7794 if (paddr < dmaplimit)
7795 return (PHYS_TO_DMAP(paddr));
7796 mtx_lock_spin(&qframe_mtx);
7797 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7798 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7799 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7804 pmap_quick_remove_page(vm_offset_t addr)
7809 pte_store(vtopte(qframe), 0);
7811 mtx_unlock_spin(&qframe_mtx);
7815 pmap_pti_alloc_page(void)
7819 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7820 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_NOBUSY |
7821 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
7826 pmap_pti_free_page(vm_page_t m)
7829 KASSERT(m->wire_count > 0, ("page %p not wired", m));
7831 if (m->wire_count != 0)
7833 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
7834 vm_page_free_zero(m);
7848 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
7849 VM_OBJECT_WLOCK(pti_obj);
7850 pml4_pg = pmap_pti_alloc_page();
7851 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
7852 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
7853 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
7854 pdpe = pmap_pti_pdpe(va);
7855 pmap_pti_wire_pte(pdpe);
7857 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
7858 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
7859 pmap_pti_add_kva_locked((vm_offset_t)gdt, (vm_offset_t)gdt +
7860 sizeof(struct user_segment_descriptor) * NGDT * MAXCPU, false);
7861 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
7862 sizeof(struct gate_descriptor) * NIDT, false);
7863 pmap_pti_add_kva_locked((vm_offset_t)common_tss,
7864 (vm_offset_t)common_tss + sizeof(struct amd64tss) * MAXCPU, false);
7866 /* Doublefault stack IST 1 */
7867 va = common_tss[i].tss_ist1;
7868 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7869 /* NMI stack IST 2 */
7870 va = common_tss[i].tss_ist2 + sizeof(struct nmi_pcpu);
7871 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7872 /* MC# stack IST 3 */
7873 va = common_tss[i].tss_ist3 + sizeof(struct nmi_pcpu);
7874 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7875 /* DB# stack IST 4 */
7876 va = common_tss[i].tss_ist4 + sizeof(struct nmi_pcpu);
7877 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7879 pmap_pti_add_kva_locked((vm_offset_t)kernphys + KERNBASE,
7880 (vm_offset_t)etext, true);
7881 pti_finalized = true;
7882 VM_OBJECT_WUNLOCK(pti_obj);
7884 SYSINIT(pmap_pti, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_pti_init, NULL);
7886 static pdp_entry_t *
7887 pmap_pti_pdpe(vm_offset_t va)
7889 pml4_entry_t *pml4e;
7892 vm_pindex_t pml4_idx;
7895 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7897 pml4_idx = pmap_pml4e_index(va);
7898 pml4e = &pti_pml4[pml4_idx];
7902 panic("pml4 alloc after finalization\n");
7903 m = pmap_pti_alloc_page();
7905 pmap_pti_free_page(m);
7906 mphys = *pml4e & ~PAGE_MASK;
7908 mphys = VM_PAGE_TO_PHYS(m);
7909 *pml4e = mphys | X86_PG_RW | X86_PG_V;
7912 mphys = *pml4e & ~PAGE_MASK;
7914 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
7919 pmap_pti_wire_pte(void *pte)
7923 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7924 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7929 pmap_pti_unwire_pde(void *pde, bool only_ref)
7933 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7934 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
7935 MPASS(m->wire_count > 0);
7936 MPASS(only_ref || m->wire_count > 1);
7937 pmap_pti_free_page(m);
7941 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
7946 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7947 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7948 MPASS(m->wire_count > 0);
7949 if (pmap_pti_free_page(m)) {
7950 pde = pmap_pti_pde(va);
7951 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
7953 pmap_pti_unwire_pde(pde, false);
7958 pmap_pti_pde(vm_offset_t va)
7966 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7968 pdpe = pmap_pti_pdpe(va);
7970 m = pmap_pti_alloc_page();
7972 pmap_pti_free_page(m);
7973 MPASS((*pdpe & X86_PG_PS) == 0);
7974 mphys = *pdpe & ~PAGE_MASK;
7976 mphys = VM_PAGE_TO_PHYS(m);
7977 *pdpe = mphys | X86_PG_RW | X86_PG_V;
7980 MPASS((*pdpe & X86_PG_PS) == 0);
7981 mphys = *pdpe & ~PAGE_MASK;
7984 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
7985 pd_idx = pmap_pde_index(va);
7991 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
7998 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8000 pde = pmap_pti_pde(va);
8001 if (unwire_pde != NULL) {
8003 pmap_pti_wire_pte(pde);
8006 m = pmap_pti_alloc_page();
8008 pmap_pti_free_page(m);
8009 MPASS((*pde & X86_PG_PS) == 0);
8010 mphys = *pde & ~(PAGE_MASK | pg_nx);
8012 mphys = VM_PAGE_TO_PHYS(m);
8013 *pde = mphys | X86_PG_RW | X86_PG_V;
8014 if (unwire_pde != NULL)
8015 *unwire_pde = false;
8018 MPASS((*pde & X86_PG_PS) == 0);
8019 mphys = *pde & ~(PAGE_MASK | pg_nx);
8022 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
8023 pte += pmap_pte_index(va);
8029 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
8033 pt_entry_t *pte, ptev;
8036 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8038 sva = trunc_page(sva);
8039 MPASS(sva > VM_MAXUSER_ADDRESS);
8040 eva = round_page(eva);
8042 for (; sva < eva; sva += PAGE_SIZE) {
8043 pte = pmap_pti_pte(sva, &unwire_pde);
8044 pa = pmap_kextract(sva);
8045 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A | X86_PG_G |
8046 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
8047 VM_MEMATTR_DEFAULT, FALSE);
8049 pte_store(pte, ptev);
8050 pmap_pti_wire_pte(pte);
8052 KASSERT(!pti_finalized,
8053 ("pti overlap after fin %#lx %#lx %#lx",
8055 KASSERT(*pte == ptev,
8056 ("pti non-identical pte after fin %#lx %#lx %#lx",
8060 pde = pmap_pti_pde(sva);
8061 pmap_pti_unwire_pde(pde, true);
8067 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
8072 VM_OBJECT_WLOCK(pti_obj);
8073 pmap_pti_add_kva_locked(sva, eva, exec);
8074 VM_OBJECT_WUNLOCK(pti_obj);
8078 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
8085 sva = rounddown2(sva, PAGE_SIZE);
8086 MPASS(sva > VM_MAXUSER_ADDRESS);
8087 eva = roundup2(eva, PAGE_SIZE);
8089 VM_OBJECT_WLOCK(pti_obj);
8090 for (va = sva; va < eva; va += PAGE_SIZE) {
8091 pte = pmap_pti_pte(va, NULL);
8092 KASSERT((*pte & X86_PG_V) != 0,
8093 ("invalid pte va %#lx pte %#lx pt %#lx", va,
8094 (u_long)pte, *pte));
8096 pmap_pti_unwire_pte(pte, va);
8098 pmap_invalidate_range(kernel_pmap, sva, eva);
8099 VM_OBJECT_WUNLOCK(pti_obj);
8102 #include "opt_ddb.h"
8104 #include <ddb/ddb.h>
8106 DB_SHOW_COMMAND(pte, pmap_print_pte)
8112 pt_entry_t *pte, PG_V;
8116 va = (vm_offset_t)addr;
8117 pmap = PCPU_GET(curpmap); /* XXX */
8119 db_printf("show pte addr\n");
8122 PG_V = pmap_valid_bit(pmap);
8123 pml4 = pmap_pml4e(pmap, va);
8124 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
8125 if ((*pml4 & PG_V) == 0) {
8129 pdp = pmap_pml4e_to_pdpe(pml4, va);
8130 db_printf(" pdpe %#016lx", *pdp);
8131 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
8135 pde = pmap_pdpe_to_pde(pdp, va);
8136 db_printf(" pde %#016lx", *pde);
8137 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
8141 pte = pmap_pde_to_pte(pde, va);
8142 db_printf(" pte %#016lx\n", *pte);
8145 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
8150 a = (vm_paddr_t)addr;
8151 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
8153 db_printf("show phys2dmap addr\n");