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;
1106 * PMAP_PCID_KERN + 1 is used for initialization of
1107 * proc0 pmap. The pmap' pcid state might be used by
1108 * EFIRT entry before first context switch, so it
1109 * needs to be valid.
1111 PCPU_SET(pcid_next, PMAP_PCID_KERN + 2);
1112 PCPU_SET(pcid_gen, 1);
1115 * pcpu area for APs is zeroed during AP startup.
1116 * pc_pcid_next and pc_pcid_gen are initialized by AP
1117 * during pcpu setup.
1119 load_cr4(rcr4() | CR4_PCIDE);
1121 pmap_pcid_enabled = 0;
1126 * Setup the PAT MSR.
1131 int pat_table[PAT_INDEX_SIZE];
1136 /* Bail if this CPU doesn't implement PAT. */
1137 if ((cpu_feature & CPUID_PAT) == 0)
1140 /* Set default PAT index table. */
1141 for (i = 0; i < PAT_INDEX_SIZE; i++)
1143 pat_table[PAT_WRITE_BACK] = 0;
1144 pat_table[PAT_WRITE_THROUGH] = 1;
1145 pat_table[PAT_UNCACHEABLE] = 3;
1146 pat_table[PAT_WRITE_COMBINING] = 3;
1147 pat_table[PAT_WRITE_PROTECTED] = 3;
1148 pat_table[PAT_UNCACHED] = 3;
1150 /* Initialize default PAT entries. */
1151 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1152 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1153 PAT_VALUE(2, PAT_UNCACHED) |
1154 PAT_VALUE(3, PAT_UNCACHEABLE) |
1155 PAT_VALUE(4, PAT_WRITE_BACK) |
1156 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1157 PAT_VALUE(6, PAT_UNCACHED) |
1158 PAT_VALUE(7, PAT_UNCACHEABLE);
1162 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1163 * Program 5 and 6 as WP and WC.
1164 * Leave 4 and 7 as WB and UC.
1166 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1167 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1168 PAT_VALUE(6, PAT_WRITE_COMBINING);
1169 pat_table[PAT_UNCACHED] = 2;
1170 pat_table[PAT_WRITE_PROTECTED] = 5;
1171 pat_table[PAT_WRITE_COMBINING] = 6;
1174 * Just replace PAT Index 2 with WC instead of UC-.
1176 pat_msr &= ~PAT_MASK(2);
1177 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1178 pat_table[PAT_WRITE_COMBINING] = 2;
1183 load_cr4(cr4 & ~CR4_PGE);
1185 /* Disable caches (CD = 1, NW = 0). */
1187 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1189 /* Flushes caches and TLBs. */
1193 /* Update PAT and index table. */
1194 wrmsr(MSR_PAT, pat_msr);
1195 for (i = 0; i < PAT_INDEX_SIZE; i++)
1196 pat_index[i] = pat_table[i];
1198 /* Flush caches and TLBs again. */
1202 /* Restore caches and PGE. */
1208 * Initialize a vm_page's machine-dependent fields.
1211 pmap_page_init(vm_page_t m)
1214 TAILQ_INIT(&m->md.pv_list);
1215 m->md.pat_mode = PAT_WRITE_BACK;
1219 * Initialize the pmap module.
1220 * Called by vm_init, to initialize any structures that the pmap
1221 * system needs to map virtual memory.
1226 struct pmap_preinit_mapping *ppim;
1229 int error, i, pv_npg, ret, skz63;
1231 /* L1TF, reserve page @0 unconditionally */
1232 vm_page_blacklist_add(0, bootverbose);
1234 /* Detect bare-metal Skylake Server and Skylake-X. */
1235 if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
1236 CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
1238 * Skylake-X errata SKZ63. Processor May Hang When
1239 * Executing Code In an HLE Transaction Region between
1240 * 40000000H and 403FFFFFH.
1242 * Mark the pages in the range as preallocated. It
1243 * seems to be impossible to distinguish between
1244 * Skylake Server and Skylake X.
1247 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
1250 printf("SKZ63: skipping 4M RAM starting "
1251 "at physical 1G\n");
1252 for (i = 0; i < atop(0x400000); i++) {
1253 ret = vm_page_blacklist_add(0x40000000 +
1255 if (!ret && bootverbose)
1256 printf("page at %#lx already used\n",
1257 0x40000000 + ptoa(i));
1263 * Initialize the vm page array entries for the kernel pmap's
1266 PMAP_LOCK(kernel_pmap);
1267 for (i = 0; i < nkpt; i++) {
1268 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1269 KASSERT(mpte >= vm_page_array &&
1270 mpte < &vm_page_array[vm_page_array_size],
1271 ("pmap_init: page table page is out of range"));
1272 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1273 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1274 mpte->wire_count = 1;
1275 if (i << PDRSHIFT < KERNend &&
1276 pmap_insert_pt_page(kernel_pmap, mpte))
1277 panic("pmap_init: pmap_insert_pt_page failed");
1279 PMAP_UNLOCK(kernel_pmap);
1280 atomic_add_int(&vm_cnt.v_wire_count, nkpt);
1283 * If the kernel is running on a virtual machine, then it must assume
1284 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1285 * be prepared for the hypervisor changing the vendor and family that
1286 * are reported by CPUID. Consequently, the workaround for AMD Family
1287 * 10h Erratum 383 is enabled if the processor's feature set does not
1288 * include at least one feature that is only supported by older Intel
1289 * or newer AMD processors.
1291 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1292 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1293 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1295 workaround_erratum383 = 1;
1298 * Are large page mappings enabled?
1300 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1301 if (pg_ps_enabled) {
1302 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1303 ("pmap_init: can't assign to pagesizes[1]"));
1304 pagesizes[1] = NBPDR;
1308 * Initialize the pv chunk list mutex.
1310 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1313 * Initialize the pool of pv list locks.
1315 for (i = 0; i < NPV_LIST_LOCKS; i++)
1316 rw_init(&pv_list_locks[i], "pmap pv list");
1319 * Calculate the size of the pv head table for superpages.
1321 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1324 * Allocate memory for the pv head table for superpages.
1326 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1328 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1330 for (i = 0; i < pv_npg; i++)
1331 TAILQ_INIT(&pv_table[i].pv_list);
1332 TAILQ_INIT(&pv_dummy.pv_list);
1334 pmap_initialized = 1;
1335 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1336 ppim = pmap_preinit_mapping + i;
1339 /* Make the direct map consistent */
1340 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1341 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1342 ppim->sz, ppim->mode);
1346 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1347 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1350 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1351 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1352 (vmem_addr_t *)&qframe);
1354 panic("qframe allocation failed");
1357 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1358 "2MB page mapping counters");
1360 static u_long pmap_pde_demotions;
1361 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1362 &pmap_pde_demotions, 0, "2MB page demotions");
1364 static u_long pmap_pde_mappings;
1365 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1366 &pmap_pde_mappings, 0, "2MB page mappings");
1368 static u_long pmap_pde_p_failures;
1369 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1370 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1372 static u_long pmap_pde_promotions;
1373 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1374 &pmap_pde_promotions, 0, "2MB page promotions");
1376 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1377 "1GB page mapping counters");
1379 static u_long pmap_pdpe_demotions;
1380 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1381 &pmap_pdpe_demotions, 0, "1GB page demotions");
1383 /***************************************************
1384 * Low level helper routines.....
1385 ***************************************************/
1388 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1390 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1392 switch (pmap->pm_type) {
1395 /* Verify that both PAT bits are not set at the same time */
1396 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1397 ("Invalid PAT bits in entry %#lx", entry));
1399 /* Swap the PAT bits if one of them is set */
1400 if ((entry & x86_pat_bits) != 0)
1401 entry ^= x86_pat_bits;
1405 * Nothing to do - the memory attributes are represented
1406 * the same way for regular pages and superpages.
1410 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1417 * Determine the appropriate bits to set in a PTE or PDE for a specified
1421 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1423 int cache_bits, pat_flag, pat_idx;
1425 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1426 panic("Unknown caching mode %d\n", mode);
1428 switch (pmap->pm_type) {
1431 /* The PAT bit is different for PTE's and PDE's. */
1432 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1434 /* Map the caching mode to a PAT index. */
1435 pat_idx = pat_index[mode];
1437 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1440 cache_bits |= pat_flag;
1442 cache_bits |= PG_NC_PCD;
1444 cache_bits |= PG_NC_PWT;
1448 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1452 panic("unsupported pmap type %d", pmap->pm_type);
1455 return (cache_bits);
1459 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1463 switch (pmap->pm_type) {
1466 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1469 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1472 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1479 pmap_ps_enabled(pmap_t pmap)
1482 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1486 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1489 switch (pmap->pm_type) {
1496 * This is a little bogus since the generation number is
1497 * supposed to be bumped up when a region of the address
1498 * space is invalidated in the page tables.
1500 * In this case the old PDE entry is valid but yet we want
1501 * to make sure that any mappings using the old entry are
1502 * invalidated in the TLB.
1504 * The reason this works as expected is because we rendezvous
1505 * "all" host cpus and force any vcpu context to exit as a
1508 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1511 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1513 pde_store(pde, newpde);
1517 * After changing the page size for the specified virtual address in the page
1518 * table, flush the corresponding entries from the processor's TLB. Only the
1519 * calling processor's TLB is affected.
1521 * The calling thread must be pinned to a processor.
1524 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1528 if (pmap_type_guest(pmap))
1531 KASSERT(pmap->pm_type == PT_X86,
1532 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1534 PG_G = pmap_global_bit(pmap);
1536 if ((newpde & PG_PS) == 0)
1537 /* Demotion: flush a specific 2MB page mapping. */
1539 else if ((newpde & PG_G) == 0)
1541 * Promotion: flush every 4KB page mapping from the TLB
1542 * because there are too many to flush individually.
1547 * Promotion: flush every 4KB page mapping from the TLB,
1548 * including any global (PG_G) mappings.
1556 * For SMP, these functions have to use the IPI mechanism for coherence.
1558 * N.B.: Before calling any of the following TLB invalidation functions,
1559 * the calling processor must ensure that all stores updating a non-
1560 * kernel page table are globally performed. Otherwise, another
1561 * processor could cache an old, pre-update entry without being
1562 * invalidated. This can happen one of two ways: (1) The pmap becomes
1563 * active on another processor after its pm_active field is checked by
1564 * one of the following functions but before a store updating the page
1565 * table is globally performed. (2) The pmap becomes active on another
1566 * processor before its pm_active field is checked but due to
1567 * speculative loads one of the following functions stills reads the
1568 * pmap as inactive on the other processor.
1570 * The kernel page table is exempt because its pm_active field is
1571 * immutable. The kernel page table is always active on every
1576 * Interrupt the cpus that are executing in the guest context.
1577 * This will force the vcpu to exit and the cached EPT mappings
1578 * will be invalidated by the host before the next vmresume.
1580 static __inline void
1581 pmap_invalidate_ept(pmap_t pmap)
1586 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1587 ("pmap_invalidate_ept: absurd pm_active"));
1590 * The TLB mappings associated with a vcpu context are not
1591 * flushed each time a different vcpu is chosen to execute.
1593 * This is in contrast with a process's vtop mappings that
1594 * are flushed from the TLB on each context switch.
1596 * Therefore we need to do more than just a TLB shootdown on
1597 * the active cpus in 'pmap->pm_active'. To do this we keep
1598 * track of the number of invalidations performed on this pmap.
1600 * Each vcpu keeps a cache of this counter and compares it
1601 * just before a vmresume. If the counter is out-of-date an
1602 * invept will be done to flush stale mappings from the TLB.
1604 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1607 * Force the vcpu to exit and trap back into the hypervisor.
1609 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1610 ipi_selected(pmap->pm_active, ipinum);
1615 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1618 struct invpcid_descr d;
1619 uint64_t kcr3, ucr3;
1623 if (pmap_type_guest(pmap)) {
1624 pmap_invalidate_ept(pmap);
1628 KASSERT(pmap->pm_type == PT_X86,
1629 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1632 if (pmap == kernel_pmap) {
1636 cpuid = PCPU_GET(cpuid);
1637 if (pmap == PCPU_GET(curpmap)) {
1639 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1641 * Disable context switching. pm_pcid
1642 * is recalculated on switch, which
1643 * might make us use wrong pcid below.
1646 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1648 if (invpcid_works) {
1649 d.pcid = pcid | PMAP_PCID_USER_PT;
1652 invpcid(&d, INVPCID_ADDR);
1654 kcr3 = pmap->pm_cr3 | pcid |
1656 ucr3 = pmap->pm_ucr3 | pcid |
1657 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1658 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1662 } else if (pmap_pcid_enabled)
1663 pmap->pm_pcids[cpuid].pm_gen = 0;
1664 if (pmap_pcid_enabled) {
1667 pmap->pm_pcids[i].pm_gen = 0;
1671 * The fence is between stores to pm_gen and the read of
1672 * the pm_active mask. We need to ensure that it is
1673 * impossible for us to miss the bit update in pm_active
1674 * and simultaneously observe a non-zero pm_gen in
1675 * pmap_activate_sw(), otherwise TLB update is missed.
1676 * Without the fence, IA32 allows such an outcome.
1677 * Note that pm_active is updated by a locked operation,
1678 * which provides the reciprocal fence.
1680 atomic_thread_fence_seq_cst();
1682 mask = &pmap->pm_active;
1684 smp_masked_invlpg(*mask, va, pmap);
1688 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1689 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1692 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1695 struct invpcid_descr d;
1697 uint64_t kcr3, ucr3;
1701 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1702 pmap_invalidate_all(pmap);
1706 if (pmap_type_guest(pmap)) {
1707 pmap_invalidate_ept(pmap);
1711 KASSERT(pmap->pm_type == PT_X86,
1712 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1715 cpuid = PCPU_GET(cpuid);
1716 if (pmap == kernel_pmap) {
1717 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1721 if (pmap == PCPU_GET(curpmap)) {
1722 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1724 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1726 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1727 if (invpcid_works) {
1728 d.pcid = pcid | PMAP_PCID_USER_PT;
1731 for (; d.addr < eva; d.addr +=
1733 invpcid(&d, INVPCID_ADDR);
1735 kcr3 = pmap->pm_cr3 | pcid |
1737 ucr3 = pmap->pm_ucr3 | pcid |
1738 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1739 pmap_pti_pcid_invlrng(ucr3, kcr3, sva,
1744 } else if (pmap_pcid_enabled) {
1745 pmap->pm_pcids[cpuid].pm_gen = 0;
1747 if (pmap_pcid_enabled) {
1750 pmap->pm_pcids[i].pm_gen = 0;
1752 /* See the comment in pmap_invalidate_page(). */
1753 atomic_thread_fence_seq_cst();
1755 mask = &pmap->pm_active;
1757 smp_masked_invlpg_range(*mask, sva, eva, pmap);
1762 pmap_invalidate_all(pmap_t pmap)
1765 struct invpcid_descr d;
1766 uint64_t kcr3, ucr3;
1770 if (pmap_type_guest(pmap)) {
1771 pmap_invalidate_ept(pmap);
1775 KASSERT(pmap->pm_type == PT_X86,
1776 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1779 if (pmap == kernel_pmap) {
1780 if (pmap_pcid_enabled && invpcid_works) {
1781 bzero(&d, sizeof(d));
1782 invpcid(&d, INVPCID_CTXGLOB);
1788 cpuid = PCPU_GET(cpuid);
1789 if (pmap == PCPU_GET(curpmap)) {
1790 if (pmap_pcid_enabled) {
1792 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1793 if (invpcid_works) {
1797 invpcid(&d, INVPCID_CTX);
1798 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1799 d.pcid |= PMAP_PCID_USER_PT;
1800 invpcid(&d, INVPCID_CTX);
1803 kcr3 = pmap->pm_cr3 | pcid;
1804 ucr3 = pmap->pm_ucr3;
1805 if (ucr3 != PMAP_NO_CR3) {
1806 ucr3 |= pcid | PMAP_PCID_USER_PT;
1807 pmap_pti_pcid_invalidate(ucr3,
1817 } else if (pmap_pcid_enabled) {
1818 pmap->pm_pcids[cpuid].pm_gen = 0;
1820 if (pmap_pcid_enabled) {
1823 pmap->pm_pcids[i].pm_gen = 0;
1825 /* See the comment in pmap_invalidate_page(). */
1826 atomic_thread_fence_seq_cst();
1828 mask = &pmap->pm_active;
1830 smp_masked_invltlb(*mask, pmap);
1835 pmap_invalidate_cache(void)
1845 cpuset_t invalidate; /* processors that invalidate their TLB */
1850 u_int store; /* processor that updates the PDE */
1854 pmap_update_pde_action(void *arg)
1856 struct pde_action *act = arg;
1858 if (act->store == PCPU_GET(cpuid))
1859 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1863 pmap_update_pde_teardown(void *arg)
1865 struct pde_action *act = arg;
1867 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1868 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1872 * Change the page size for the specified virtual address in a way that
1873 * prevents any possibility of the TLB ever having two entries that map the
1874 * same virtual address using different page sizes. This is the recommended
1875 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1876 * machine check exception for a TLB state that is improperly diagnosed as a
1880 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1882 struct pde_action act;
1883 cpuset_t active, other_cpus;
1887 cpuid = PCPU_GET(cpuid);
1888 other_cpus = all_cpus;
1889 CPU_CLR(cpuid, &other_cpus);
1890 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1893 active = pmap->pm_active;
1895 if (CPU_OVERLAP(&active, &other_cpus)) {
1897 act.invalidate = active;
1901 act.newpde = newpde;
1902 CPU_SET(cpuid, &active);
1903 smp_rendezvous_cpus(active,
1904 smp_no_rendezvous_barrier, pmap_update_pde_action,
1905 pmap_update_pde_teardown, &act);
1907 pmap_update_pde_store(pmap, pde, newpde);
1908 if (CPU_ISSET(cpuid, &active))
1909 pmap_update_pde_invalidate(pmap, va, newpde);
1915 * Normal, non-SMP, invalidation functions.
1918 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1920 struct invpcid_descr d;
1921 uint64_t kcr3, ucr3;
1924 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1928 KASSERT(pmap->pm_type == PT_X86,
1929 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1931 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1933 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
1934 pmap->pm_ucr3 != PMAP_NO_CR3) {
1936 pcid = pmap->pm_pcids[0].pm_pcid;
1937 if (invpcid_works) {
1938 d.pcid = pcid | PMAP_PCID_USER_PT;
1941 invpcid(&d, INVPCID_ADDR);
1943 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
1944 ucr3 = pmap->pm_ucr3 | pcid |
1945 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1946 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1950 } else if (pmap_pcid_enabled)
1951 pmap->pm_pcids[0].pm_gen = 0;
1955 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1957 struct invpcid_descr d;
1959 uint64_t kcr3, ucr3;
1961 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1965 KASSERT(pmap->pm_type == PT_X86,
1966 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1968 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1969 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1971 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
1972 pmap->pm_ucr3 != PMAP_NO_CR3) {
1974 if (invpcid_works) {
1975 d.pcid = pmap->pm_pcids[0].pm_pcid |
1979 for (; d.addr < eva; d.addr += PAGE_SIZE)
1980 invpcid(&d, INVPCID_ADDR);
1982 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].
1983 pm_pcid | CR3_PCID_SAVE;
1984 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[0].
1985 pm_pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1986 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
1990 } else if (pmap_pcid_enabled) {
1991 pmap->pm_pcids[0].pm_gen = 0;
1996 pmap_invalidate_all(pmap_t pmap)
1998 struct invpcid_descr d;
1999 uint64_t kcr3, ucr3;
2001 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
2005 KASSERT(pmap->pm_type == PT_X86,
2006 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
2008 if (pmap == kernel_pmap) {
2009 if (pmap_pcid_enabled && invpcid_works) {
2010 bzero(&d, sizeof(d));
2011 invpcid(&d, INVPCID_CTXGLOB);
2015 } else if (pmap == PCPU_GET(curpmap)) {
2016 if (pmap_pcid_enabled) {
2018 if (invpcid_works) {
2019 d.pcid = pmap->pm_pcids[0].pm_pcid;
2022 invpcid(&d, INVPCID_CTX);
2023 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2024 d.pcid |= PMAP_PCID_USER_PT;
2025 invpcid(&d, INVPCID_CTX);
2028 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].pm_pcid;
2029 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2030 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[
2031 0].pm_pcid | PMAP_PCID_USER_PT;
2032 pmap_pti_pcid_invalidate(ucr3, kcr3);
2040 } else if (pmap_pcid_enabled) {
2041 pmap->pm_pcids[0].pm_gen = 0;
2046 pmap_invalidate_cache(void)
2053 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
2056 pmap_update_pde_store(pmap, pde, newpde);
2057 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
2058 pmap_update_pde_invalidate(pmap, va, newpde);
2060 pmap->pm_pcids[0].pm_gen = 0;
2065 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
2069 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
2070 * by a promotion that did not invalidate the 512 4KB page mappings
2071 * that might exist in the TLB. Consequently, at this point, the TLB
2072 * may hold both 4KB and 2MB page mappings for the address range [va,
2073 * va + NBPDR). Therefore, the entire range must be invalidated here.
2074 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
2075 * 4KB page mappings for the address range [va, va + NBPDR), and so a
2076 * single INVLPG suffices to invalidate the 2MB page mapping from the
2079 if ((pde & PG_PROMOTED) != 0)
2080 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
2082 pmap_invalidate_page(pmap, va);
2085 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
2088 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
2092 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
2094 KASSERT((sva & PAGE_MASK) == 0,
2095 ("pmap_invalidate_cache_range: sva not page-aligned"));
2096 KASSERT((eva & PAGE_MASK) == 0,
2097 ("pmap_invalidate_cache_range: eva not page-aligned"));
2100 if ((cpu_feature & CPUID_SS) != 0 && !force)
2101 ; /* If "Self Snoop" is supported and allowed, do nothing. */
2102 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
2103 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2105 * XXX: Some CPUs fault, hang, or trash the local APIC
2106 * registers if we use CLFLUSH on the local APIC
2107 * range. The local APIC is always uncached, so we
2108 * don't need to flush for that range anyway.
2110 if (pmap_kextract(sva) == lapic_paddr)
2114 * Otherwise, do per-cache line flush. Use the sfence
2115 * instruction to insure that previous stores are
2116 * included in the write-back. The processor
2117 * propagates flush to other processors in the cache
2121 for (; sva < eva; sva += cpu_clflush_line_size)
2124 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
2125 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2126 if (pmap_kextract(sva) == lapic_paddr)
2129 * Writes are ordered by CLFLUSH on Intel CPUs.
2131 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2133 for (; sva < eva; sva += cpu_clflush_line_size)
2135 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2140 * No targeted cache flush methods are supported by CPU,
2141 * or the supplied range is bigger than 2MB.
2142 * Globally invalidate cache.
2144 pmap_invalidate_cache();
2149 * Remove the specified set of pages from the data and instruction caches.
2151 * In contrast to pmap_invalidate_cache_range(), this function does not
2152 * rely on the CPU's self-snoop feature, because it is intended for use
2153 * when moving pages into a different cache domain.
2156 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
2158 vm_offset_t daddr, eva;
2162 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
2163 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
2164 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
2165 pmap_invalidate_cache();
2169 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2171 for (i = 0; i < count; i++) {
2172 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
2173 eva = daddr + PAGE_SIZE;
2174 for (; daddr < eva; daddr += cpu_clflush_line_size) {
2183 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2189 * Routine: pmap_extract
2191 * Extract the physical page address associated
2192 * with the given map/virtual_address pair.
2195 pmap_extract(pmap_t pmap, vm_offset_t va)
2199 pt_entry_t *pte, PG_V;
2203 PG_V = pmap_valid_bit(pmap);
2205 pdpe = pmap_pdpe(pmap, va);
2206 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2207 if ((*pdpe & PG_PS) != 0)
2208 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
2210 pde = pmap_pdpe_to_pde(pdpe, va);
2211 if ((*pde & PG_V) != 0) {
2212 if ((*pde & PG_PS) != 0) {
2213 pa = (*pde & PG_PS_FRAME) |
2216 pte = pmap_pde_to_pte(pde, va);
2217 pa = (*pte & PG_FRAME) |
2228 * Routine: pmap_extract_and_hold
2230 * Atomically extract and hold the physical page
2231 * with the given pmap and virtual address pair
2232 * if that mapping permits the given protection.
2235 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
2237 pd_entry_t pde, *pdep;
2238 pt_entry_t pte, PG_RW, PG_V;
2244 PG_RW = pmap_rw_bit(pmap);
2245 PG_V = pmap_valid_bit(pmap);
2248 pdep = pmap_pde(pmap, va);
2249 if (pdep != NULL && (pde = *pdep)) {
2251 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2252 if (vm_page_pa_tryrelock(pmap, (pde &
2253 PG_PS_FRAME) | (va & PDRMASK), &pa))
2255 m = PHYS_TO_VM_PAGE(pa);
2258 pte = *pmap_pde_to_pte(pdep, va);
2260 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2261 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2264 m = PHYS_TO_VM_PAGE(pa);
2276 pmap_kextract(vm_offset_t va)
2281 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2282 pa = DMAP_TO_PHYS(va);
2286 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2289 * Beware of a concurrent promotion that changes the
2290 * PDE at this point! For example, vtopte() must not
2291 * be used to access the PTE because it would use the
2292 * new PDE. It is, however, safe to use the old PDE
2293 * because the page table page is preserved by the
2296 pa = *pmap_pde_to_pte(&pde, va);
2297 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2303 /***************************************************
2304 * Low level mapping routines.....
2305 ***************************************************/
2308 * Add a wired page to the kva.
2309 * Note: not SMP coherent.
2312 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2317 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g);
2320 static __inline void
2321 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2327 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2328 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | cache_bits);
2332 * Remove a page from the kernel pagetables.
2333 * Note: not SMP coherent.
2336 pmap_kremove(vm_offset_t va)
2345 * Used to map a range of physical addresses into kernel
2346 * virtual address space.
2348 * The value passed in '*virt' is a suggested virtual address for
2349 * the mapping. Architectures which can support a direct-mapped
2350 * physical to virtual region can return the appropriate address
2351 * within that region, leaving '*virt' unchanged. Other
2352 * architectures should map the pages starting at '*virt' and
2353 * update '*virt' with the first usable address after the mapped
2357 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2359 return PHYS_TO_DMAP(start);
2364 * Add a list of wired pages to the kva
2365 * this routine is only used for temporary
2366 * kernel mappings that do not need to have
2367 * page modification or references recorded.
2368 * Note that old mappings are simply written
2369 * over. The page *must* be wired.
2370 * Note: SMP coherent. Uses a ranged shootdown IPI.
2373 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2375 pt_entry_t *endpte, oldpte, pa, *pte;
2381 endpte = pte + count;
2382 while (pte < endpte) {
2384 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2385 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2386 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2388 pte_store(pte, pa | pg_g | X86_PG_RW | X86_PG_V);
2392 if (__predict_false((oldpte & X86_PG_V) != 0))
2393 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2398 * This routine tears out page mappings from the
2399 * kernel -- it is meant only for temporary mappings.
2400 * Note: SMP coherent. Uses a ranged shootdown IPI.
2403 pmap_qremove(vm_offset_t sva, int count)
2408 while (count-- > 0) {
2409 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2413 pmap_invalidate_range(kernel_pmap, sva, va);
2416 /***************************************************
2417 * Page table page management routines.....
2418 ***************************************************/
2419 static __inline void
2420 pmap_free_zero_pages(struct spglist *free)
2425 for (count = 0; (m = SLIST_FIRST(free)) != NULL; count++) {
2426 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2427 /* Preserve the page's PG_ZERO setting. */
2428 vm_page_free_toq(m);
2430 atomic_subtract_int(&vm_cnt.v_wire_count, count);
2434 * Schedule the specified unused page table page to be freed. Specifically,
2435 * add the page to the specified list of pages that will be released to the
2436 * physical memory manager after the TLB has been updated.
2438 static __inline void
2439 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2440 boolean_t set_PG_ZERO)
2444 m->flags |= PG_ZERO;
2446 m->flags &= ~PG_ZERO;
2447 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2451 * Inserts the specified page table page into the specified pmap's collection
2452 * of idle page table pages. Each of a pmap's page table pages is responsible
2453 * for mapping a distinct range of virtual addresses. The pmap's collection is
2454 * ordered by this virtual address range.
2457 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2460 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2461 return (vm_radix_insert(&pmap->pm_root, mpte));
2465 * Removes the page table page mapping the specified virtual address from the
2466 * specified pmap's collection of idle page table pages, and returns it.
2467 * Otherwise, returns NULL if there is no page table page corresponding to the
2468 * specified virtual address.
2470 static __inline vm_page_t
2471 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
2474 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2475 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
2479 * Decrements a page table page's wire count, which is used to record the
2480 * number of valid page table entries within the page. If the wire count
2481 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2482 * page table page was unmapped and FALSE otherwise.
2484 static inline boolean_t
2485 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2489 if (m->wire_count == 0) {
2490 _pmap_unwire_ptp(pmap, va, m, free);
2497 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2500 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2502 * unmap the page table page
2504 if (m->pindex >= (NUPDE + NUPDPE)) {
2507 pml4 = pmap_pml4e(pmap, va);
2509 if (pmap->pm_pml4u != NULL && va <= VM_MAXUSER_ADDRESS) {
2510 pml4 = &pmap->pm_pml4u[pmap_pml4e_index(va)];
2513 } else if (m->pindex >= NUPDE) {
2516 pdp = pmap_pdpe(pmap, va);
2521 pd = pmap_pde(pmap, va);
2524 pmap_resident_count_dec(pmap, 1);
2525 if (m->pindex < NUPDE) {
2526 /* We just released a PT, unhold the matching PD */
2529 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2530 pmap_unwire_ptp(pmap, va, pdpg, free);
2532 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2533 /* We just released a PD, unhold the matching PDP */
2536 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2537 pmap_unwire_ptp(pmap, va, pdppg, free);
2541 * Put page on a list so that it is released after
2542 * *ALL* TLB shootdown is done
2544 pmap_add_delayed_free_list(m, free, TRUE);
2548 * After removing a page table entry, this routine is used to
2549 * conditionally free the page, and manage the hold/wire counts.
2552 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2553 struct spglist *free)
2557 if (va >= VM_MAXUSER_ADDRESS)
2559 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2560 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2561 return (pmap_unwire_ptp(pmap, va, mpte, free));
2565 pmap_pinit0(pmap_t pmap)
2569 PMAP_LOCK_INIT(pmap);
2570 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2571 pmap->pm_pml4u = NULL;
2572 pmap->pm_cr3 = KPML4phys;
2573 /* hack to keep pmap_pti_pcid_invalidate() alive */
2574 pmap->pm_ucr3 = PMAP_NO_CR3;
2575 pmap->pm_root.rt_root = 0;
2576 CPU_ZERO(&pmap->pm_active);
2577 TAILQ_INIT(&pmap->pm_pvchunk);
2578 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2579 pmap->pm_flags = pmap_flags;
2581 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN + 1;
2582 pmap->pm_pcids[i].pm_gen = 1;
2584 pmap_activate_boot(pmap);
2588 pmap_pinit_pml4(vm_page_t pml4pg)
2590 pml4_entry_t *pm_pml4;
2593 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2595 /* Wire in kernel global address entries. */
2596 for (i = 0; i < NKPML4E; i++) {
2597 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2600 for (i = 0; i < ndmpdpphys; i++) {
2601 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2605 /* install self-referential address mapping entry(s) */
2606 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2607 X86_PG_A | X86_PG_M;
2611 pmap_pinit_pml4_pti(vm_page_t pml4pg)
2613 pml4_entry_t *pm_pml4;
2616 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2617 for (i = 0; i < NPML4EPG; i++)
2618 pm_pml4[i] = pti_pml4[i];
2622 * Initialize a preallocated and zeroed pmap structure,
2623 * such as one in a vmspace structure.
2626 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2628 vm_page_t pml4pg, pml4pgu;
2629 vm_paddr_t pml4phys;
2633 * allocate the page directory page
2635 pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
2636 VM_ALLOC_WIRED | VM_ALLOC_ZERO | VM_ALLOC_WAITOK);
2638 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2639 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2641 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2642 pmap->pm_pcids[i].pm_gen = 0;
2644 pmap->pm_cr3 = PMAP_NO_CR3; /* initialize to an invalid value */
2645 pmap->pm_ucr3 = PMAP_NO_CR3;
2646 pmap->pm_pml4u = NULL;
2648 pmap->pm_type = pm_type;
2649 if ((pml4pg->flags & PG_ZERO) == 0)
2650 pagezero(pmap->pm_pml4);
2653 * Do not install the host kernel mappings in the nested page
2654 * tables. These mappings are meaningless in the guest physical
2656 * Install minimal kernel mappings in PTI case.
2658 if (pm_type == PT_X86) {
2659 pmap->pm_cr3 = pml4phys;
2660 pmap_pinit_pml4(pml4pg);
2662 pml4pgu = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2663 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2664 pmap->pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(
2665 VM_PAGE_TO_PHYS(pml4pgu));
2666 pmap_pinit_pml4_pti(pml4pgu);
2667 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pml4pgu);
2671 pmap->pm_root.rt_root = 0;
2672 CPU_ZERO(&pmap->pm_active);
2673 TAILQ_INIT(&pmap->pm_pvchunk);
2674 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2675 pmap->pm_flags = flags;
2676 pmap->pm_eptgen = 0;
2682 pmap_pinit(pmap_t pmap)
2685 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2689 * This routine is called if the desired page table page does not exist.
2691 * If page table page allocation fails, this routine may sleep before
2692 * returning NULL. It sleeps only if a lock pointer was given.
2694 * Note: If a page allocation fails at page table level two or three,
2695 * one or two pages may be held during the wait, only to be released
2696 * afterwards. This conservative approach is easily argued to avoid
2700 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2702 vm_page_t m, pdppg, pdpg;
2703 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2705 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2707 PG_A = pmap_accessed_bit(pmap);
2708 PG_M = pmap_modified_bit(pmap);
2709 PG_V = pmap_valid_bit(pmap);
2710 PG_RW = pmap_rw_bit(pmap);
2713 * Allocate a page table page.
2715 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2716 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2717 if (lockp != NULL) {
2718 RELEASE_PV_LIST_LOCK(lockp);
2720 PMAP_ASSERT_NOT_IN_DI();
2726 * Indicate the need to retry. While waiting, the page table
2727 * page may have been allocated.
2731 if ((m->flags & PG_ZERO) == 0)
2735 * Map the pagetable page into the process address space, if
2736 * it isn't already there.
2739 if (ptepindex >= (NUPDE + NUPDPE)) {
2740 pml4_entry_t *pml4, *pml4u;
2741 vm_pindex_t pml4index;
2743 /* Wire up a new PDPE page */
2744 pml4index = ptepindex - (NUPDE + NUPDPE);
2745 pml4 = &pmap->pm_pml4[pml4index];
2746 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2747 if (pmap->pm_pml4u != NULL && pml4index < NUPML4E) {
2749 * PTI: Make all user-space mappings in the
2750 * kernel-mode page table no-execute so that
2751 * we detect any programming errors that leave
2752 * the kernel-mode page table active on return
2755 if (pmap->pm_ucr3 != PMAP_NO_CR3)
2758 pml4u = &pmap->pm_pml4u[pml4index];
2759 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
2763 } else if (ptepindex >= NUPDE) {
2764 vm_pindex_t pml4index;
2765 vm_pindex_t pdpindex;
2769 /* Wire up a new PDE page */
2770 pdpindex = ptepindex - NUPDE;
2771 pml4index = pdpindex >> NPML4EPGSHIFT;
2773 pml4 = &pmap->pm_pml4[pml4index];
2774 if ((*pml4 & PG_V) == 0) {
2775 /* Have to allocate a new pdp, recurse */
2776 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2779 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2780 vm_page_free_zero(m);
2784 /* Add reference to pdp page */
2785 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2786 pdppg->wire_count++;
2788 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2790 /* Now find the pdp page */
2791 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2792 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2795 vm_pindex_t pml4index;
2796 vm_pindex_t pdpindex;
2801 /* Wire up a new PTE page */
2802 pdpindex = ptepindex >> NPDPEPGSHIFT;
2803 pml4index = pdpindex >> NPML4EPGSHIFT;
2805 /* First, find the pdp and check that its valid. */
2806 pml4 = &pmap->pm_pml4[pml4index];
2807 if ((*pml4 & PG_V) == 0) {
2808 /* Have to allocate a new pd, recurse */
2809 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2812 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2813 vm_page_free_zero(m);
2816 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2817 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2819 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2820 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2821 if ((*pdp & PG_V) == 0) {
2822 /* Have to allocate a new pd, recurse */
2823 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2826 atomic_subtract_int(&vm_cnt.v_wire_count,
2828 vm_page_free_zero(m);
2832 /* Add reference to the pd page */
2833 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2837 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2839 /* Now we know where the page directory page is */
2840 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2841 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2844 pmap_resident_count_inc(pmap, 1);
2850 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2852 vm_pindex_t pdpindex, ptepindex;
2853 pdp_entry_t *pdpe, PG_V;
2856 PG_V = pmap_valid_bit(pmap);
2859 pdpe = pmap_pdpe(pmap, va);
2860 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2861 /* Add a reference to the pd page. */
2862 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2865 /* Allocate a pd page. */
2866 ptepindex = pmap_pde_pindex(va);
2867 pdpindex = ptepindex >> NPDPEPGSHIFT;
2868 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2869 if (pdpg == NULL && lockp != NULL)
2876 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2878 vm_pindex_t ptepindex;
2879 pd_entry_t *pd, PG_V;
2882 PG_V = pmap_valid_bit(pmap);
2885 * Calculate pagetable page index
2887 ptepindex = pmap_pde_pindex(va);
2890 * Get the page directory entry
2892 pd = pmap_pde(pmap, va);
2895 * This supports switching from a 2MB page to a
2898 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2899 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2901 * Invalidation of the 2MB page mapping may have caused
2902 * the deallocation of the underlying PD page.
2909 * If the page table page is mapped, we just increment the
2910 * hold count, and activate it.
2912 if (pd != NULL && (*pd & PG_V) != 0) {
2913 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2917 * Here if the pte page isn't mapped, or if it has been
2920 m = _pmap_allocpte(pmap, ptepindex, lockp);
2921 if (m == NULL && lockp != NULL)
2928 /***************************************************
2929 * Pmap allocation/deallocation routines.
2930 ***************************************************/
2933 * Release any resources held by the given physical map.
2934 * Called when a pmap initialized by pmap_pinit is being released.
2935 * Should only be called if the map contains no valid mappings.
2938 pmap_release(pmap_t pmap)
2943 KASSERT(pmap->pm_stats.resident_count == 0,
2944 ("pmap_release: pmap resident count %ld != 0",
2945 pmap->pm_stats.resident_count));
2946 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2947 ("pmap_release: pmap has reserved page table page(s)"));
2948 KASSERT(CPU_EMPTY(&pmap->pm_active),
2949 ("releasing active pmap %p", pmap));
2951 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2953 for (i = 0; i < NKPML4E; i++) /* KVA */
2954 pmap->pm_pml4[KPML4BASE + i] = 0;
2955 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
2956 pmap->pm_pml4[DMPML4I + i] = 0;
2957 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
2960 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2961 vm_page_free_zero(m);
2963 if (pmap->pm_pml4u != NULL) {
2964 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4u));
2966 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2972 kvm_size(SYSCTL_HANDLER_ARGS)
2974 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2976 return sysctl_handle_long(oidp, &ksize, 0, req);
2978 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2979 0, 0, kvm_size, "LU", "Size of KVM");
2982 kvm_free(SYSCTL_HANDLER_ARGS)
2984 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2986 return sysctl_handle_long(oidp, &kfree, 0, req);
2988 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2989 0, 0, kvm_free, "LU", "Amount of KVM free");
2992 * grow the number of kernel page table entries, if needed
2995 pmap_growkernel(vm_offset_t addr)
2999 pd_entry_t *pde, newpdir;
3002 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
3005 * Return if "addr" is within the range of kernel page table pages
3006 * that were preallocated during pmap bootstrap. Moreover, leave
3007 * "kernel_vm_end" and the kernel page table as they were.
3009 * The correctness of this action is based on the following
3010 * argument: vm_map_insert() allocates contiguous ranges of the
3011 * kernel virtual address space. It calls this function if a range
3012 * ends after "kernel_vm_end". If the kernel is mapped between
3013 * "kernel_vm_end" and "addr", then the range cannot begin at
3014 * "kernel_vm_end". In fact, its beginning address cannot be less
3015 * than the kernel. Thus, there is no immediate need to allocate
3016 * any new kernel page table pages between "kernel_vm_end" and
3019 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
3022 addr = roundup2(addr, NBPDR);
3023 if (addr - 1 >= vm_map_max(kernel_map))
3024 addr = vm_map_max(kernel_map);
3025 while (kernel_vm_end < addr) {
3026 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
3027 if ((*pdpe & X86_PG_V) == 0) {
3028 /* We need a new PDP entry */
3029 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
3030 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
3031 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
3033 panic("pmap_growkernel: no memory to grow kernel");
3034 if ((nkpg->flags & PG_ZERO) == 0)
3035 pmap_zero_page(nkpg);
3036 paddr = VM_PAGE_TO_PHYS(nkpg);
3037 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
3038 X86_PG_A | X86_PG_M);
3039 continue; /* try again */
3041 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
3042 if ((*pde & X86_PG_V) != 0) {
3043 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3044 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
3045 kernel_vm_end = vm_map_max(kernel_map);
3051 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
3052 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
3055 panic("pmap_growkernel: no memory to grow kernel");
3056 if ((nkpg->flags & PG_ZERO) == 0)
3057 pmap_zero_page(nkpg);
3058 paddr = VM_PAGE_TO_PHYS(nkpg);
3059 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
3060 pde_store(pde, newpdir);
3062 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3063 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
3064 kernel_vm_end = vm_map_max(kernel_map);
3071 /***************************************************
3072 * page management routines.
3073 ***************************************************/
3075 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
3076 CTASSERT(_NPCM == 3);
3077 CTASSERT(_NPCPV == 168);
3079 static __inline struct pv_chunk *
3080 pv_to_chunk(pv_entry_t pv)
3083 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
3086 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
3088 #define PC_FREE0 0xfffffffffffffffful
3089 #define PC_FREE1 0xfffffffffffffffful
3090 #define PC_FREE2 0x000000fffffffffful
3092 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
3095 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
3097 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
3098 "Current number of pv entry chunks");
3099 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
3100 "Current number of pv entry chunks allocated");
3101 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
3102 "Current number of pv entry chunks frees");
3103 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
3104 "Number of times tried to get a chunk page but failed.");
3106 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
3107 static int pv_entry_spare;
3109 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
3110 "Current number of pv entry frees");
3111 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
3112 "Current number of pv entry allocs");
3113 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
3114 "Current number of pv entries");
3115 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
3116 "Current number of spare pv entries");
3120 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
3125 pmap_invalidate_all(pmap);
3126 if (pmap != locked_pmap)
3129 pmap_delayed_invl_finished();
3133 * We are in a serious low memory condition. Resort to
3134 * drastic measures to free some pages so we can allocate
3135 * another pv entry chunk.
3137 * Returns NULL if PV entries were reclaimed from the specified pmap.
3139 * We do not, however, unmap 2mpages because subsequent accesses will
3140 * allocate per-page pv entries until repromotion occurs, thereby
3141 * exacerbating the shortage of free pv entries.
3144 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
3146 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
3147 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
3148 struct md_page *pvh;
3150 pmap_t next_pmap, pmap;
3151 pt_entry_t *pte, tpte;
3152 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3156 struct spglist free;
3158 int bit, field, freed;
3160 static int active_reclaims = 0;
3162 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
3163 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
3166 PG_G = PG_A = PG_M = PG_RW = 0;
3168 bzero(&pc_marker_b, sizeof(pc_marker_b));
3169 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
3170 pc_marker = (struct pv_chunk *)&pc_marker_b;
3171 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
3174 * A delayed invalidation block should already be active if
3175 * pmap_advise() or pmap_remove() called this function by way
3176 * of pmap_demote_pde_locked().
3178 start_di = pmap_not_in_di();
3180 mtx_lock(&pv_chunks_mutex);
3182 TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
3183 TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
3184 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
3185 SLIST_EMPTY(&free)) {
3186 next_pmap = pc->pc_pmap;
3187 if (next_pmap == NULL) {
3189 * The next chunk is a marker. However, it is
3190 * not our marker, so active_reclaims must be
3191 * > 1. Consequently, the next_chunk code
3192 * will not rotate the pv_chunks list.
3196 mtx_unlock(&pv_chunks_mutex);
3199 * A pv_chunk can only be removed from the pc_lru list
3200 * when both pc_chunks_mutex is owned and the
3201 * corresponding pmap is locked.
3203 if (pmap != next_pmap) {
3204 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
3207 /* Avoid deadlock and lock recursion. */
3208 if (pmap > locked_pmap) {
3209 RELEASE_PV_LIST_LOCK(lockp);
3212 pmap_delayed_invl_started();
3213 mtx_lock(&pv_chunks_mutex);
3215 } else if (pmap != locked_pmap) {
3216 if (PMAP_TRYLOCK(pmap)) {
3218 pmap_delayed_invl_started();
3219 mtx_lock(&pv_chunks_mutex);
3222 pmap = NULL; /* pmap is not locked */
3223 mtx_lock(&pv_chunks_mutex);
3224 pc = TAILQ_NEXT(pc_marker, pc_lru);
3226 pc->pc_pmap != next_pmap)
3230 } else if (start_di)
3231 pmap_delayed_invl_started();
3232 PG_G = pmap_global_bit(pmap);
3233 PG_A = pmap_accessed_bit(pmap);
3234 PG_M = pmap_modified_bit(pmap);
3235 PG_RW = pmap_rw_bit(pmap);
3239 * Destroy every non-wired, 4 KB page mapping in the chunk.
3242 for (field = 0; field < _NPCM; field++) {
3243 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
3244 inuse != 0; inuse &= ~(1UL << bit)) {
3246 pv = &pc->pc_pventry[field * 64 + bit];
3248 pde = pmap_pde(pmap, va);
3249 if ((*pde & PG_PS) != 0)
3251 pte = pmap_pde_to_pte(pde, va);
3252 if ((*pte & PG_W) != 0)
3254 tpte = pte_load_clear(pte);
3255 if ((tpte & PG_G) != 0)
3256 pmap_invalidate_page(pmap, va);
3257 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3258 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3260 if ((tpte & PG_A) != 0)
3261 vm_page_aflag_set(m, PGA_REFERENCED);
3262 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3263 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3265 if (TAILQ_EMPTY(&m->md.pv_list) &&
3266 (m->flags & PG_FICTITIOUS) == 0) {
3267 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3268 if (TAILQ_EMPTY(&pvh->pv_list)) {
3269 vm_page_aflag_clear(m,
3273 pmap_delayed_invl_page(m);
3274 pc->pc_map[field] |= 1UL << bit;
3275 pmap_unuse_pt(pmap, va, *pde, &free);
3280 mtx_lock(&pv_chunks_mutex);
3283 /* Every freed mapping is for a 4 KB page. */
3284 pmap_resident_count_dec(pmap, freed);
3285 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
3286 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
3287 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
3288 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3289 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
3290 pc->pc_map[2] == PC_FREE2) {
3291 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3292 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3293 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3294 /* Entire chunk is free; return it. */
3295 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3296 dump_drop_page(m_pc->phys_addr);
3297 mtx_lock(&pv_chunks_mutex);
3298 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3301 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3302 mtx_lock(&pv_chunks_mutex);
3303 /* One freed pv entry in locked_pmap is sufficient. */
3304 if (pmap == locked_pmap)
3307 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3308 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
3309 if (active_reclaims == 1 && pmap != NULL) {
3311 * Rotate the pv chunks list so that we do not
3312 * scan the same pv chunks that could not be
3313 * freed (because they contained a wired
3314 * and/or superpage mapping) on every
3315 * invocation of reclaim_pv_chunk().
3317 while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
3318 MPASS(pc->pc_pmap != NULL);
3319 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3320 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3324 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3325 TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
3327 mtx_unlock(&pv_chunks_mutex);
3328 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
3329 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
3330 m_pc = SLIST_FIRST(&free);
3331 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3332 /* Recycle a freed page table page. */
3333 m_pc->wire_count = 1;
3335 pmap_free_zero_pages(&free);
3340 * free the pv_entry back to the free list
3343 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3345 struct pv_chunk *pc;
3346 int idx, field, bit;
3348 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3349 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3350 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3351 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3352 pc = pv_to_chunk(pv);
3353 idx = pv - &pc->pc_pventry[0];
3356 pc->pc_map[field] |= 1ul << bit;
3357 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3358 pc->pc_map[2] != PC_FREE2) {
3359 /* 98% of the time, pc is already at the head of the list. */
3360 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3361 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3362 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3366 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3371 free_pv_chunk(struct pv_chunk *pc)
3375 mtx_lock(&pv_chunks_mutex);
3376 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3377 mtx_unlock(&pv_chunks_mutex);
3378 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3379 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3380 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3381 /* entire chunk is free, return it */
3382 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3383 dump_drop_page(m->phys_addr);
3384 vm_page_unwire(m, PQ_NONE);
3389 * Returns a new PV entry, allocating a new PV chunk from the system when
3390 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3391 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3394 * The given PV list lock may be released.
3397 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3401 struct pv_chunk *pc;
3404 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3405 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3407 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3409 for (field = 0; field < _NPCM; field++) {
3410 if (pc->pc_map[field]) {
3411 bit = bsfq(pc->pc_map[field]);
3415 if (field < _NPCM) {
3416 pv = &pc->pc_pventry[field * 64 + bit];
3417 pc->pc_map[field] &= ~(1ul << bit);
3418 /* If this was the last item, move it to tail */
3419 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3420 pc->pc_map[2] == 0) {
3421 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3422 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3425 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3426 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3430 /* No free items, allocate another chunk */
3431 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3434 if (lockp == NULL) {
3435 PV_STAT(pc_chunk_tryfail++);
3438 m = reclaim_pv_chunk(pmap, lockp);
3442 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3443 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3444 dump_add_page(m->phys_addr);
3445 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3447 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3448 pc->pc_map[1] = PC_FREE1;
3449 pc->pc_map[2] = PC_FREE2;
3450 mtx_lock(&pv_chunks_mutex);
3451 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3452 mtx_unlock(&pv_chunks_mutex);
3453 pv = &pc->pc_pventry[0];
3454 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3455 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3456 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3461 * Returns the number of one bits within the given PV chunk map.
3463 * The erratas for Intel processors state that "POPCNT Instruction May
3464 * Take Longer to Execute Than Expected". It is believed that the
3465 * issue is the spurious dependency on the destination register.
3466 * Provide a hint to the register rename logic that the destination
3467 * value is overwritten, by clearing it, as suggested in the
3468 * optimization manual. It should be cheap for unaffected processors
3471 * Reference numbers for erratas are
3472 * 4th Gen Core: HSD146
3473 * 5th Gen Core: BDM85
3474 * 6th Gen Core: SKL029
3477 popcnt_pc_map_pq(uint64_t *map)
3481 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3482 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3483 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3484 : "=&r" (result), "=&r" (tmp)
3485 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3490 * Ensure that the number of spare PV entries in the specified pmap meets or
3491 * exceeds the given count, "needed".
3493 * The given PV list lock may be released.
3496 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3498 struct pch new_tail;
3499 struct pv_chunk *pc;
3504 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3505 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3508 * Newly allocated PV chunks must be stored in a private list until
3509 * the required number of PV chunks have been allocated. Otherwise,
3510 * reclaim_pv_chunk() could recycle one of these chunks. In
3511 * contrast, these chunks must be added to the pmap upon allocation.
3513 TAILQ_INIT(&new_tail);
3516 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3518 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3519 bit_count((bitstr_t *)pc->pc_map, 0,
3520 sizeof(pc->pc_map) * NBBY, &free);
3523 free = popcnt_pc_map_pq(pc->pc_map);
3527 if (avail >= needed)
3530 for (reclaimed = false; avail < needed; avail += _NPCPV) {
3531 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3534 m = reclaim_pv_chunk(pmap, lockp);
3539 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3540 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3541 dump_add_page(m->phys_addr);
3542 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3544 pc->pc_map[0] = PC_FREE0;
3545 pc->pc_map[1] = PC_FREE1;
3546 pc->pc_map[2] = PC_FREE2;
3547 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3548 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3549 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3552 * The reclaim might have freed a chunk from the current pmap.
3553 * If that chunk contained available entries, we need to
3554 * re-count the number of available entries.
3559 if (!TAILQ_EMPTY(&new_tail)) {
3560 mtx_lock(&pv_chunks_mutex);
3561 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3562 mtx_unlock(&pv_chunks_mutex);
3567 * First find and then remove the pv entry for the specified pmap and virtual
3568 * address from the specified pv list. Returns the pv entry if found and NULL
3569 * otherwise. This operation can be performed on pv lists for either 4KB or
3570 * 2MB page mappings.
3572 static __inline pv_entry_t
3573 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3577 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3578 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3579 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3588 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3589 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3590 * entries for each of the 4KB page mappings.
3593 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3594 struct rwlock **lockp)
3596 struct md_page *pvh;
3597 struct pv_chunk *pc;
3599 vm_offset_t va_last;
3603 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3604 KASSERT((pa & PDRMASK) == 0,
3605 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3606 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3609 * Transfer the 2mpage's pv entry for this mapping to the first
3610 * page's pv list. Once this transfer begins, the pv list lock
3611 * must not be released until the last pv entry is reinstantiated.
3613 pvh = pa_to_pvh(pa);
3614 va = trunc_2mpage(va);
3615 pv = pmap_pvh_remove(pvh, pmap, va);
3616 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3617 m = PHYS_TO_VM_PAGE(pa);
3618 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3620 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3621 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3622 va_last = va + NBPDR - PAGE_SIZE;
3624 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3625 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3626 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3627 for (field = 0; field < _NPCM; field++) {
3628 while (pc->pc_map[field]) {
3629 bit = bsfq(pc->pc_map[field]);
3630 pc->pc_map[field] &= ~(1ul << bit);
3631 pv = &pc->pc_pventry[field * 64 + bit];
3635 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3636 ("pmap_pv_demote_pde: page %p is not managed", m));
3637 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3643 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3644 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3647 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3648 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3649 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3651 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3652 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3655 #if VM_NRESERVLEVEL > 0
3657 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3658 * replace the many pv entries for the 4KB page mappings by a single pv entry
3659 * for the 2MB page mapping.
3662 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3663 struct rwlock **lockp)
3665 struct md_page *pvh;
3667 vm_offset_t va_last;
3670 KASSERT((pa & PDRMASK) == 0,
3671 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3672 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3675 * Transfer the first page's pv entry for this mapping to the 2mpage's
3676 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3677 * a transfer avoids the possibility that get_pv_entry() calls
3678 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3679 * mappings that is being promoted.
3681 m = PHYS_TO_VM_PAGE(pa);
3682 va = trunc_2mpage(va);
3683 pv = pmap_pvh_remove(&m->md, pmap, va);
3684 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3685 pvh = pa_to_pvh(pa);
3686 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3688 /* Free the remaining NPTEPG - 1 pv entries. */
3689 va_last = va + NBPDR - PAGE_SIZE;
3693 pmap_pvh_free(&m->md, pmap, va);
3694 } while (va < va_last);
3696 #endif /* VM_NRESERVLEVEL > 0 */
3699 * First find and then destroy the pv entry for the specified pmap and virtual
3700 * address. This operation can be performed on pv lists for either 4KB or 2MB
3704 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3708 pv = pmap_pvh_remove(pvh, pmap, va);
3709 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3710 free_pv_entry(pmap, pv);
3714 * Conditionally create the PV entry for a 4KB page mapping if the required
3715 * memory can be allocated without resorting to reclamation.
3718 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3719 struct rwlock **lockp)
3723 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3724 /* Pass NULL instead of the lock pointer to disable reclamation. */
3725 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3727 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3728 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3736 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3737 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3738 * false if the PV entry cannot be allocated without resorting to reclamation.
3741 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
3742 struct rwlock **lockp)
3744 struct md_page *pvh;
3748 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3749 /* Pass NULL instead of the lock pointer to disable reclamation. */
3750 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3751 NULL : lockp)) == NULL)
3754 pa = pde & PG_PS_FRAME;
3755 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3756 pvh = pa_to_pvh(pa);
3757 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3763 * Fills a page table page with mappings to consecutive physical pages.
3766 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3770 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3772 newpte += PAGE_SIZE;
3777 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3778 * mapping is invalidated.
3781 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3783 struct rwlock *lock;
3787 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3794 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3795 struct rwlock **lockp)
3797 pd_entry_t newpde, oldpde;
3798 pt_entry_t *firstpte, newpte;
3799 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3802 struct spglist free;
3806 PG_G = pmap_global_bit(pmap);
3807 PG_A = pmap_accessed_bit(pmap);
3808 PG_M = pmap_modified_bit(pmap);
3809 PG_RW = pmap_rw_bit(pmap);
3810 PG_V = pmap_valid_bit(pmap);
3811 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3813 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3815 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3816 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3817 if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
3819 KASSERT((oldpde & PG_W) == 0,
3820 ("pmap_demote_pde: page table page for a wired mapping"
3824 * Invalidate the 2MB page mapping and return "failure" if the
3825 * mapping was never accessed or the allocation of the new
3826 * page table page fails. If the 2MB page mapping belongs to
3827 * the direct map region of the kernel's address space, then
3828 * the page allocation request specifies the highest possible
3829 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3830 * normal. Page table pages are preallocated for every other
3831 * part of the kernel address space, so the direct map region
3832 * is the only part of the kernel address space that must be
3835 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3836 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3837 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3838 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3840 sva = trunc_2mpage(va);
3841 pmap_remove_pde(pmap, pde, sva, &free, lockp);
3842 if ((oldpde & PG_G) == 0)
3843 pmap_invalidate_pde_page(pmap, sva, oldpde);
3844 pmap_free_zero_pages(&free);
3845 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3846 " in pmap %p", va, pmap);
3849 if (va < VM_MAXUSER_ADDRESS)
3850 pmap_resident_count_inc(pmap, 1);
3852 mptepa = VM_PAGE_TO_PHYS(mpte);
3853 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3854 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3855 KASSERT((oldpde & PG_A) != 0,
3856 ("pmap_demote_pde: oldpde is missing PG_A"));
3857 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3858 ("pmap_demote_pde: oldpde is missing PG_M"));
3859 newpte = oldpde & ~PG_PS;
3860 newpte = pmap_swap_pat(pmap, newpte);
3863 * If the page table page is new, initialize it.
3865 if (mpte->wire_count == 1) {
3866 mpte->wire_count = NPTEPG;
3867 pmap_fill_ptp(firstpte, newpte);
3869 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3870 ("pmap_demote_pde: firstpte and newpte map different physical"
3874 * If the mapping has changed attributes, update the page table
3877 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3878 pmap_fill_ptp(firstpte, newpte);
3881 * The spare PV entries must be reserved prior to demoting the
3882 * mapping, that is, prior to changing the PDE. Otherwise, the state
3883 * of the PDE and the PV lists will be inconsistent, which can result
3884 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3885 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3886 * PV entry for the 2MB page mapping that is being demoted.
3888 if ((oldpde & PG_MANAGED) != 0)
3889 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3892 * Demote the mapping. This pmap is locked. The old PDE has
3893 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3894 * set. Thus, there is no danger of a race with another
3895 * processor changing the setting of PG_A and/or PG_M between
3896 * the read above and the store below.
3898 if (workaround_erratum383)
3899 pmap_update_pde(pmap, va, pde, newpde);
3901 pde_store(pde, newpde);
3904 * Invalidate a stale recursive mapping of the page table page.
3906 if (va >= VM_MAXUSER_ADDRESS)
3907 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3910 * Demote the PV entry.
3912 if ((oldpde & PG_MANAGED) != 0)
3913 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3915 atomic_add_long(&pmap_pde_demotions, 1);
3916 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3917 " in pmap %p", va, pmap);
3922 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3925 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3931 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3932 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3933 mpte = pmap_remove_pt_page(pmap, va);
3935 panic("pmap_remove_kernel_pde: Missing pt page.");
3937 mptepa = VM_PAGE_TO_PHYS(mpte);
3938 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3941 * Initialize the page table page.
3943 pagezero((void *)PHYS_TO_DMAP(mptepa));
3946 * Demote the mapping.
3948 if (workaround_erratum383)
3949 pmap_update_pde(pmap, va, pde, newpde);
3951 pde_store(pde, newpde);
3954 * Invalidate a stale recursive mapping of the page table page.
3956 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3960 * pmap_remove_pde: do the things to unmap a superpage in a process
3963 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
3964 struct spglist *free, struct rwlock **lockp)
3966 struct md_page *pvh;
3968 vm_offset_t eva, va;
3970 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3972 PG_G = pmap_global_bit(pmap);
3973 PG_A = pmap_accessed_bit(pmap);
3974 PG_M = pmap_modified_bit(pmap);
3975 PG_RW = pmap_rw_bit(pmap);
3977 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3978 KASSERT((sva & PDRMASK) == 0,
3979 ("pmap_remove_pde: sva is not 2mpage aligned"));
3980 oldpde = pte_load_clear(pdq);
3982 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
3983 if ((oldpde & PG_G) != 0)
3984 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
3985 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
3986 if (oldpde & PG_MANAGED) {
3987 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
3988 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
3989 pmap_pvh_free(pvh, pmap, sva);
3991 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3992 va < eva; va += PAGE_SIZE, m++) {
3993 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3996 vm_page_aflag_set(m, PGA_REFERENCED);
3997 if (TAILQ_EMPTY(&m->md.pv_list) &&
3998 TAILQ_EMPTY(&pvh->pv_list))
3999 vm_page_aflag_clear(m, PGA_WRITEABLE);
4000 pmap_delayed_invl_page(m);
4003 if (pmap == kernel_pmap) {
4004 pmap_remove_kernel_pde(pmap, pdq, sva);
4006 mpte = pmap_remove_pt_page(pmap, sva);
4008 pmap_resident_count_dec(pmap, 1);
4009 KASSERT(mpte->wire_count == NPTEPG,
4010 ("pmap_remove_pde: pte page wire count error"));
4011 mpte->wire_count = 0;
4012 pmap_add_delayed_free_list(mpte, free, FALSE);
4015 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
4019 * pmap_remove_pte: do the things to unmap a page in a process
4022 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
4023 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
4025 struct md_page *pvh;
4026 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
4029 PG_A = pmap_accessed_bit(pmap);
4030 PG_M = pmap_modified_bit(pmap);
4031 PG_RW = pmap_rw_bit(pmap);
4033 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4034 oldpte = pte_load_clear(ptq);
4036 pmap->pm_stats.wired_count -= 1;
4037 pmap_resident_count_dec(pmap, 1);
4038 if (oldpte & PG_MANAGED) {
4039 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
4040 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4043 vm_page_aflag_set(m, PGA_REFERENCED);
4044 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
4045 pmap_pvh_free(&m->md, pmap, va);
4046 if (TAILQ_EMPTY(&m->md.pv_list) &&
4047 (m->flags & PG_FICTITIOUS) == 0) {
4048 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4049 if (TAILQ_EMPTY(&pvh->pv_list))
4050 vm_page_aflag_clear(m, PGA_WRITEABLE);
4052 pmap_delayed_invl_page(m);
4054 return (pmap_unuse_pt(pmap, va, ptepde, free));
4058 * Remove a single page from a process address space
4061 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
4062 struct spglist *free)
4064 struct rwlock *lock;
4065 pt_entry_t *pte, PG_V;
4067 PG_V = pmap_valid_bit(pmap);
4068 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4069 if ((*pde & PG_V) == 0)
4071 pte = pmap_pde_to_pte(pde, va);
4072 if ((*pte & PG_V) == 0)
4075 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
4078 pmap_invalidate_page(pmap, va);
4082 * Removes the specified range of addresses from the page table page.
4085 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
4086 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
4088 pt_entry_t PG_G, *pte;
4092 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4093 PG_G = pmap_global_bit(pmap);
4096 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
4100 pmap_invalidate_range(pmap, va, sva);
4105 if ((*pte & PG_G) == 0)
4109 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
4115 pmap_invalidate_range(pmap, va, sva);
4120 * Remove the given range of addresses from the specified map.
4122 * It is assumed that the start and end are properly
4123 * rounded to the page size.
4126 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4128 struct rwlock *lock;
4129 vm_offset_t va_next;
4130 pml4_entry_t *pml4e;
4132 pd_entry_t ptpaddr, *pde;
4133 pt_entry_t PG_G, PG_V;
4134 struct spglist free;
4137 PG_G = pmap_global_bit(pmap);
4138 PG_V = pmap_valid_bit(pmap);
4141 * Perform an unsynchronized read. This is, however, safe.
4143 if (pmap->pm_stats.resident_count == 0)
4149 pmap_delayed_invl_started();
4153 * special handling of removing one page. a very
4154 * common operation and easy to short circuit some
4157 if (sva + PAGE_SIZE == eva) {
4158 pde = pmap_pde(pmap, sva);
4159 if (pde && (*pde & PG_PS) == 0) {
4160 pmap_remove_page(pmap, sva, pde, &free);
4166 for (; sva < eva; sva = va_next) {
4168 if (pmap->pm_stats.resident_count == 0)
4171 pml4e = pmap_pml4e(pmap, sva);
4172 if ((*pml4e & PG_V) == 0) {
4173 va_next = (sva + NBPML4) & ~PML4MASK;
4179 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4180 if ((*pdpe & PG_V) == 0) {
4181 va_next = (sva + NBPDP) & ~PDPMASK;
4188 * Calculate index for next page table.
4190 va_next = (sva + NBPDR) & ~PDRMASK;
4194 pde = pmap_pdpe_to_pde(pdpe, sva);
4198 * Weed out invalid mappings.
4204 * Check for large page.
4206 if ((ptpaddr & PG_PS) != 0) {
4208 * Are we removing the entire large page? If not,
4209 * demote the mapping and fall through.
4211 if (sva + NBPDR == va_next && eva >= va_next) {
4213 * The TLB entry for a PG_G mapping is
4214 * invalidated by pmap_remove_pde().
4216 if ((ptpaddr & PG_G) == 0)
4218 pmap_remove_pde(pmap, pde, sva, &free, &lock);
4220 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
4222 /* The large page mapping was destroyed. */
4229 * Limit our scan to either the end of the va represented
4230 * by the current page table page, or to the end of the
4231 * range being removed.
4236 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
4243 pmap_invalidate_all(pmap);
4245 pmap_delayed_invl_finished();
4246 pmap_free_zero_pages(&free);
4250 * Routine: pmap_remove_all
4252 * Removes this physical page from
4253 * all physical maps in which it resides.
4254 * Reflects back modify bits to the pager.
4257 * Original versions of this routine were very
4258 * inefficient because they iteratively called
4259 * pmap_remove (slow...)
4263 pmap_remove_all(vm_page_t m)
4265 struct md_page *pvh;
4268 struct rwlock *lock;
4269 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
4272 struct spglist free;
4273 int pvh_gen, md_gen;
4275 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4276 ("pmap_remove_all: page %p is not managed", m));
4278 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4279 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
4280 pa_to_pvh(VM_PAGE_TO_PHYS(m));
4283 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
4285 if (!PMAP_TRYLOCK(pmap)) {
4286 pvh_gen = pvh->pv_gen;
4290 if (pvh_gen != pvh->pv_gen) {
4297 pde = pmap_pde(pmap, va);
4298 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
4301 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4303 if (!PMAP_TRYLOCK(pmap)) {
4304 pvh_gen = pvh->pv_gen;
4305 md_gen = m->md.pv_gen;
4309 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
4315 PG_A = pmap_accessed_bit(pmap);
4316 PG_M = pmap_modified_bit(pmap);
4317 PG_RW = pmap_rw_bit(pmap);
4318 pmap_resident_count_dec(pmap, 1);
4319 pde = pmap_pde(pmap, pv->pv_va);
4320 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
4321 " a 2mpage in page %p's pv list", m));
4322 pte = pmap_pde_to_pte(pde, pv->pv_va);
4323 tpte = pte_load_clear(pte);
4325 pmap->pm_stats.wired_count--;
4327 vm_page_aflag_set(m, PGA_REFERENCED);
4330 * Update the vm_page_t clean and reference bits.
4332 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4334 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
4335 pmap_invalidate_page(pmap, pv->pv_va);
4336 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4338 free_pv_entry(pmap, pv);
4341 vm_page_aflag_clear(m, PGA_WRITEABLE);
4343 pmap_delayed_invl_wait(m);
4344 pmap_free_zero_pages(&free);
4348 * pmap_protect_pde: do the things to protect a 2mpage in a process
4351 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
4353 pd_entry_t newpde, oldpde;
4354 vm_offset_t eva, va;
4356 boolean_t anychanged;
4357 pt_entry_t PG_G, PG_M, PG_RW;
4359 PG_G = pmap_global_bit(pmap);
4360 PG_M = pmap_modified_bit(pmap);
4361 PG_RW = pmap_rw_bit(pmap);
4363 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4364 KASSERT((sva & PDRMASK) == 0,
4365 ("pmap_protect_pde: sva is not 2mpage aligned"));
4368 oldpde = newpde = *pde;
4369 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4370 (PG_MANAGED | PG_M | PG_RW)) {
4372 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4373 va < eva; va += PAGE_SIZE, m++)
4376 if ((prot & VM_PROT_WRITE) == 0)
4377 newpde &= ~(PG_RW | PG_M);
4378 if ((prot & VM_PROT_EXECUTE) == 0)
4380 if (newpde != oldpde) {
4382 * As an optimization to future operations on this PDE, clear
4383 * PG_PROMOTED. The impending invalidation will remove any
4384 * lingering 4KB page mappings from the TLB.
4386 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
4388 if ((oldpde & PG_G) != 0)
4389 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4393 return (anychanged);
4397 * Set the physical protection on the
4398 * specified range of this map as requested.
4401 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4403 vm_offset_t va_next;
4404 pml4_entry_t *pml4e;
4406 pd_entry_t ptpaddr, *pde;
4407 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4408 boolean_t anychanged;
4410 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4411 if (prot == VM_PROT_NONE) {
4412 pmap_remove(pmap, sva, eva);
4416 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4417 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4420 PG_G = pmap_global_bit(pmap);
4421 PG_M = pmap_modified_bit(pmap);
4422 PG_V = pmap_valid_bit(pmap);
4423 PG_RW = pmap_rw_bit(pmap);
4427 * Although this function delays and batches the invalidation
4428 * of stale TLB entries, it does not need to call
4429 * pmap_delayed_invl_started() and
4430 * pmap_delayed_invl_finished(), because it does not
4431 * ordinarily destroy mappings. Stale TLB entries from
4432 * protection-only changes need only be invalidated before the
4433 * pmap lock is released, because protection-only changes do
4434 * not destroy PV entries. Even operations that iterate over
4435 * a physical page's PV list of mappings, like
4436 * pmap_remove_write(), acquire the pmap lock for each
4437 * mapping. Consequently, for protection-only changes, the
4438 * pmap lock suffices to synchronize both page table and TLB
4441 * This function only destroys a mapping if pmap_demote_pde()
4442 * fails. In that case, stale TLB entries are immediately
4447 for (; sva < eva; sva = va_next) {
4449 pml4e = pmap_pml4e(pmap, sva);
4450 if ((*pml4e & PG_V) == 0) {
4451 va_next = (sva + NBPML4) & ~PML4MASK;
4457 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4458 if ((*pdpe & PG_V) == 0) {
4459 va_next = (sva + NBPDP) & ~PDPMASK;
4465 va_next = (sva + NBPDR) & ~PDRMASK;
4469 pde = pmap_pdpe_to_pde(pdpe, sva);
4473 * Weed out invalid mappings.
4479 * Check for large page.
4481 if ((ptpaddr & PG_PS) != 0) {
4483 * Are we protecting the entire large page? If not,
4484 * demote the mapping and fall through.
4486 if (sva + NBPDR == va_next && eva >= va_next) {
4488 * The TLB entry for a PG_G mapping is
4489 * invalidated by pmap_protect_pde().
4491 if (pmap_protect_pde(pmap, pde, sva, prot))
4494 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4496 * The large page mapping was destroyed.
4505 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4507 pt_entry_t obits, pbits;
4511 obits = pbits = *pte;
4512 if ((pbits & PG_V) == 0)
4515 if ((prot & VM_PROT_WRITE) == 0) {
4516 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4517 (PG_MANAGED | PG_M | PG_RW)) {
4518 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4521 pbits &= ~(PG_RW | PG_M);
4523 if ((prot & VM_PROT_EXECUTE) == 0)
4526 if (pbits != obits) {
4527 if (!atomic_cmpset_long(pte, obits, pbits))
4530 pmap_invalidate_page(pmap, sva);
4537 pmap_invalidate_all(pmap);
4541 #if VM_NRESERVLEVEL > 0
4543 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4544 * single page table page (PTP) to a single 2MB page mapping. For promotion
4545 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4546 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4547 * identical characteristics.
4550 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4551 struct rwlock **lockp)
4554 pt_entry_t *firstpte, oldpte, pa, *pte;
4555 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4559 PG_A = pmap_accessed_bit(pmap);
4560 PG_G = pmap_global_bit(pmap);
4561 PG_M = pmap_modified_bit(pmap);
4562 PG_V = pmap_valid_bit(pmap);
4563 PG_RW = pmap_rw_bit(pmap);
4564 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4566 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4569 * Examine the first PTE in the specified PTP. Abort if this PTE is
4570 * either invalid, unused, or does not map the first 4KB physical page
4571 * within a 2MB page.
4573 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4576 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4577 atomic_add_long(&pmap_pde_p_failures, 1);
4578 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4579 " in pmap %p", va, pmap);
4582 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4584 * When PG_M is already clear, PG_RW can be cleared without
4585 * a TLB invalidation.
4587 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4593 * Examine each of the other PTEs in the specified PTP. Abort if this
4594 * PTE maps an unexpected 4KB physical page or does not have identical
4595 * characteristics to the first PTE.
4597 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4598 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4601 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4602 atomic_add_long(&pmap_pde_p_failures, 1);
4603 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4604 " in pmap %p", va, pmap);
4607 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4609 * When PG_M is already clear, PG_RW can be cleared
4610 * without a TLB invalidation.
4612 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4615 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4616 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4617 (va & ~PDRMASK), pmap);
4619 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4620 atomic_add_long(&pmap_pde_p_failures, 1);
4621 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4622 " in pmap %p", va, pmap);
4629 * Save the page table page in its current state until the PDE
4630 * mapping the superpage is demoted by pmap_demote_pde() or
4631 * destroyed by pmap_remove_pde().
4633 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4634 KASSERT(mpte >= vm_page_array &&
4635 mpte < &vm_page_array[vm_page_array_size],
4636 ("pmap_promote_pde: page table page is out of range"));
4637 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4638 ("pmap_promote_pde: page table page's pindex is wrong"));
4639 if (pmap_insert_pt_page(pmap, mpte)) {
4640 atomic_add_long(&pmap_pde_p_failures, 1);
4642 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4648 * Promote the pv entries.
4650 if ((newpde & PG_MANAGED) != 0)
4651 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4654 * Propagate the PAT index to its proper position.
4656 newpde = pmap_swap_pat(pmap, newpde);
4659 * Map the superpage.
4661 if (workaround_erratum383)
4662 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4664 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
4666 atomic_add_long(&pmap_pde_promotions, 1);
4667 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4668 " in pmap %p", va, pmap);
4670 #endif /* VM_NRESERVLEVEL > 0 */
4673 * Insert the given physical page (p) at
4674 * the specified virtual address (v) in the
4675 * target physical map with the protection requested.
4677 * If specified, the page will be wired down, meaning
4678 * that the related pte can not be reclaimed.
4680 * NB: This is the only routine which MAY NOT lazy-evaluate
4681 * or lose information. That is, this routine must actually
4682 * insert this page into the given map NOW.
4684 * When destroying both a page table and PV entry, this function
4685 * performs the TLB invalidation before releasing the PV list
4686 * lock, so we do not need pmap_delayed_invl_page() calls here.
4689 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4690 u_int flags, int8_t psind)
4692 struct rwlock *lock;
4694 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4695 pt_entry_t newpte, origpte;
4702 PG_A = pmap_accessed_bit(pmap);
4703 PG_G = pmap_global_bit(pmap);
4704 PG_M = pmap_modified_bit(pmap);
4705 PG_V = pmap_valid_bit(pmap);
4706 PG_RW = pmap_rw_bit(pmap);
4708 va = trunc_page(va);
4709 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4710 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4711 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4713 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4714 va >= kmi.clean_eva,
4715 ("pmap_enter: managed mapping within the clean submap"));
4716 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4717 VM_OBJECT_ASSERT_LOCKED(m->object);
4718 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
4719 ("pmap_enter: flags %u has reserved bits set", flags));
4720 pa = VM_PAGE_TO_PHYS(m);
4721 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4722 if ((flags & VM_PROT_WRITE) != 0)
4724 if ((prot & VM_PROT_WRITE) != 0)
4726 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4727 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4728 if ((prot & VM_PROT_EXECUTE) == 0)
4730 if ((flags & PMAP_ENTER_WIRED) != 0)
4732 if (va < VM_MAXUSER_ADDRESS)
4734 if (pmap == kernel_pmap)
4736 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
4739 * Set modified bit gratuitously for writeable mappings if
4740 * the page is unmanaged. We do not want to take a fault
4741 * to do the dirty bit accounting for these mappings.
4743 if ((m->oflags & VPO_UNMANAGED) != 0) {
4744 if ((newpte & PG_RW) != 0)
4747 newpte |= PG_MANAGED;
4752 /* Assert the required virtual and physical alignment. */
4753 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
4754 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4755 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
4761 * In the case that a page table page is not
4762 * resident, we are creating it here.
4765 pde = pmap_pde(pmap, va);
4766 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4767 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4768 pte = pmap_pde_to_pte(pde, va);
4769 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4770 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4773 } else if (va < VM_MAXUSER_ADDRESS) {
4775 * Here if the pte page isn't mapped, or if it has been
4778 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4779 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4780 nosleep ? NULL : &lock);
4781 if (mpte == NULL && nosleep) {
4782 rv = KERN_RESOURCE_SHORTAGE;
4787 panic("pmap_enter: invalid page directory va=%#lx", va);
4793 * Is the specified virtual address already mapped?
4795 if ((origpte & PG_V) != 0) {
4797 * Wiring change, just update stats. We don't worry about
4798 * wiring PT pages as they remain resident as long as there
4799 * are valid mappings in them. Hence, if a user page is wired,
4800 * the PT page will be also.
4802 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4803 pmap->pm_stats.wired_count++;
4804 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4805 pmap->pm_stats.wired_count--;
4808 * Remove the extra PT page reference.
4812 KASSERT(mpte->wire_count > 0,
4813 ("pmap_enter: missing reference to page table page,"
4818 * Has the physical page changed?
4820 opa = origpte & PG_FRAME;
4823 * No, might be a protection or wiring change.
4825 if ((origpte & PG_MANAGED) != 0 &&
4826 (newpte & PG_RW) != 0)
4827 vm_page_aflag_set(m, PGA_WRITEABLE);
4828 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4834 * The physical page has changed. Temporarily invalidate
4835 * the mapping. This ensures that all threads sharing the
4836 * pmap keep a consistent view of the mapping, which is
4837 * necessary for the correct handling of COW faults. It
4838 * also permits reuse of the old mapping's PV entry,
4839 * avoiding an allocation.
4841 * For consistency, handle unmanaged mappings the same way.
4843 origpte = pte_load_clear(pte);
4844 KASSERT((origpte & PG_FRAME) == opa,
4845 ("pmap_enter: unexpected pa update for %#lx", va));
4846 if ((origpte & PG_MANAGED) != 0) {
4847 om = PHYS_TO_VM_PAGE(opa);
4850 * The pmap lock is sufficient to synchronize with
4851 * concurrent calls to pmap_page_test_mappings() and
4852 * pmap_ts_referenced().
4854 if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4856 if ((origpte & PG_A) != 0)
4857 vm_page_aflag_set(om, PGA_REFERENCED);
4858 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4859 pv = pmap_pvh_remove(&om->md, pmap, va);
4860 if ((newpte & PG_MANAGED) == 0)
4861 free_pv_entry(pmap, pv);
4862 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4863 TAILQ_EMPTY(&om->md.pv_list) &&
4864 ((om->flags & PG_FICTITIOUS) != 0 ||
4865 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4866 vm_page_aflag_clear(om, PGA_WRITEABLE);
4868 if ((origpte & PG_A) != 0)
4869 pmap_invalidate_page(pmap, va);
4873 * Increment the counters.
4875 if ((newpte & PG_W) != 0)
4876 pmap->pm_stats.wired_count++;
4877 pmap_resident_count_inc(pmap, 1);
4881 * Enter on the PV list if part of our managed memory.
4883 if ((newpte & PG_MANAGED) != 0) {
4885 pv = get_pv_entry(pmap, &lock);
4888 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4889 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4891 if ((newpte & PG_RW) != 0)
4892 vm_page_aflag_set(m, PGA_WRITEABLE);
4898 if ((origpte & PG_V) != 0) {
4900 origpte = pte_load_store(pte, newpte);
4901 KASSERT((origpte & PG_FRAME) == pa,
4902 ("pmap_enter: unexpected pa update for %#lx", va));
4903 if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
4905 if ((origpte & PG_MANAGED) != 0)
4909 * Although the PTE may still have PG_RW set, TLB
4910 * invalidation may nonetheless be required because
4911 * the PTE no longer has PG_M set.
4913 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4915 * This PTE change does not require TLB invalidation.
4919 if ((origpte & PG_A) != 0)
4920 pmap_invalidate_page(pmap, va);
4922 pte_store(pte, newpte);
4926 #if VM_NRESERVLEVEL > 0
4928 * If both the page table page and the reservation are fully
4929 * populated, then attempt promotion.
4931 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4932 pmap_ps_enabled(pmap) &&
4933 (m->flags & PG_FICTITIOUS) == 0 &&
4934 vm_reserv_level_iffullpop(m) == 0)
4935 pmap_promote_pde(pmap, pde, va, &lock);
4947 * Tries to create a read- and/or execute-only 2MB page mapping. Returns true
4948 * if successful. Returns false if (1) a page table page cannot be allocated
4949 * without sleeping, (2) a mapping already exists at the specified virtual
4950 * address, or (3) a PV entry cannot be allocated without reclaiming another
4954 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4955 struct rwlock **lockp)
4960 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4961 PG_V = pmap_valid_bit(pmap);
4962 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
4964 if ((m->oflags & VPO_UNMANAGED) == 0)
4965 newpde |= PG_MANAGED;
4966 if ((prot & VM_PROT_EXECUTE) == 0)
4968 if (va < VM_MAXUSER_ADDRESS)
4970 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
4971 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
4976 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
4977 * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
4978 * otherwise. Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
4979 * a mapping already exists at the specified virtual address. Returns
4980 * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
4981 * page allocation failed. Returns KERN_RESOURCE_SHORTAGE if
4982 * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
4984 * The parameter "m" is only used when creating a managed, writeable mapping.
4987 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
4988 vm_page_t m, struct rwlock **lockp)
4990 struct spglist free;
4991 pd_entry_t oldpde, *pde;
4992 pt_entry_t PG_G, PG_RW, PG_V;
4995 PG_G = pmap_global_bit(pmap);
4996 PG_RW = pmap_rw_bit(pmap);
4997 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
4998 ("pmap_enter_pde: newpde is missing PG_M"));
4999 PG_V = pmap_valid_bit(pmap);
5000 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5002 if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
5003 NULL : lockp)) == NULL) {
5004 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5005 " in pmap %p", va, pmap);
5006 return (KERN_RESOURCE_SHORTAGE);
5008 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5009 pde = &pde[pmap_pde_index(va)];
5011 if ((oldpde & PG_V) != 0) {
5012 KASSERT(pdpg->wire_count > 1,
5013 ("pmap_enter_pde: pdpg's wire count is too low"));
5014 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
5016 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5017 " in pmap %p", va, pmap);
5018 return (KERN_FAILURE);
5020 /* Break the existing mapping(s). */
5022 if ((oldpde & PG_PS) != 0) {
5024 * The reference to the PD page that was acquired by
5025 * pmap_allocpde() ensures that it won't be freed.
5026 * However, if the PDE resulted from a promotion, then
5027 * a reserved PT page could be freed.
5029 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
5030 if ((oldpde & PG_G) == 0)
5031 pmap_invalidate_pde_page(pmap, va, oldpde);
5033 pmap_delayed_invl_started();
5034 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
5036 pmap_invalidate_all(pmap);
5037 pmap_delayed_invl_finished();
5039 pmap_free_zero_pages(&free);
5040 if (va >= VM_MAXUSER_ADDRESS) {
5041 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
5042 if (pmap_insert_pt_page(pmap, mt)) {
5044 * XXX Currently, this can't happen because
5045 * we do not perform pmap_enter(psind == 1)
5046 * on the kernel pmap.
5048 panic("pmap_enter_pde: trie insert failed");
5051 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
5054 if ((newpde & PG_MANAGED) != 0) {
5056 * Abort this mapping if its PV entry could not be created.
5058 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
5060 if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
5062 * Although "va" is not mapped, paging-
5063 * structure caches could nonetheless have
5064 * entries that refer to the freed page table
5065 * pages. Invalidate those entries.
5067 pmap_invalidate_page(pmap, va);
5068 pmap_free_zero_pages(&free);
5070 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5071 " in pmap %p", va, pmap);
5072 return (KERN_RESOURCE_SHORTAGE);
5074 if ((newpde & PG_RW) != 0) {
5075 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5076 vm_page_aflag_set(mt, PGA_WRITEABLE);
5081 * Increment counters.
5083 if ((newpde & PG_W) != 0)
5084 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
5085 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5088 * Map the superpage. (This is not a promoted mapping; there will not
5089 * be any lingering 4KB page mappings in the TLB.)
5091 pde_store(pde, newpde);
5093 atomic_add_long(&pmap_pde_mappings, 1);
5094 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
5095 " in pmap %p", va, pmap);
5096 return (KERN_SUCCESS);
5100 * Maps a sequence of resident pages belonging to the same object.
5101 * The sequence begins with the given page m_start. This page is
5102 * mapped at the given virtual address start. Each subsequent page is
5103 * mapped at a virtual address that is offset from start by the same
5104 * amount as the page is offset from m_start within the object. The
5105 * last page in the sequence is the page with the largest offset from
5106 * m_start that can be mapped at a virtual address less than the given
5107 * virtual address end. Not every virtual page between start and end
5108 * is mapped; only those for which a resident page exists with the
5109 * corresponding offset from m_start are mapped.
5112 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
5113 vm_page_t m_start, vm_prot_t prot)
5115 struct rwlock *lock;
5118 vm_pindex_t diff, psize;
5120 VM_OBJECT_ASSERT_LOCKED(m_start->object);
5122 psize = atop(end - start);
5127 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
5128 va = start + ptoa(diff);
5129 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
5130 m->psind == 1 && pmap_ps_enabled(pmap) &&
5131 pmap_enter_2mpage(pmap, va, m, prot, &lock))
5132 m = &m[NBPDR / PAGE_SIZE - 1];
5134 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
5136 m = TAILQ_NEXT(m, listq);
5144 * this code makes some *MAJOR* assumptions:
5145 * 1. Current pmap & pmap exists.
5148 * 4. No page table pages.
5149 * but is *MUCH* faster than pmap_enter...
5153 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
5155 struct rwlock *lock;
5159 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
5166 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
5167 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
5169 struct spglist free;
5170 pt_entry_t *pte, PG_V;
5173 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
5174 (m->oflags & VPO_UNMANAGED) != 0,
5175 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
5176 PG_V = pmap_valid_bit(pmap);
5177 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5180 * In the case that a page table page is not
5181 * resident, we are creating it here.
5183 if (va < VM_MAXUSER_ADDRESS) {
5184 vm_pindex_t ptepindex;
5188 * Calculate pagetable page index
5190 ptepindex = pmap_pde_pindex(va);
5191 if (mpte && (mpte->pindex == ptepindex)) {
5195 * Get the page directory entry
5197 ptepa = pmap_pde(pmap, va);
5200 * If the page table page is mapped, we just increment
5201 * the hold count, and activate it. Otherwise, we
5202 * attempt to allocate a page table page. If this
5203 * attempt fails, we don't retry. Instead, we give up.
5205 if (ptepa && (*ptepa & PG_V) != 0) {
5208 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
5212 * Pass NULL instead of the PV list lock
5213 * pointer, because we don't intend to sleep.
5215 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
5220 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
5221 pte = &pte[pmap_pte_index(va)];
5235 * Enter on the PV list if part of our managed memory.
5237 if ((m->oflags & VPO_UNMANAGED) == 0 &&
5238 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
5241 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
5243 * Although "va" is not mapped, paging-
5244 * structure caches could nonetheless have
5245 * entries that refer to the freed page table
5246 * pages. Invalidate those entries.
5248 pmap_invalidate_page(pmap, va);
5249 pmap_free_zero_pages(&free);
5257 * Increment counters
5259 pmap_resident_count_inc(pmap, 1);
5261 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
5262 if ((prot & VM_PROT_EXECUTE) == 0)
5266 * Now validate mapping with RO protection
5268 if ((m->oflags & VPO_UNMANAGED) != 0)
5269 pte_store(pte, pa | PG_V | PG_U);
5271 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
5276 * Make a temporary mapping for a physical address. This is only intended
5277 * to be used for panic dumps.
5280 pmap_kenter_temporary(vm_paddr_t pa, int i)
5284 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
5285 pmap_kenter(va, pa);
5287 return ((void *)crashdumpmap);
5291 * This code maps large physical mmap regions into the
5292 * processor address space. Note that some shortcuts
5293 * are taken, but the code works.
5296 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
5297 vm_pindex_t pindex, vm_size_t size)
5300 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5301 vm_paddr_t pa, ptepa;
5305 PG_A = pmap_accessed_bit(pmap);
5306 PG_M = pmap_modified_bit(pmap);
5307 PG_V = pmap_valid_bit(pmap);
5308 PG_RW = pmap_rw_bit(pmap);
5310 VM_OBJECT_ASSERT_WLOCKED(object);
5311 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
5312 ("pmap_object_init_pt: non-device object"));
5313 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
5314 if (!pmap_ps_enabled(pmap))
5316 if (!vm_object_populate(object, pindex, pindex + atop(size)))
5318 p = vm_page_lookup(object, pindex);
5319 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5320 ("pmap_object_init_pt: invalid page %p", p));
5321 pat_mode = p->md.pat_mode;
5324 * Abort the mapping if the first page is not physically
5325 * aligned to a 2MB page boundary.
5327 ptepa = VM_PAGE_TO_PHYS(p);
5328 if (ptepa & (NBPDR - 1))
5332 * Skip the first page. Abort the mapping if the rest of
5333 * the pages are not physically contiguous or have differing
5334 * memory attributes.
5336 p = TAILQ_NEXT(p, listq);
5337 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
5339 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5340 ("pmap_object_init_pt: invalid page %p", p));
5341 if (pa != VM_PAGE_TO_PHYS(p) ||
5342 pat_mode != p->md.pat_mode)
5344 p = TAILQ_NEXT(p, listq);
5348 * Map using 2MB pages. Since "ptepa" is 2M aligned and
5349 * "size" is a multiple of 2M, adding the PAT setting to "pa"
5350 * will not affect the termination of this loop.
5353 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
5354 pa < ptepa + size; pa += NBPDR) {
5355 pdpg = pmap_allocpde(pmap, addr, NULL);
5358 * The creation of mappings below is only an
5359 * optimization. If a page directory page
5360 * cannot be allocated without blocking,
5361 * continue on to the next mapping rather than
5367 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5368 pde = &pde[pmap_pde_index(addr)];
5369 if ((*pde & PG_V) == 0) {
5370 pde_store(pde, pa | PG_PS | PG_M | PG_A |
5371 PG_U | PG_RW | PG_V);
5372 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5373 atomic_add_long(&pmap_pde_mappings, 1);
5375 /* Continue on if the PDE is already valid. */
5377 KASSERT(pdpg->wire_count > 0,
5378 ("pmap_object_init_pt: missing reference "
5379 "to page directory page, va: 0x%lx", addr));
5388 * Clear the wired attribute from the mappings for the specified range of
5389 * addresses in the given pmap. Every valid mapping within that range
5390 * must have the wired attribute set. In contrast, invalid mappings
5391 * cannot have the wired attribute set, so they are ignored.
5393 * The wired attribute of the page table entry is not a hardware
5394 * feature, so there is no need to invalidate any TLB entries.
5395 * Since pmap_demote_pde() for the wired entry must never fail,
5396 * pmap_delayed_invl_started()/finished() calls around the
5397 * function are not needed.
5400 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5402 vm_offset_t va_next;
5403 pml4_entry_t *pml4e;
5406 pt_entry_t *pte, PG_V;
5408 PG_V = pmap_valid_bit(pmap);
5410 for (; sva < eva; sva = va_next) {
5411 pml4e = pmap_pml4e(pmap, sva);
5412 if ((*pml4e & PG_V) == 0) {
5413 va_next = (sva + NBPML4) & ~PML4MASK;
5418 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5419 if ((*pdpe & PG_V) == 0) {
5420 va_next = (sva + NBPDP) & ~PDPMASK;
5425 va_next = (sva + NBPDR) & ~PDRMASK;
5428 pde = pmap_pdpe_to_pde(pdpe, sva);
5429 if ((*pde & PG_V) == 0)
5431 if ((*pde & PG_PS) != 0) {
5432 if ((*pde & PG_W) == 0)
5433 panic("pmap_unwire: pde %#jx is missing PG_W",
5437 * Are we unwiring the entire large page? If not,
5438 * demote the mapping and fall through.
5440 if (sva + NBPDR == va_next && eva >= va_next) {
5441 atomic_clear_long(pde, PG_W);
5442 pmap->pm_stats.wired_count -= NBPDR /
5445 } else if (!pmap_demote_pde(pmap, pde, sva))
5446 panic("pmap_unwire: demotion failed");
5450 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
5452 if ((*pte & PG_V) == 0)
5454 if ((*pte & PG_W) == 0)
5455 panic("pmap_unwire: pte %#jx is missing PG_W",
5459 * PG_W must be cleared atomically. Although the pmap
5460 * lock synchronizes access to PG_W, another processor
5461 * could be setting PG_M and/or PG_A concurrently.
5463 atomic_clear_long(pte, PG_W);
5464 pmap->pm_stats.wired_count--;
5471 * Copy the range specified by src_addr/len
5472 * from the source map to the range dst_addr/len
5473 * in the destination map.
5475 * This routine is only advisory and need not do anything.
5479 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5480 vm_offset_t src_addr)
5482 struct rwlock *lock;
5483 struct spglist free;
5485 vm_offset_t end_addr = src_addr + len;
5486 vm_offset_t va_next;
5487 vm_page_t dst_pdpg, dstmpte, srcmpte;
5488 pt_entry_t PG_A, PG_M, PG_V;
5490 if (dst_addr != src_addr)
5493 if (dst_pmap->pm_type != src_pmap->pm_type)
5497 * EPT page table entries that require emulation of A/D bits are
5498 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5499 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5500 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5501 * implementations flag an EPT misconfiguration for exec-only
5502 * mappings we skip this function entirely for emulated pmaps.
5504 if (pmap_emulate_ad_bits(dst_pmap))
5508 if (dst_pmap < src_pmap) {
5509 PMAP_LOCK(dst_pmap);
5510 PMAP_LOCK(src_pmap);
5512 PMAP_LOCK(src_pmap);
5513 PMAP_LOCK(dst_pmap);
5516 PG_A = pmap_accessed_bit(dst_pmap);
5517 PG_M = pmap_modified_bit(dst_pmap);
5518 PG_V = pmap_valid_bit(dst_pmap);
5520 for (addr = src_addr; addr < end_addr; addr = va_next) {
5521 pt_entry_t *src_pte, *dst_pte;
5522 pml4_entry_t *pml4e;
5524 pd_entry_t srcptepaddr, *pde;
5526 KASSERT(addr < UPT_MIN_ADDRESS,
5527 ("pmap_copy: invalid to pmap_copy page tables"));
5529 pml4e = pmap_pml4e(src_pmap, addr);
5530 if ((*pml4e & PG_V) == 0) {
5531 va_next = (addr + NBPML4) & ~PML4MASK;
5537 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5538 if ((*pdpe & PG_V) == 0) {
5539 va_next = (addr + NBPDP) & ~PDPMASK;
5545 va_next = (addr + NBPDR) & ~PDRMASK;
5549 pde = pmap_pdpe_to_pde(pdpe, addr);
5551 if (srcptepaddr == 0)
5554 if (srcptepaddr & PG_PS) {
5555 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5557 dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
5558 if (dst_pdpg == NULL)
5560 pde = (pd_entry_t *)
5561 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
5562 pde = &pde[pmap_pde_index(addr)];
5563 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5564 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
5565 PMAP_ENTER_NORECLAIM, &lock))) {
5566 *pde = srcptepaddr & ~PG_W;
5567 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5568 atomic_add_long(&pmap_pde_mappings, 1);
5570 dst_pdpg->wire_count--;
5574 srcptepaddr &= PG_FRAME;
5575 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5576 KASSERT(srcmpte->wire_count > 0,
5577 ("pmap_copy: source page table page is unused"));
5579 if (va_next > end_addr)
5582 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5583 src_pte = &src_pte[pmap_pte_index(addr)];
5585 while (addr < va_next) {
5589 * we only virtual copy managed pages
5591 if ((ptetemp & PG_MANAGED) != 0) {
5592 if (dstmpte != NULL &&
5593 dstmpte->pindex == pmap_pde_pindex(addr))
5594 dstmpte->wire_count++;
5595 else if ((dstmpte = pmap_allocpte(dst_pmap,
5596 addr, NULL)) == NULL)
5598 dst_pte = (pt_entry_t *)
5599 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5600 dst_pte = &dst_pte[pmap_pte_index(addr)];
5601 if (*dst_pte == 0 &&
5602 pmap_try_insert_pv_entry(dst_pmap, addr,
5603 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5606 * Clear the wired, modified, and
5607 * accessed (referenced) bits
5610 *dst_pte = ptetemp & ~(PG_W | PG_M |
5612 pmap_resident_count_inc(dst_pmap, 1);
5615 if (pmap_unwire_ptp(dst_pmap, addr,
5618 * Although "addr" is not
5619 * mapped, paging-structure
5620 * caches could nonetheless
5621 * have entries that refer to
5622 * the freed page table pages.
5623 * Invalidate those entries.
5625 pmap_invalidate_page(dst_pmap,
5627 pmap_free_zero_pages(&free);
5631 if (dstmpte->wire_count >= srcmpte->wire_count)
5641 PMAP_UNLOCK(src_pmap);
5642 PMAP_UNLOCK(dst_pmap);
5646 * pmap_zero_page zeros the specified hardware page by mapping
5647 * the page into KVM and using bzero to clear its contents.
5650 pmap_zero_page(vm_page_t m)
5652 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5654 pagezero((void *)va);
5658 * pmap_zero_page_area zeros the specified hardware page by mapping
5659 * the page into KVM and using bzero to clear its contents.
5661 * off and size may not cover an area beyond a single hardware page.
5664 pmap_zero_page_area(vm_page_t m, int off, int size)
5666 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5668 if (off == 0 && size == PAGE_SIZE)
5669 pagezero((void *)va);
5671 bzero((char *)va + off, size);
5675 * pmap_zero_page_idle zeros the specified hardware page by mapping
5676 * the page into KVM and using bzero to clear its contents. This
5677 * is intended to be called from the vm_pagezero process only and
5681 pmap_zero_page_idle(vm_page_t m)
5683 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5685 pagezero((void *)va);
5689 * pmap_copy_page copies the specified (machine independent)
5690 * page by mapping the page into virtual memory and using
5691 * bcopy to copy the page, one machine dependent page at a
5695 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5697 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5698 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5700 pagecopy((void *)src, (void *)dst);
5703 int unmapped_buf_allowed = 1;
5706 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5707 vm_offset_t b_offset, int xfersize)
5711 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5715 while (xfersize > 0) {
5716 a_pg_offset = a_offset & PAGE_MASK;
5717 pages[0] = ma[a_offset >> PAGE_SHIFT];
5718 b_pg_offset = b_offset & PAGE_MASK;
5719 pages[1] = mb[b_offset >> PAGE_SHIFT];
5720 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5721 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5722 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5723 a_cp = (char *)vaddr[0] + a_pg_offset;
5724 b_cp = (char *)vaddr[1] + b_pg_offset;
5725 bcopy(a_cp, b_cp, cnt);
5726 if (__predict_false(mapped))
5727 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5735 * Returns true if the pmap's pv is one of the first
5736 * 16 pvs linked to from this page. This count may
5737 * be changed upwards or downwards in the future; it
5738 * is only necessary that true be returned for a small
5739 * subset of pmaps for proper page aging.
5742 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5744 struct md_page *pvh;
5745 struct rwlock *lock;
5750 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5751 ("pmap_page_exists_quick: page %p is not managed", m));
5753 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5755 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5756 if (PV_PMAP(pv) == pmap) {
5764 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5765 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5766 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5767 if (PV_PMAP(pv) == pmap) {
5781 * pmap_page_wired_mappings:
5783 * Return the number of managed mappings to the given physical page
5787 pmap_page_wired_mappings(vm_page_t m)
5789 struct rwlock *lock;
5790 struct md_page *pvh;
5794 int count, md_gen, pvh_gen;
5796 if ((m->oflags & VPO_UNMANAGED) != 0)
5798 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5802 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5804 if (!PMAP_TRYLOCK(pmap)) {
5805 md_gen = m->md.pv_gen;
5809 if (md_gen != m->md.pv_gen) {
5814 pte = pmap_pte(pmap, pv->pv_va);
5815 if ((*pte & PG_W) != 0)
5819 if ((m->flags & PG_FICTITIOUS) == 0) {
5820 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5821 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5823 if (!PMAP_TRYLOCK(pmap)) {
5824 md_gen = m->md.pv_gen;
5825 pvh_gen = pvh->pv_gen;
5829 if (md_gen != m->md.pv_gen ||
5830 pvh_gen != pvh->pv_gen) {
5835 pte = pmap_pde(pmap, pv->pv_va);
5836 if ((*pte & PG_W) != 0)
5846 * Returns TRUE if the given page is mapped individually or as part of
5847 * a 2mpage. Otherwise, returns FALSE.
5850 pmap_page_is_mapped(vm_page_t m)
5852 struct rwlock *lock;
5855 if ((m->oflags & VPO_UNMANAGED) != 0)
5857 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5859 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5860 ((m->flags & PG_FICTITIOUS) == 0 &&
5861 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5867 * Destroy all managed, non-wired mappings in the given user-space
5868 * pmap. This pmap cannot be active on any processor besides the
5871 * This function cannot be applied to the kernel pmap. Moreover, it
5872 * is not intended for general use. It is only to be used during
5873 * process termination. Consequently, it can be implemented in ways
5874 * that make it faster than pmap_remove(). First, it can more quickly
5875 * destroy mappings by iterating over the pmap's collection of PV
5876 * entries, rather than searching the page table. Second, it doesn't
5877 * have to test and clear the page table entries atomically, because
5878 * no processor is currently accessing the user address space. In
5879 * particular, a page table entry's dirty bit won't change state once
5880 * this function starts.
5882 * Although this function destroys all of the pmap's managed,
5883 * non-wired mappings, it can delay and batch the invalidation of TLB
5884 * entries without calling pmap_delayed_invl_started() and
5885 * pmap_delayed_invl_finished(). Because the pmap is not active on
5886 * any other processor, none of these TLB entries will ever be used
5887 * before their eventual invalidation. Consequently, there is no need
5888 * for either pmap_remove_all() or pmap_remove_write() to wait for
5889 * that eventual TLB invalidation.
5892 pmap_remove_pages(pmap_t pmap)
5895 pt_entry_t *pte, tpte;
5896 pt_entry_t PG_M, PG_RW, PG_V;
5897 struct spglist free;
5898 vm_page_t m, mpte, mt;
5900 struct md_page *pvh;
5901 struct pv_chunk *pc, *npc;
5902 struct rwlock *lock;
5904 uint64_t inuse, bitmask;
5905 int allfree, field, freed, idx;
5906 boolean_t superpage;
5910 * Assert that the given pmap is only active on the current
5911 * CPU. Unfortunately, we cannot block another CPU from
5912 * activating the pmap while this function is executing.
5914 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5917 cpuset_t other_cpus;
5919 other_cpus = all_cpus;
5921 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5922 CPU_AND(&other_cpus, &pmap->pm_active);
5924 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5929 PG_M = pmap_modified_bit(pmap);
5930 PG_V = pmap_valid_bit(pmap);
5931 PG_RW = pmap_rw_bit(pmap);
5935 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5938 for (field = 0; field < _NPCM; field++) {
5939 inuse = ~pc->pc_map[field] & pc_freemask[field];
5940 while (inuse != 0) {
5942 bitmask = 1UL << bit;
5943 idx = field * 64 + bit;
5944 pv = &pc->pc_pventry[idx];
5947 pte = pmap_pdpe(pmap, pv->pv_va);
5949 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5951 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5954 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5956 pte = &pte[pmap_pte_index(pv->pv_va)];
5960 * Keep track whether 'tpte' is a
5961 * superpage explicitly instead of
5962 * relying on PG_PS being set.
5964 * This is because PG_PS is numerically
5965 * identical to PG_PTE_PAT and thus a
5966 * regular page could be mistaken for
5972 if ((tpte & PG_V) == 0) {
5973 panic("bad pte va %lx pte %lx",
5978 * We cannot remove wired pages from a process' mapping at this time
5986 pa = tpte & PG_PS_FRAME;
5988 pa = tpte & PG_FRAME;
5990 m = PHYS_TO_VM_PAGE(pa);
5991 KASSERT(m->phys_addr == pa,
5992 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5993 m, (uintmax_t)m->phys_addr,
5996 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5997 m < &vm_page_array[vm_page_array_size],
5998 ("pmap_remove_pages: bad tpte %#jx",
6004 * Update the vm_page_t clean/reference bits.
6006 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6008 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6014 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
6017 pc->pc_map[field] |= bitmask;
6019 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
6020 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
6021 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6023 if (TAILQ_EMPTY(&pvh->pv_list)) {
6024 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6025 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
6026 TAILQ_EMPTY(&mt->md.pv_list))
6027 vm_page_aflag_clear(mt, PGA_WRITEABLE);
6029 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
6031 pmap_resident_count_dec(pmap, 1);
6032 KASSERT(mpte->wire_count == NPTEPG,
6033 ("pmap_remove_pages: pte page wire count error"));
6034 mpte->wire_count = 0;
6035 pmap_add_delayed_free_list(mpte, &free, FALSE);
6038 pmap_resident_count_dec(pmap, 1);
6039 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6041 if ((m->aflags & PGA_WRITEABLE) != 0 &&
6042 TAILQ_EMPTY(&m->md.pv_list) &&
6043 (m->flags & PG_FICTITIOUS) == 0) {
6044 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6045 if (TAILQ_EMPTY(&pvh->pv_list))
6046 vm_page_aflag_clear(m, PGA_WRITEABLE);
6049 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
6053 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
6054 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
6055 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
6057 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
6063 pmap_invalidate_all(pmap);
6065 pmap_free_zero_pages(&free);
6069 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
6071 struct rwlock *lock;
6073 struct md_page *pvh;
6074 pt_entry_t *pte, mask;
6075 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6077 int md_gen, pvh_gen;
6081 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6084 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6086 if (!PMAP_TRYLOCK(pmap)) {
6087 md_gen = m->md.pv_gen;
6091 if (md_gen != m->md.pv_gen) {
6096 pte = pmap_pte(pmap, pv->pv_va);
6099 PG_M = pmap_modified_bit(pmap);
6100 PG_RW = pmap_rw_bit(pmap);
6101 mask |= PG_RW | PG_M;
6104 PG_A = pmap_accessed_bit(pmap);
6105 PG_V = pmap_valid_bit(pmap);
6106 mask |= PG_V | PG_A;
6108 rv = (*pte & mask) == mask;
6113 if ((m->flags & PG_FICTITIOUS) == 0) {
6114 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6115 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
6117 if (!PMAP_TRYLOCK(pmap)) {
6118 md_gen = m->md.pv_gen;
6119 pvh_gen = pvh->pv_gen;
6123 if (md_gen != m->md.pv_gen ||
6124 pvh_gen != pvh->pv_gen) {
6129 pte = pmap_pde(pmap, pv->pv_va);
6132 PG_M = pmap_modified_bit(pmap);
6133 PG_RW = pmap_rw_bit(pmap);
6134 mask |= PG_RW | PG_M;
6137 PG_A = pmap_accessed_bit(pmap);
6138 PG_V = pmap_valid_bit(pmap);
6139 mask |= PG_V | PG_A;
6141 rv = (*pte & mask) == mask;
6155 * Return whether or not the specified physical page was modified
6156 * in any physical maps.
6159 pmap_is_modified(vm_page_t m)
6162 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6163 ("pmap_is_modified: page %p is not managed", m));
6166 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6167 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
6168 * is clear, no PTEs can have PG_M set.
6170 VM_OBJECT_ASSERT_WLOCKED(m->object);
6171 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6173 return (pmap_page_test_mappings(m, FALSE, TRUE));
6177 * pmap_is_prefaultable:
6179 * Return whether or not the specified virtual address is eligible
6183 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
6186 pt_entry_t *pte, PG_V;
6189 PG_V = pmap_valid_bit(pmap);
6192 pde = pmap_pde(pmap, addr);
6193 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
6194 pte = pmap_pde_to_pte(pde, addr);
6195 rv = (*pte & PG_V) == 0;
6202 * pmap_is_referenced:
6204 * Return whether or not the specified physical page was referenced
6205 * in any physical maps.
6208 pmap_is_referenced(vm_page_t m)
6211 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6212 ("pmap_is_referenced: page %p is not managed", m));
6213 return (pmap_page_test_mappings(m, TRUE, FALSE));
6217 * Clear the write and modified bits in each of the given page's mappings.
6220 pmap_remove_write(vm_page_t m)
6222 struct md_page *pvh;
6224 struct rwlock *lock;
6225 pv_entry_t next_pv, pv;
6227 pt_entry_t oldpte, *pte, PG_M, PG_RW;
6229 int pvh_gen, md_gen;
6231 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6232 ("pmap_remove_write: page %p is not managed", m));
6235 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6236 * set by another thread while the object is locked. Thus,
6237 * if PGA_WRITEABLE is clear, no page table entries need updating.
6239 VM_OBJECT_ASSERT_WLOCKED(m->object);
6240 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6242 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6243 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6244 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6247 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6249 if (!PMAP_TRYLOCK(pmap)) {
6250 pvh_gen = pvh->pv_gen;
6254 if (pvh_gen != pvh->pv_gen) {
6260 PG_RW = pmap_rw_bit(pmap);
6262 pde = pmap_pde(pmap, va);
6263 if ((*pde & PG_RW) != 0)
6264 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6265 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6266 ("inconsistent pv lock %p %p for page %p",
6267 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6270 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6272 if (!PMAP_TRYLOCK(pmap)) {
6273 pvh_gen = pvh->pv_gen;
6274 md_gen = m->md.pv_gen;
6278 if (pvh_gen != pvh->pv_gen ||
6279 md_gen != m->md.pv_gen) {
6285 PG_M = pmap_modified_bit(pmap);
6286 PG_RW = pmap_rw_bit(pmap);
6287 pde = pmap_pde(pmap, pv->pv_va);
6288 KASSERT((*pde & PG_PS) == 0,
6289 ("pmap_remove_write: found a 2mpage in page %p's pv list",
6291 pte = pmap_pde_to_pte(pde, pv->pv_va);
6294 if (oldpte & PG_RW) {
6295 if (!atomic_cmpset_long(pte, oldpte, oldpte &
6298 if ((oldpte & PG_M) != 0)
6300 pmap_invalidate_page(pmap, pv->pv_va);
6305 vm_page_aflag_clear(m, PGA_WRITEABLE);
6306 pmap_delayed_invl_wait(m);
6309 static __inline boolean_t
6310 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
6313 if (!pmap_emulate_ad_bits(pmap))
6316 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
6319 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
6320 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
6321 * if the EPT_PG_WRITE bit is set.
6323 if ((pte & EPT_PG_WRITE) != 0)
6327 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
6329 if ((pte & EPT_PG_EXECUTE) == 0 ||
6330 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
6337 * pmap_ts_referenced:
6339 * Return a count of reference bits for a page, clearing those bits.
6340 * It is not necessary for every reference bit to be cleared, but it
6341 * is necessary that 0 only be returned when there are truly no
6342 * reference bits set.
6344 * As an optimization, update the page's dirty field if a modified bit is
6345 * found while counting reference bits. This opportunistic update can be
6346 * performed at low cost and can eliminate the need for some future calls
6347 * to pmap_is_modified(). However, since this function stops after
6348 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
6349 * dirty pages. Those dirty pages will only be detected by a future call
6350 * to pmap_is_modified().
6352 * A DI block is not needed within this function, because
6353 * invalidations are performed before the PV list lock is
6357 pmap_ts_referenced(vm_page_t m)
6359 struct md_page *pvh;
6362 struct rwlock *lock;
6363 pd_entry_t oldpde, *pde;
6364 pt_entry_t *pte, PG_A, PG_M, PG_RW;
6367 int cleared, md_gen, not_cleared, pvh_gen;
6368 struct spglist free;
6371 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6372 ("pmap_ts_referenced: page %p is not managed", m));
6375 pa = VM_PAGE_TO_PHYS(m);
6376 lock = PHYS_TO_PV_LIST_LOCK(pa);
6377 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
6381 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6382 goto small_mappings;
6388 if (!PMAP_TRYLOCK(pmap)) {
6389 pvh_gen = pvh->pv_gen;
6393 if (pvh_gen != pvh->pv_gen) {
6398 PG_A = pmap_accessed_bit(pmap);
6399 PG_M = pmap_modified_bit(pmap);
6400 PG_RW = pmap_rw_bit(pmap);
6402 pde = pmap_pde(pmap, pv->pv_va);
6404 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6406 * Although "oldpde" is mapping a 2MB page, because
6407 * this function is called at a 4KB page granularity,
6408 * we only update the 4KB page under test.
6412 if ((oldpde & PG_A) != 0) {
6414 * Since this reference bit is shared by 512 4KB
6415 * pages, it should not be cleared every time it is
6416 * tested. Apply a simple "hash" function on the
6417 * physical page number, the virtual superpage number,
6418 * and the pmap address to select one 4KB page out of
6419 * the 512 on which testing the reference bit will
6420 * result in clearing that reference bit. This
6421 * function is designed to avoid the selection of the
6422 * same 4KB page for every 2MB page mapping.
6424 * On demotion, a mapping that hasn't been referenced
6425 * is simply destroyed. To avoid the possibility of a
6426 * subsequent page fault on a demoted wired mapping,
6427 * always leave its reference bit set. Moreover,
6428 * since the superpage is wired, the current state of
6429 * its reference bit won't affect page replacement.
6431 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
6432 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
6433 (oldpde & PG_W) == 0) {
6434 if (safe_to_clear_referenced(pmap, oldpde)) {
6435 atomic_clear_long(pde, PG_A);
6436 pmap_invalidate_page(pmap, pv->pv_va);
6438 } else if (pmap_demote_pde_locked(pmap, pde,
6439 pv->pv_va, &lock)) {
6441 * Remove the mapping to a single page
6442 * so that a subsequent access may
6443 * repromote. Since the underlying
6444 * page table page is fully populated,
6445 * this removal never frees a page
6449 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6451 pte = pmap_pde_to_pte(pde, va);
6452 pmap_remove_pte(pmap, pte, va, *pde,
6454 pmap_invalidate_page(pmap, va);
6460 * The superpage mapping was removed
6461 * entirely and therefore 'pv' is no
6469 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6470 ("inconsistent pv lock %p %p for page %p",
6471 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6476 /* Rotate the PV list if it has more than one entry. */
6477 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6478 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6479 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6482 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6484 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6486 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6493 if (!PMAP_TRYLOCK(pmap)) {
6494 pvh_gen = pvh->pv_gen;
6495 md_gen = m->md.pv_gen;
6499 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6504 PG_A = pmap_accessed_bit(pmap);
6505 PG_M = pmap_modified_bit(pmap);
6506 PG_RW = pmap_rw_bit(pmap);
6507 pde = pmap_pde(pmap, pv->pv_va);
6508 KASSERT((*pde & PG_PS) == 0,
6509 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6511 pte = pmap_pde_to_pte(pde, pv->pv_va);
6512 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6514 if ((*pte & PG_A) != 0) {
6515 if (safe_to_clear_referenced(pmap, *pte)) {
6516 atomic_clear_long(pte, PG_A);
6517 pmap_invalidate_page(pmap, pv->pv_va);
6519 } else if ((*pte & PG_W) == 0) {
6521 * Wired pages cannot be paged out so
6522 * doing accessed bit emulation for
6523 * them is wasted effort. We do the
6524 * hard work for unwired pages only.
6526 pmap_remove_pte(pmap, pte, pv->pv_va,
6527 *pde, &free, &lock);
6528 pmap_invalidate_page(pmap, pv->pv_va);
6533 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6534 ("inconsistent pv lock %p %p for page %p",
6535 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6540 /* Rotate the PV list if it has more than one entry. */
6541 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6542 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6543 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6546 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6547 not_cleared < PMAP_TS_REFERENCED_MAX);
6550 pmap_free_zero_pages(&free);
6551 return (cleared + not_cleared);
6555 * Apply the given advice to the specified range of addresses within the
6556 * given pmap. Depending on the advice, clear the referenced and/or
6557 * modified flags in each mapping and set the mapped page's dirty field.
6560 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6562 struct rwlock *lock;
6563 pml4_entry_t *pml4e;
6565 pd_entry_t oldpde, *pde;
6566 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6567 vm_offset_t va, va_next;
6569 boolean_t anychanged;
6571 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6575 * A/D bit emulation requires an alternate code path when clearing
6576 * the modified and accessed bits below. Since this function is
6577 * advisory in nature we skip it entirely for pmaps that require
6578 * A/D bit emulation.
6580 if (pmap_emulate_ad_bits(pmap))
6583 PG_A = pmap_accessed_bit(pmap);
6584 PG_G = pmap_global_bit(pmap);
6585 PG_M = pmap_modified_bit(pmap);
6586 PG_V = pmap_valid_bit(pmap);
6587 PG_RW = pmap_rw_bit(pmap);
6589 pmap_delayed_invl_started();
6591 for (; sva < eva; sva = va_next) {
6592 pml4e = pmap_pml4e(pmap, sva);
6593 if ((*pml4e & PG_V) == 0) {
6594 va_next = (sva + NBPML4) & ~PML4MASK;
6599 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6600 if ((*pdpe & PG_V) == 0) {
6601 va_next = (sva + NBPDP) & ~PDPMASK;
6606 va_next = (sva + NBPDR) & ~PDRMASK;
6609 pde = pmap_pdpe_to_pde(pdpe, sva);
6611 if ((oldpde & PG_V) == 0)
6613 else if ((oldpde & PG_PS) != 0) {
6614 if ((oldpde & PG_MANAGED) == 0)
6617 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6622 * The large page mapping was destroyed.
6628 * Unless the page mappings are wired, remove the
6629 * mapping to a single page so that a subsequent
6630 * access may repromote. Since the underlying page
6631 * table page is fully populated, this removal never
6632 * frees a page table page.
6634 if ((oldpde & PG_W) == 0) {
6635 pte = pmap_pde_to_pte(pde, sva);
6636 KASSERT((*pte & PG_V) != 0,
6637 ("pmap_advise: invalid PTE"));
6638 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6648 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6650 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6652 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6653 if (advice == MADV_DONTNEED) {
6655 * Future calls to pmap_is_modified()
6656 * can be avoided by making the page
6659 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6662 atomic_clear_long(pte, PG_M | PG_A);
6663 } else if ((*pte & PG_A) != 0)
6664 atomic_clear_long(pte, PG_A);
6668 if ((*pte & PG_G) != 0) {
6675 if (va != va_next) {
6676 pmap_invalidate_range(pmap, va, sva);
6681 pmap_invalidate_range(pmap, va, sva);
6684 pmap_invalidate_all(pmap);
6686 pmap_delayed_invl_finished();
6690 * Clear the modify bits on the specified physical page.
6693 pmap_clear_modify(vm_page_t m)
6695 struct md_page *pvh;
6697 pv_entry_t next_pv, pv;
6698 pd_entry_t oldpde, *pde;
6699 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6700 struct rwlock *lock;
6702 int md_gen, pvh_gen;
6704 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6705 ("pmap_clear_modify: page %p is not managed", m));
6706 VM_OBJECT_ASSERT_WLOCKED(m->object);
6707 KASSERT(!vm_page_xbusied(m),
6708 ("pmap_clear_modify: page %p is exclusive busied", m));
6711 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6712 * If the object containing the page is locked and the page is not
6713 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6715 if ((m->aflags & PGA_WRITEABLE) == 0)
6717 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6718 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6719 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6722 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6724 if (!PMAP_TRYLOCK(pmap)) {
6725 pvh_gen = pvh->pv_gen;
6729 if (pvh_gen != pvh->pv_gen) {
6734 PG_M = pmap_modified_bit(pmap);
6735 PG_V = pmap_valid_bit(pmap);
6736 PG_RW = pmap_rw_bit(pmap);
6738 pde = pmap_pde(pmap, va);
6740 if ((oldpde & PG_RW) != 0) {
6741 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6742 if ((oldpde & PG_W) == 0) {
6744 * Write protect the mapping to a
6745 * single page so that a subsequent
6746 * write access may repromote.
6748 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6750 pte = pmap_pde_to_pte(pde, va);
6752 if ((oldpte & PG_V) != 0) {
6753 while (!atomic_cmpset_long(pte,
6755 oldpte & ~(PG_M | PG_RW)))
6758 pmap_invalidate_page(pmap, va);
6765 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6767 if (!PMAP_TRYLOCK(pmap)) {
6768 md_gen = m->md.pv_gen;
6769 pvh_gen = pvh->pv_gen;
6773 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6778 PG_M = pmap_modified_bit(pmap);
6779 PG_RW = pmap_rw_bit(pmap);
6780 pde = pmap_pde(pmap, pv->pv_va);
6781 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6782 " a 2mpage in page %p's pv list", m));
6783 pte = pmap_pde_to_pte(pde, pv->pv_va);
6784 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6785 atomic_clear_long(pte, PG_M);
6786 pmap_invalidate_page(pmap, pv->pv_va);
6794 * Miscellaneous support routines follow
6797 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6798 static __inline void
6799 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6804 * The cache mode bits are all in the low 32-bits of the
6805 * PTE, so we can just spin on updating the low 32-bits.
6808 opte = *(u_int *)pte;
6809 npte = opte & ~mask;
6811 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6814 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6815 static __inline void
6816 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6821 * The cache mode bits are all in the low 32-bits of the
6822 * PDE, so we can just spin on updating the low 32-bits.
6825 opde = *(u_int *)pde;
6826 npde = opde & ~mask;
6828 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6832 * Map a set of physical memory pages into the kernel virtual
6833 * address space. Return a pointer to where it is mapped. This
6834 * routine is intended to be used for mapping device memory,
6838 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6840 struct pmap_preinit_mapping *ppim;
6841 vm_offset_t va, offset;
6845 offset = pa & PAGE_MASK;
6846 size = round_page(offset + size);
6847 pa = trunc_page(pa);
6849 if (!pmap_initialized) {
6851 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6852 ppim = pmap_preinit_mapping + i;
6853 if (ppim->va == 0) {
6857 ppim->va = virtual_avail;
6858 virtual_avail += size;
6864 panic("%s: too many preinit mappings", __func__);
6867 * If we have a preinit mapping, re-use it.
6869 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6870 ppim = pmap_preinit_mapping + i;
6871 if (ppim->pa == pa && ppim->sz == size &&
6873 return ((void *)(ppim->va + offset));
6876 * If the specified range of physical addresses fits within
6877 * the direct map window, use the direct map.
6879 if (pa < dmaplimit && pa + size < dmaplimit) {
6880 va = PHYS_TO_DMAP(pa);
6881 if (!pmap_change_attr(va, size, mode))
6882 return ((void *)(va + offset));
6884 va = kva_alloc(size);
6886 panic("%s: Couldn't allocate KVA", __func__);
6888 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6889 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6890 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6891 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6892 return ((void *)(va + offset));
6896 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6899 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6903 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6906 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6910 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6912 struct pmap_preinit_mapping *ppim;
6916 /* If we gave a direct map region in pmap_mapdev, do nothing */
6917 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6919 offset = va & PAGE_MASK;
6920 size = round_page(offset + size);
6921 va = trunc_page(va);
6922 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6923 ppim = pmap_preinit_mapping + i;
6924 if (ppim->va == va && ppim->sz == size) {
6925 if (pmap_initialized)
6931 if (va + size == virtual_avail)
6936 if (pmap_initialized)
6941 * Tries to demote a 1GB page mapping.
6944 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6946 pdp_entry_t newpdpe, oldpdpe;
6947 pd_entry_t *firstpde, newpde, *pde;
6948 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6952 PG_A = pmap_accessed_bit(pmap);
6953 PG_M = pmap_modified_bit(pmap);
6954 PG_V = pmap_valid_bit(pmap);
6955 PG_RW = pmap_rw_bit(pmap);
6957 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6959 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6960 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6961 if ((pdpg = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6962 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6963 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6964 " in pmap %p", va, pmap);
6967 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
6968 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
6969 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6970 KASSERT((oldpdpe & PG_A) != 0,
6971 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6972 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6973 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
6977 * Initialize the page directory page.
6979 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
6985 * Demote the mapping.
6990 * Invalidate a stale recursive mapping of the page directory page.
6992 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
6994 pmap_pdpe_demotions++;
6995 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
6996 " in pmap %p", va, pmap);
7001 * Sets the memory attribute for the specified page.
7004 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
7007 m->md.pat_mode = ma;
7010 * If "m" is a normal page, update its direct mapping. This update
7011 * can be relied upon to perform any cache operations that are
7012 * required for data coherence.
7014 if ((m->flags & PG_FICTITIOUS) == 0 &&
7015 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
7017 panic("memory attribute change on the direct map failed");
7021 * Changes the specified virtual address range's memory type to that given by
7022 * the parameter "mode". The specified virtual address range must be
7023 * completely contained within either the direct map or the kernel map. If
7024 * the virtual address range is contained within the kernel map, then the
7025 * memory type for each of the corresponding ranges of the direct map is also
7026 * changed. (The corresponding ranges of the direct map are those ranges that
7027 * map the same physical pages as the specified virtual address range.) These
7028 * changes to the direct map are necessary because Intel describes the
7029 * behavior of their processors as "undefined" if two or more mappings to the
7030 * same physical page have different memory types.
7032 * Returns zero if the change completed successfully, and either EINVAL or
7033 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
7034 * of the virtual address range was not mapped, and ENOMEM is returned if
7035 * there was insufficient memory available to complete the change. In the
7036 * latter case, the memory type may have been changed on some part of the
7037 * virtual address range or the direct map.
7040 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
7044 PMAP_LOCK(kernel_pmap);
7045 error = pmap_change_attr_locked(va, size, mode);
7046 PMAP_UNLOCK(kernel_pmap);
7051 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
7053 vm_offset_t base, offset, tmpva;
7054 vm_paddr_t pa_start, pa_end, pa_end1;
7058 int cache_bits_pte, cache_bits_pde, error;
7061 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
7062 base = trunc_page(va);
7063 offset = va & PAGE_MASK;
7064 size = round_page(offset + size);
7067 * Only supported on kernel virtual addresses, including the direct
7068 * map but excluding the recursive map.
7070 if (base < DMAP_MIN_ADDRESS)
7073 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
7074 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
7078 * Pages that aren't mapped aren't supported. Also break down 2MB pages
7079 * into 4KB pages if required.
7081 for (tmpva = base; tmpva < base + size; ) {
7082 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7083 if (pdpe == NULL || *pdpe == 0)
7085 if (*pdpe & PG_PS) {
7087 * If the current 1GB page already has the required
7088 * memory type, then we need not demote this page. Just
7089 * increment tmpva to the next 1GB page frame.
7091 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
7092 tmpva = trunc_1gpage(tmpva) + NBPDP;
7097 * If the current offset aligns with a 1GB page frame
7098 * and there is at least 1GB left within the range, then
7099 * we need not break down this page into 2MB pages.
7101 if ((tmpva & PDPMASK) == 0 &&
7102 tmpva + PDPMASK < base + size) {
7106 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
7109 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7114 * If the current 2MB page already has the required
7115 * memory type, then we need not demote this page. Just
7116 * increment tmpva to the next 2MB page frame.
7118 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
7119 tmpva = trunc_2mpage(tmpva) + NBPDR;
7124 * If the current offset aligns with a 2MB page frame
7125 * and there is at least 2MB left within the range, then
7126 * we need not break down this page into 4KB pages.
7128 if ((tmpva & PDRMASK) == 0 &&
7129 tmpva + PDRMASK < base + size) {
7133 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
7136 pte = pmap_pde_to_pte(pde, tmpva);
7144 * Ok, all the pages exist, so run through them updating their
7145 * cache mode if required.
7147 pa_start = pa_end = 0;
7148 for (tmpva = base; tmpva < base + size; ) {
7149 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7150 if (*pdpe & PG_PS) {
7151 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
7152 pmap_pde_attr(pdpe, cache_bits_pde,
7156 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7157 (*pdpe & PG_PS_FRAME) < dmaplimit) {
7158 if (pa_start == pa_end) {
7159 /* Start physical address run. */
7160 pa_start = *pdpe & PG_PS_FRAME;
7161 pa_end = pa_start + NBPDP;
7162 } else if (pa_end == (*pdpe & PG_PS_FRAME))
7165 /* Run ended, update direct map. */
7166 error = pmap_change_attr_locked(
7167 PHYS_TO_DMAP(pa_start),
7168 pa_end - pa_start, mode);
7171 /* Start physical address run. */
7172 pa_start = *pdpe & PG_PS_FRAME;
7173 pa_end = pa_start + NBPDP;
7176 tmpva = trunc_1gpage(tmpva) + NBPDP;
7179 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7181 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
7182 pmap_pde_attr(pde, cache_bits_pde,
7186 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7187 (*pde & PG_PS_FRAME) < dmaplimit) {
7188 if (pa_start == pa_end) {
7189 /* Start physical address run. */
7190 pa_start = *pde & PG_PS_FRAME;
7191 pa_end = pa_start + NBPDR;
7192 } else if (pa_end == (*pde & PG_PS_FRAME))
7195 /* Run ended, update direct map. */
7196 error = pmap_change_attr_locked(
7197 PHYS_TO_DMAP(pa_start),
7198 pa_end - pa_start, mode);
7201 /* Start physical address run. */
7202 pa_start = *pde & PG_PS_FRAME;
7203 pa_end = pa_start + NBPDR;
7206 tmpva = trunc_2mpage(tmpva) + NBPDR;
7208 pte = pmap_pde_to_pte(pde, tmpva);
7209 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
7210 pmap_pte_attr(pte, cache_bits_pte,
7214 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7215 (*pte & PG_FRAME) < dmaplimit) {
7216 if (pa_start == pa_end) {
7217 /* Start physical address run. */
7218 pa_start = *pte & PG_FRAME;
7219 pa_end = pa_start + PAGE_SIZE;
7220 } else if (pa_end == (*pte & PG_FRAME))
7221 pa_end += PAGE_SIZE;
7223 /* Run ended, update direct map. */
7224 error = pmap_change_attr_locked(
7225 PHYS_TO_DMAP(pa_start),
7226 pa_end - pa_start, mode);
7229 /* Start physical address run. */
7230 pa_start = *pte & PG_FRAME;
7231 pa_end = pa_start + PAGE_SIZE;
7237 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
7238 pa_end1 = MIN(pa_end, dmaplimit);
7239 if (pa_start != pa_end1)
7240 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
7241 pa_end1 - pa_start, mode);
7245 * Flush CPU caches if required to make sure any data isn't cached that
7246 * shouldn't be, etc.
7249 pmap_invalidate_range(kernel_pmap, base, tmpva);
7250 pmap_invalidate_cache_range(base, tmpva, FALSE);
7256 * Demotes any mapping within the direct map region that covers more than the
7257 * specified range of physical addresses. This range's size must be a power
7258 * of two and its starting address must be a multiple of its size. Since the
7259 * demotion does not change any attributes of the mapping, a TLB invalidation
7260 * is not mandatory. The caller may, however, request a TLB invalidation.
7263 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
7272 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
7273 KASSERT((base & (len - 1)) == 0,
7274 ("pmap_demote_DMAP: base is not a multiple of len"));
7275 if (len < NBPDP && base < dmaplimit) {
7276 va = PHYS_TO_DMAP(base);
7278 PMAP_LOCK(kernel_pmap);
7279 pdpe = pmap_pdpe(kernel_pmap, va);
7280 if ((*pdpe & X86_PG_V) == 0)
7281 panic("pmap_demote_DMAP: invalid PDPE");
7282 if ((*pdpe & PG_PS) != 0) {
7283 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
7284 panic("pmap_demote_DMAP: PDPE failed");
7288 pde = pmap_pdpe_to_pde(pdpe, va);
7289 if ((*pde & X86_PG_V) == 0)
7290 panic("pmap_demote_DMAP: invalid PDE");
7291 if ((*pde & PG_PS) != 0) {
7292 if (!pmap_demote_pde(kernel_pmap, pde, va))
7293 panic("pmap_demote_DMAP: PDE failed");
7297 if (changed && invalidate)
7298 pmap_invalidate_page(kernel_pmap, va);
7299 PMAP_UNLOCK(kernel_pmap);
7304 * perform the pmap work for mincore
7307 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
7310 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
7314 PG_A = pmap_accessed_bit(pmap);
7315 PG_M = pmap_modified_bit(pmap);
7316 PG_V = pmap_valid_bit(pmap);
7317 PG_RW = pmap_rw_bit(pmap);
7321 pdep = pmap_pde(pmap, addr);
7322 if (pdep != NULL && (*pdep & PG_V)) {
7323 if (*pdep & PG_PS) {
7325 /* Compute the physical address of the 4KB page. */
7326 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
7328 val = MINCORE_SUPER;
7330 pte = *pmap_pde_to_pte(pdep, addr);
7331 pa = pte & PG_FRAME;
7339 if ((pte & PG_V) != 0) {
7340 val |= MINCORE_INCORE;
7341 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7342 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
7343 if ((pte & PG_A) != 0)
7344 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
7346 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
7347 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
7348 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
7349 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
7350 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
7353 PA_UNLOCK_COND(*locked_pa);
7359 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
7361 uint32_t gen, new_gen, pcid_next;
7363 CRITICAL_ASSERT(curthread);
7364 gen = PCPU_GET(pcid_gen);
7365 if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN)
7366 return (pti ? 0 : CR3_PCID_SAVE);
7367 if (pmap->pm_pcids[cpuid].pm_gen == gen)
7368 return (CR3_PCID_SAVE);
7369 pcid_next = PCPU_GET(pcid_next);
7370 KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
7371 (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
7372 ("cpu %d pcid_next %#x", cpuid, pcid_next));
7373 if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
7374 (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
7378 PCPU_SET(pcid_gen, new_gen);
7379 pcid_next = PMAP_PCID_KERN + 1;
7383 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
7384 pmap->pm_pcids[cpuid].pm_gen = new_gen;
7385 PCPU_SET(pcid_next, pcid_next + 1);
7390 pmap_activate_sw(struct thread *td)
7392 pmap_t oldpmap, pmap;
7393 struct invpcid_descr d;
7394 uint64_t cached, cr3, kcr3, kern_pti_cached, rsp0, ucr3;
7397 struct amd64tss *tssp;
7399 oldpmap = PCPU_GET(curpmap);
7400 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7401 if (oldpmap == pmap)
7403 cpuid = PCPU_GET(cpuid);
7405 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7407 CPU_SET(cpuid, &pmap->pm_active);
7410 if (pmap_pcid_enabled) {
7411 cached = pmap_pcid_alloc(pmap, cpuid);
7412 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
7413 pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
7414 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
7415 pmap->pm_pcids[cpuid].pm_pcid));
7416 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
7417 pmap == kernel_pmap,
7418 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
7419 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
7422 * If the INVPCID instruction is not available,
7423 * invltlb_pcid_handler() is used for handle
7424 * invalidate_all IPI, which checks for curpmap ==
7425 * smp_tlb_pmap. Below operations sequence has a
7426 * window where %CR3 is loaded with the new pmap's
7427 * PML4 address, but curpmap value is not yet updated.
7428 * This causes invltlb IPI handler, called between the
7429 * updates, to execute as NOP, which leaves stale TLB
7432 * Note that the most typical use of
7433 * pmap_activate_sw(), from the context switch, is
7434 * immune to this race, because interrupts are
7435 * disabled (while the thread lock is owned), and IPI
7436 * happens after curpmap is updated. Protect other
7437 * callers in a similar way, by disabling interrupts
7438 * around the %cr3 register reload and curpmap
7442 rflags = intr_disable();
7444 kern_pti_cached = pti ? 0 : cached;
7445 if (!kern_pti_cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
7446 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
7449 PCPU_SET(curpmap, pmap);
7451 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid;
7452 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[cpuid].pm_pcid |
7455 if (!cached && pmap->pm_ucr3 != PMAP_NO_CR3) {
7457 * Manually invalidate translations cached
7458 * from the user page table. They are not
7459 * flushed by reload of cr3 with the kernel
7460 * page table pointer above.
7462 if (invpcid_works) {
7463 d.pcid = PMAP_PCID_USER_PT |
7464 pmap->pm_pcids[cpuid].pm_pcid;
7467 invpcid(&d, INVPCID_CTX);
7469 pmap_pti_pcid_invalidate(ucr3, kcr3);
7473 PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
7474 PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
7477 intr_restore(rflags);
7479 PCPU_INC(pm_save_cnt);
7481 load_cr3(pmap->pm_cr3);
7482 PCPU_SET(curpmap, pmap);
7484 PCPU_SET(kcr3, pmap->pm_cr3);
7485 PCPU_SET(ucr3, pmap->pm_ucr3);
7488 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
7489 rsp0 = ((vm_offset_t)PCPU_PTR(pti_stack) +
7490 PC_PTI_STACK_SZ * sizeof(uint64_t)) & ~0xful;
7491 tssp = PCPU_GET(tssp);
7492 tssp->tss_rsp0 = rsp0;
7495 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
7497 CPU_CLR(cpuid, &oldpmap->pm_active);
7502 pmap_activate(struct thread *td)
7506 pmap_activate_sw(td);
7511 pmap_activate_boot(pmap_t pmap)
7517 * kernel_pmap must be never deactivated, and we ensure that
7518 * by never activating it at all.
7520 MPASS(pmap != kernel_pmap);
7522 cpuid = PCPU_GET(cpuid);
7524 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7526 CPU_SET(cpuid, &pmap->pm_active);
7528 PCPU_SET(curpmap, pmap);
7530 kcr3 = pmap->pm_cr3;
7531 if (pmap_pcid_enabled)
7532 kcr3 |= pmap->pm_pcids[cpuid].pm_pcid | CR3_PCID_SAVE;
7536 PCPU_SET(kcr3, kcr3);
7537 PCPU_SET(ucr3, PMAP_NO_CR3);
7541 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
7546 * Increase the starting virtual address of the given mapping if a
7547 * different alignment might result in more superpage mappings.
7550 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7551 vm_offset_t *addr, vm_size_t size)
7553 vm_offset_t superpage_offset;
7557 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7558 offset += ptoa(object->pg_color);
7559 superpage_offset = offset & PDRMASK;
7560 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
7561 (*addr & PDRMASK) == superpage_offset)
7563 if ((*addr & PDRMASK) < superpage_offset)
7564 *addr = (*addr & ~PDRMASK) + superpage_offset;
7566 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
7570 static unsigned long num_dirty_emulations;
7571 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
7572 &num_dirty_emulations, 0, NULL);
7574 static unsigned long num_accessed_emulations;
7575 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
7576 &num_accessed_emulations, 0, NULL);
7578 static unsigned long num_superpage_accessed_emulations;
7579 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7580 &num_superpage_accessed_emulations, 0, NULL);
7582 static unsigned long ad_emulation_superpage_promotions;
7583 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7584 &ad_emulation_superpage_promotions, 0, NULL);
7585 #endif /* INVARIANTS */
7588 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7591 struct rwlock *lock;
7592 #if VM_NRESERVLEVEL > 0
7596 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7598 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7599 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7601 if (!pmap_emulate_ad_bits(pmap))
7604 PG_A = pmap_accessed_bit(pmap);
7605 PG_M = pmap_modified_bit(pmap);
7606 PG_V = pmap_valid_bit(pmap);
7607 PG_RW = pmap_rw_bit(pmap);
7613 pde = pmap_pde(pmap, va);
7614 if (pde == NULL || (*pde & PG_V) == 0)
7617 if ((*pde & PG_PS) != 0) {
7618 if (ftype == VM_PROT_READ) {
7620 atomic_add_long(&num_superpage_accessed_emulations, 1);
7628 pte = pmap_pde_to_pte(pde, va);
7629 if ((*pte & PG_V) == 0)
7632 if (ftype == VM_PROT_WRITE) {
7633 if ((*pte & PG_RW) == 0)
7636 * Set the modified and accessed bits simultaneously.
7638 * Intel EPT PTEs that do software emulation of A/D bits map
7639 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7640 * An EPT misconfiguration is triggered if the PTE is writable
7641 * but not readable (WR=10). This is avoided by setting PG_A
7642 * and PG_M simultaneously.
7644 *pte |= PG_M | PG_A;
7649 #if VM_NRESERVLEVEL > 0
7650 /* try to promote the mapping */
7651 if (va < VM_MAXUSER_ADDRESS)
7652 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7656 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7658 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7659 pmap_ps_enabled(pmap) &&
7660 (m->flags & PG_FICTITIOUS) == 0 &&
7661 vm_reserv_level_iffullpop(m) == 0) {
7662 pmap_promote_pde(pmap, pde, va, &lock);
7664 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7670 if (ftype == VM_PROT_WRITE)
7671 atomic_add_long(&num_dirty_emulations, 1);
7673 atomic_add_long(&num_accessed_emulations, 1);
7675 rv = 0; /* success */
7684 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7689 pt_entry_t *pte, PG_V;
7693 PG_V = pmap_valid_bit(pmap);
7696 pml4 = pmap_pml4e(pmap, va);
7698 if ((*pml4 & PG_V) == 0)
7701 pdp = pmap_pml4e_to_pdpe(pml4, va);
7703 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7706 pde = pmap_pdpe_to_pde(pdp, va);
7708 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7711 pte = pmap_pde_to_pte(pde, va);
7720 * Get the kernel virtual address of a set of physical pages. If there are
7721 * physical addresses not covered by the DMAP perform a transient mapping
7722 * that will be removed when calling pmap_unmap_io_transient.
7724 * \param page The pages the caller wishes to obtain the virtual
7725 * address on the kernel memory map.
7726 * \param vaddr On return contains the kernel virtual memory address
7727 * of the pages passed in the page parameter.
7728 * \param count Number of pages passed in.
7729 * \param can_fault TRUE if the thread using the mapped pages can take
7730 * page faults, FALSE otherwise.
7732 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7733 * finished or FALSE otherwise.
7737 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7738 boolean_t can_fault)
7741 boolean_t needs_mapping;
7743 int cache_bits, error, i;
7746 * Allocate any KVA space that we need, this is done in a separate
7747 * loop to prevent calling vmem_alloc while pinned.
7749 needs_mapping = FALSE;
7750 for (i = 0; i < count; i++) {
7751 paddr = VM_PAGE_TO_PHYS(page[i]);
7752 if (__predict_false(paddr >= dmaplimit)) {
7753 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7754 M_BESTFIT | M_WAITOK, &vaddr[i]);
7755 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7756 needs_mapping = TRUE;
7758 vaddr[i] = PHYS_TO_DMAP(paddr);
7762 /* Exit early if everything is covered by the DMAP */
7767 * NB: The sequence of updating a page table followed by accesses
7768 * to the corresponding pages used in the !DMAP case is subject to
7769 * the situation described in the "AMD64 Architecture Programmer's
7770 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7771 * Coherency Considerations". Therefore, issuing the INVLPG right
7772 * after modifying the PTE bits is crucial.
7776 for (i = 0; i < count; i++) {
7777 paddr = VM_PAGE_TO_PHYS(page[i]);
7778 if (paddr >= dmaplimit) {
7781 * Slow path, since we can get page faults
7782 * while mappings are active don't pin the
7783 * thread to the CPU and instead add a global
7784 * mapping visible to all CPUs.
7786 pmap_qenter(vaddr[i], &page[i], 1);
7788 pte = vtopte(vaddr[i]);
7789 cache_bits = pmap_cache_bits(kernel_pmap,
7790 page[i]->md.pat_mode, 0);
7791 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7798 return (needs_mapping);
7802 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7803 boolean_t can_fault)
7810 for (i = 0; i < count; i++) {
7811 paddr = VM_PAGE_TO_PHYS(page[i]);
7812 if (paddr >= dmaplimit) {
7814 pmap_qremove(vaddr[i], 1);
7815 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7821 pmap_quick_enter_page(vm_page_t m)
7825 paddr = VM_PAGE_TO_PHYS(m);
7826 if (paddr < dmaplimit)
7827 return (PHYS_TO_DMAP(paddr));
7828 mtx_lock_spin(&qframe_mtx);
7829 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7830 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7831 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7836 pmap_quick_remove_page(vm_offset_t addr)
7841 pte_store(vtopte(qframe), 0);
7843 mtx_unlock_spin(&qframe_mtx);
7847 pmap_pti_alloc_page(void)
7851 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7852 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_NOBUSY |
7853 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
7858 pmap_pti_free_page(vm_page_t m)
7861 KASSERT(m->wire_count > 0, ("page %p not wired", m));
7863 if (m->wire_count != 0)
7865 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
7866 vm_page_free_zero(m);
7880 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
7881 VM_OBJECT_WLOCK(pti_obj);
7882 pml4_pg = pmap_pti_alloc_page();
7883 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
7884 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
7885 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
7886 pdpe = pmap_pti_pdpe(va);
7887 pmap_pti_wire_pte(pdpe);
7889 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
7890 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
7891 pmap_pti_add_kva_locked((vm_offset_t)gdt, (vm_offset_t)gdt +
7892 sizeof(struct user_segment_descriptor) * NGDT * MAXCPU, false);
7893 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
7894 sizeof(struct gate_descriptor) * NIDT, false);
7895 pmap_pti_add_kva_locked((vm_offset_t)common_tss,
7896 (vm_offset_t)common_tss + sizeof(struct amd64tss) * MAXCPU, false);
7898 /* Doublefault stack IST 1 */
7899 va = common_tss[i].tss_ist1;
7900 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7901 /* NMI stack IST 2 */
7902 va = common_tss[i].tss_ist2 + sizeof(struct nmi_pcpu);
7903 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7904 /* MC# stack IST 3 */
7905 va = common_tss[i].tss_ist3 + sizeof(struct nmi_pcpu);
7906 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7907 /* DB# stack IST 4 */
7908 va = common_tss[i].tss_ist4 + sizeof(struct nmi_pcpu);
7909 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7911 pmap_pti_add_kva_locked((vm_offset_t)kernphys + KERNBASE,
7912 (vm_offset_t)etext, true);
7913 pti_finalized = true;
7914 VM_OBJECT_WUNLOCK(pti_obj);
7916 SYSINIT(pmap_pti, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_pti_init, NULL);
7918 static pdp_entry_t *
7919 pmap_pti_pdpe(vm_offset_t va)
7921 pml4_entry_t *pml4e;
7924 vm_pindex_t pml4_idx;
7927 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7929 pml4_idx = pmap_pml4e_index(va);
7930 pml4e = &pti_pml4[pml4_idx];
7934 panic("pml4 alloc after finalization\n");
7935 m = pmap_pti_alloc_page();
7937 pmap_pti_free_page(m);
7938 mphys = *pml4e & ~PAGE_MASK;
7940 mphys = VM_PAGE_TO_PHYS(m);
7941 *pml4e = mphys | X86_PG_RW | X86_PG_V;
7944 mphys = *pml4e & ~PAGE_MASK;
7946 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
7951 pmap_pti_wire_pte(void *pte)
7955 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7956 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7961 pmap_pti_unwire_pde(void *pde, bool only_ref)
7965 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7966 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
7967 MPASS(m->wire_count > 0);
7968 MPASS(only_ref || m->wire_count > 1);
7969 pmap_pti_free_page(m);
7973 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
7978 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7979 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7980 MPASS(m->wire_count > 0);
7981 if (pmap_pti_free_page(m)) {
7982 pde = pmap_pti_pde(va);
7983 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
7985 pmap_pti_unwire_pde(pde, false);
7990 pmap_pti_pde(vm_offset_t va)
7998 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8000 pdpe = pmap_pti_pdpe(va);
8002 m = pmap_pti_alloc_page();
8004 pmap_pti_free_page(m);
8005 MPASS((*pdpe & X86_PG_PS) == 0);
8006 mphys = *pdpe & ~PAGE_MASK;
8008 mphys = VM_PAGE_TO_PHYS(m);
8009 *pdpe = mphys | X86_PG_RW | X86_PG_V;
8012 MPASS((*pdpe & X86_PG_PS) == 0);
8013 mphys = *pdpe & ~PAGE_MASK;
8016 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
8017 pd_idx = pmap_pde_index(va);
8023 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
8030 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8032 pde = pmap_pti_pde(va);
8033 if (unwire_pde != NULL) {
8035 pmap_pti_wire_pte(pde);
8038 m = pmap_pti_alloc_page();
8040 pmap_pti_free_page(m);
8041 MPASS((*pde & X86_PG_PS) == 0);
8042 mphys = *pde & ~(PAGE_MASK | pg_nx);
8044 mphys = VM_PAGE_TO_PHYS(m);
8045 *pde = mphys | X86_PG_RW | X86_PG_V;
8046 if (unwire_pde != NULL)
8047 *unwire_pde = false;
8050 MPASS((*pde & X86_PG_PS) == 0);
8051 mphys = *pde & ~(PAGE_MASK | pg_nx);
8054 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
8055 pte += pmap_pte_index(va);
8061 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
8065 pt_entry_t *pte, ptev;
8068 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8070 sva = trunc_page(sva);
8071 MPASS(sva > VM_MAXUSER_ADDRESS);
8072 eva = round_page(eva);
8074 for (; sva < eva; sva += PAGE_SIZE) {
8075 pte = pmap_pti_pte(sva, &unwire_pde);
8076 pa = pmap_kextract(sva);
8077 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A | X86_PG_G |
8078 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
8079 VM_MEMATTR_DEFAULT, FALSE);
8081 pte_store(pte, ptev);
8082 pmap_pti_wire_pte(pte);
8084 KASSERT(!pti_finalized,
8085 ("pti overlap after fin %#lx %#lx %#lx",
8087 KASSERT(*pte == ptev,
8088 ("pti non-identical pte after fin %#lx %#lx %#lx",
8092 pde = pmap_pti_pde(sva);
8093 pmap_pti_unwire_pde(pde, true);
8099 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
8104 VM_OBJECT_WLOCK(pti_obj);
8105 pmap_pti_add_kva_locked(sva, eva, exec);
8106 VM_OBJECT_WUNLOCK(pti_obj);
8110 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
8117 sva = rounddown2(sva, PAGE_SIZE);
8118 MPASS(sva > VM_MAXUSER_ADDRESS);
8119 eva = roundup2(eva, PAGE_SIZE);
8121 VM_OBJECT_WLOCK(pti_obj);
8122 for (va = sva; va < eva; va += PAGE_SIZE) {
8123 pte = pmap_pti_pte(va, NULL);
8124 KASSERT((*pte & X86_PG_V) != 0,
8125 ("invalid pte va %#lx pte %#lx pt %#lx", va,
8126 (u_long)pte, *pte));
8128 pmap_pti_unwire_pte(pte, va);
8130 pmap_invalidate_range(kernel_pmap, sva, eva);
8131 VM_OBJECT_WUNLOCK(pti_obj);
8134 #include "opt_ddb.h"
8136 #include <ddb/ddb.h>
8138 DB_SHOW_COMMAND(pte, pmap_print_pte)
8144 pt_entry_t *pte, PG_V;
8148 va = (vm_offset_t)addr;
8149 pmap = PCPU_GET(curpmap); /* XXX */
8151 db_printf("show pte addr\n");
8154 PG_V = pmap_valid_bit(pmap);
8155 pml4 = pmap_pml4e(pmap, va);
8156 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
8157 if ((*pml4 & PG_V) == 0) {
8161 pdp = pmap_pml4e_to_pdpe(pml4, va);
8162 db_printf(" pdpe %#016lx", *pdp);
8163 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
8167 pde = pmap_pdpe_to_pde(pdp, va);
8168 db_printf(" pde %#016lx", *pde);
8169 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
8173 pte = pmap_pde_to_pte(pde, va);
8174 db_printf(" pte %#016lx\n", *pte);
8177 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
8182 a = (vm_paddr_t)addr;
8183 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
8185 db_printf("show phys2dmap addr\n");