2 * SPDX-License-Identifier: BSD-4-Clause
4 * Copyright (c) 1991 Regents of the University of California.
6 * Copyright (c) 1994 John S. Dyson
8 * Copyright (c) 1994 David Greenman
10 * Copyright (c) 2003 Peter Wemm
11 * All rights reserved.
12 * Copyright (c) 2005-2010 Alan L. Cox <alc@cs.rice.edu>
13 * All rights reserved.
15 * This code is derived from software contributed to Berkeley by
16 * the Systems Programming Group of the University of Utah Computer
17 * Science Department and William Jolitz of UUNET Technologies Inc.
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
22 * 1. Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
24 * 2. Redistributions in binary form must reproduce the above copyright
25 * notice, this list of conditions and the following disclaimer in the
26 * documentation and/or other materials provided with the distribution.
27 * 3. All advertising materials mentioning features or use of this software
28 * must display the following acknowledgement:
29 * This product includes software developed by the University of
30 * California, Berkeley and its contributors.
31 * 4. Neither the name of the University nor the names of its contributors
32 * may be used to endorse or promote products derived from this software
33 * without specific prior written permission.
35 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
36 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
39 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
40 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
41 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
42 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
43 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
44 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * from: @(#)pmap.c 7.7 (Berkeley) 5/12/91
50 * Copyright (c) 2003 Networks Associates Technology, Inc.
51 * Copyright (c) 2014-2018 The FreeBSD Foundation
52 * All rights reserved.
54 * This software was developed for the FreeBSD Project by Jake Burkholder,
55 * Safeport Network Services, and Network Associates Laboratories, the
56 * Security Research Division of Network Associates, Inc. under
57 * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
58 * CHATS research program.
60 * Portions of this software were developed by
61 * Konstantin Belousov <kib@FreeBSD.org> under sponsorship from
62 * the FreeBSD Foundation.
64 * Redistribution and use in source and binary forms, with or without
65 * modification, are permitted provided that the following conditions
67 * 1. Redistributions of source code must retain the above copyright
68 * notice, this list of conditions and the following disclaimer.
69 * 2. Redistributions in binary form must reproduce the above copyright
70 * notice, this list of conditions and the following disclaimer in the
71 * documentation and/or other materials provided with the distribution.
73 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
74 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
75 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
76 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
77 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
78 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
79 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
80 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
81 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
82 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
86 #define AMD64_NPT_AWARE
88 #include <sys/cdefs.h>
89 __FBSDID("$FreeBSD$");
92 * Manages physical address maps.
94 * Since the information managed by this module is
95 * also stored by the logical address mapping module,
96 * this module may throw away valid virtual-to-physical
97 * mappings at almost any time. However, invalidations
98 * of virtual-to-physical mappings must be done as
101 * In order to cope with hardware architectures which
102 * make virtual-to-physical map invalidates expensive,
103 * this module may delay invalidate or reduced protection
104 * operations until such time as they are actually
105 * necessary. This module is given full information as
106 * to which processors are currently using which maps,
107 * and to when physical maps must be made correct.
110 #include "opt_pmap.h"
113 #include <sys/param.h>
114 #include <sys/bitstring.h>
116 #include <sys/systm.h>
117 #include <sys/kernel.h>
119 #include <sys/lock.h>
120 #include <sys/malloc.h>
121 #include <sys/mman.h>
122 #include <sys/mutex.h>
123 #include <sys/proc.h>
124 #include <sys/rwlock.h>
126 #include <sys/turnstile.h>
127 #include <sys/vmem.h>
128 #include <sys/vmmeter.h>
129 #include <sys/sched.h>
130 #include <sys/sysctl.h>
134 #include <vm/vm_param.h>
135 #include <vm/vm_kern.h>
136 #include <vm/vm_page.h>
137 #include <vm/vm_map.h>
138 #include <vm/vm_object.h>
139 #include <vm/vm_extern.h>
140 #include <vm/vm_pageout.h>
141 #include <vm/vm_pager.h>
142 #include <vm/vm_phys.h>
143 #include <vm/vm_radix.h>
144 #include <vm/vm_reserv.h>
147 #include <machine/intr_machdep.h>
148 #include <x86/apicvar.h>
149 #include <machine/cpu.h>
150 #include <machine/cputypes.h>
151 #include <machine/md_var.h>
152 #include <machine/pcb.h>
153 #include <machine/specialreg.h>
155 #include <machine/smp.h>
157 #include <machine/tss.h>
159 static __inline boolean_t
160 pmap_type_guest(pmap_t pmap)
163 return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
166 static __inline boolean_t
167 pmap_emulate_ad_bits(pmap_t pmap)
170 return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
173 static __inline pt_entry_t
174 pmap_valid_bit(pmap_t pmap)
178 switch (pmap->pm_type) {
184 if (pmap_emulate_ad_bits(pmap))
185 mask = EPT_PG_EMUL_V;
190 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
196 static __inline pt_entry_t
197 pmap_rw_bit(pmap_t pmap)
201 switch (pmap->pm_type) {
207 if (pmap_emulate_ad_bits(pmap))
208 mask = EPT_PG_EMUL_RW;
213 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
219 static pt_entry_t pg_g;
221 static __inline pt_entry_t
222 pmap_global_bit(pmap_t pmap)
226 switch (pmap->pm_type) {
235 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
241 static __inline pt_entry_t
242 pmap_accessed_bit(pmap_t pmap)
246 switch (pmap->pm_type) {
252 if (pmap_emulate_ad_bits(pmap))
258 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
264 static __inline pt_entry_t
265 pmap_modified_bit(pmap_t pmap)
269 switch (pmap->pm_type) {
275 if (pmap_emulate_ad_bits(pmap))
281 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
287 #if !defined(DIAGNOSTIC)
288 #ifdef __GNUC_GNU_INLINE__
289 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
291 #define PMAP_INLINE extern inline
298 #define PV_STAT(x) do { x ; } while (0)
300 #define PV_STAT(x) do { } while (0)
303 #define pa_index(pa) ((pa) >> PDRSHIFT)
304 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
306 #define NPV_LIST_LOCKS MAXCPU
308 #define PHYS_TO_PV_LIST_LOCK(pa) \
309 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
311 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
312 struct rwlock **_lockp = (lockp); \
313 struct rwlock *_new_lock; \
315 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
316 if (_new_lock != *_lockp) { \
317 if (*_lockp != NULL) \
318 rw_wunlock(*_lockp); \
319 *_lockp = _new_lock; \
324 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
325 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
327 #define RELEASE_PV_LIST_LOCK(lockp) do { \
328 struct rwlock **_lockp = (lockp); \
330 if (*_lockp != NULL) { \
331 rw_wunlock(*_lockp); \
336 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
337 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
339 struct pmap kernel_pmap_store;
341 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
342 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
345 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
346 "Number of kernel page table pages allocated on bootup");
349 vm_paddr_t dmaplimit;
350 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
353 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
355 static int pat_works = 1;
356 SYSCTL_INT(_vm_pmap, OID_AUTO, pat_works, CTLFLAG_RD, &pat_works, 1,
357 "Is page attribute table fully functional?");
359 static int pg_ps_enabled = 1;
360 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
361 &pg_ps_enabled, 0, "Are large page mappings enabled?");
363 #define PAT_INDEX_SIZE 8
364 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
366 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
367 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
368 u_int64_t KPDPphys; /* phys addr of kernel level 3 */
369 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
371 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
372 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
373 static int ndmpdpphys; /* number of DMPDPphys pages */
376 * pmap_mapdev support pre initialization (i.e. console)
378 #define PMAP_PREINIT_MAPPING_COUNT 8
379 static struct pmap_preinit_mapping {
384 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
385 static int pmap_initialized;
388 * Data for the pv entry allocation mechanism.
389 * Updates to pv_invl_gen are protected by the pv_list_locks[]
390 * elements, but reads are not.
392 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
393 static struct mtx __exclusive_cache_line pv_chunks_mutex;
394 static struct rwlock __exclusive_cache_line pv_list_locks[NPV_LIST_LOCKS];
395 static u_long pv_invl_gen[NPV_LIST_LOCKS];
396 static struct md_page *pv_table;
397 static struct md_page pv_dummy;
400 * All those kernel PT submaps that BSD is so fond of
402 pt_entry_t *CMAP1 = NULL;
404 static vm_offset_t qframe = 0;
405 static struct mtx qframe_mtx;
407 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
409 int pmap_pcid_enabled = 1;
410 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
411 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
412 int invpcid_works = 0;
413 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
414 "Is the invpcid instruction available ?");
416 int __read_frequently pti = 0;
417 SYSCTL_INT(_vm_pmap, OID_AUTO, pti, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
419 "Page Table Isolation enabled");
420 static vm_object_t pti_obj;
421 static pml4_entry_t *pti_pml4;
422 static vm_pindex_t pti_pg_idx;
423 static bool pti_finalized;
426 pmap_pcid_save_cnt_proc(SYSCTL_HANDLER_ARGS)
433 res += cpuid_to_pcpu[i]->pc_pm_save_cnt;
435 return (sysctl_handle_64(oidp, &res, 0, req));
437 SYSCTL_PROC(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLTYPE_U64 | CTLFLAG_RW |
438 CTLFLAG_MPSAFE, NULL, 0, pmap_pcid_save_cnt_proc, "QU",
439 "Count of saved TLB context on switch");
441 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
442 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
443 static struct mtx invl_gen_mtx;
444 static u_long pmap_invl_gen = 0;
445 /* Fake lock object to satisfy turnstiles interface. */
446 static struct lock_object invl_gen_ts = {
454 return (curthread->td_md.md_invl_gen.gen == 0);
457 #define PMAP_ASSERT_NOT_IN_DI() \
458 KASSERT(pmap_not_in_di(), ("DI already started"))
461 * Start a new Delayed Invalidation (DI) block of code, executed by
462 * the current thread. Within a DI block, the current thread may
463 * destroy both the page table and PV list entries for a mapping and
464 * then release the corresponding PV list lock before ensuring that
465 * the mapping is flushed from the TLBs of any processors with the
469 pmap_delayed_invl_started(void)
471 struct pmap_invl_gen *invl_gen;
474 invl_gen = &curthread->td_md.md_invl_gen;
475 PMAP_ASSERT_NOT_IN_DI();
476 mtx_lock(&invl_gen_mtx);
477 if (LIST_EMPTY(&pmap_invl_gen_tracker))
478 currgen = pmap_invl_gen;
480 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
481 invl_gen->gen = currgen + 1;
482 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
483 mtx_unlock(&invl_gen_mtx);
487 * Finish the DI block, previously started by the current thread. All
488 * required TLB flushes for the pages marked by
489 * pmap_delayed_invl_page() must be finished before this function is
492 * This function works by bumping the global DI generation number to
493 * the generation number of the current thread's DI, unless there is a
494 * pending DI that started earlier. In the latter case, bumping the
495 * global DI generation number would incorrectly signal that the
496 * earlier DI had finished. Instead, this function bumps the earlier
497 * DI's generation number to match the generation number of the
498 * current thread's DI.
501 pmap_delayed_invl_finished(void)
503 struct pmap_invl_gen *invl_gen, *next;
504 struct turnstile *ts;
506 invl_gen = &curthread->td_md.md_invl_gen;
507 KASSERT(invl_gen->gen != 0, ("missed invl_started"));
508 mtx_lock(&invl_gen_mtx);
509 next = LIST_NEXT(invl_gen, link);
511 turnstile_chain_lock(&invl_gen_ts);
512 ts = turnstile_lookup(&invl_gen_ts);
513 pmap_invl_gen = invl_gen->gen;
515 turnstile_broadcast(ts, TS_SHARED_QUEUE);
516 turnstile_unpend(ts);
518 turnstile_chain_unlock(&invl_gen_ts);
520 next->gen = invl_gen->gen;
522 LIST_REMOVE(invl_gen, link);
523 mtx_unlock(&invl_gen_mtx);
528 static long invl_wait;
529 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
530 "Number of times DI invalidation blocked pmap_remove_all/write");
534 pmap_delayed_invl_genp(vm_page_t m)
537 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
541 * Ensure that all currently executing DI blocks, that need to flush
542 * TLB for the given page m, actually flushed the TLB at the time the
543 * function returned. If the page m has an empty PV list and we call
544 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
545 * valid mapping for the page m in either its page table or TLB.
547 * This function works by blocking until the global DI generation
548 * number catches up with the generation number associated with the
549 * given page m and its PV list. Since this function's callers
550 * typically own an object lock and sometimes own a page lock, it
551 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
555 pmap_delayed_invl_wait(vm_page_t m)
557 struct turnstile *ts;
560 bool accounted = false;
563 m_gen = pmap_delayed_invl_genp(m);
564 while (*m_gen > pmap_invl_gen) {
567 atomic_add_long(&invl_wait, 1);
571 ts = turnstile_trywait(&invl_gen_ts);
572 if (*m_gen > pmap_invl_gen)
573 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
575 turnstile_cancel(ts);
580 * Mark the page m's PV list as participating in the current thread's
581 * DI block. Any threads concurrently using m's PV list to remove or
582 * restrict all mappings to m will wait for the current thread's DI
583 * block to complete before proceeding.
585 * The function works by setting the DI generation number for m's PV
586 * list to at least the DI generation number of the current thread.
587 * This forces a caller of pmap_delayed_invl_wait() to block until
588 * current thread calls pmap_delayed_invl_finished().
591 pmap_delayed_invl_page(vm_page_t m)
595 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
596 gen = curthread->td_md.md_invl_gen.gen;
599 m_gen = pmap_delayed_invl_genp(m);
607 static caddr_t crashdumpmap;
610 * Internal flags for pmap_enter()'s helper functions.
612 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
613 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
615 static void free_pv_chunk(struct pv_chunk *pc);
616 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
617 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
618 static int popcnt_pc_map_pq(uint64_t *map);
619 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
620 static void reserve_pv_entries(pmap_t pmap, int needed,
621 struct rwlock **lockp);
622 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
623 struct rwlock **lockp);
624 static bool pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
625 u_int flags, struct rwlock **lockp);
626 #if VM_NRESERVLEVEL > 0
627 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
628 struct rwlock **lockp);
630 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
631 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
634 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode);
635 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
636 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
637 vm_offset_t va, struct rwlock **lockp);
638 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
640 static bool pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
641 vm_prot_t prot, struct rwlock **lockp);
642 static int pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
643 u_int flags, vm_page_t m, struct rwlock **lockp);
644 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
645 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
646 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
647 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
648 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
650 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
651 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask);
652 #if VM_NRESERVLEVEL > 0
653 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
654 struct rwlock **lockp);
656 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
658 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
659 static void pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva,
661 static pdp_entry_t *pmap_pti_pdpe(vm_offset_t va);
662 static pd_entry_t *pmap_pti_pde(vm_offset_t va);
663 static void pmap_pti_wire_pte(void *pte);
664 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
665 struct spglist *free, struct rwlock **lockp);
666 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
667 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
668 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
669 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
670 struct spglist *free);
671 static bool pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
672 pd_entry_t *pde, struct spglist *free,
673 struct rwlock **lockp);
674 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
675 vm_page_t m, struct rwlock **lockp);
676 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
678 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
680 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
681 struct rwlock **lockp);
682 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
683 struct rwlock **lockp);
684 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
685 struct rwlock **lockp);
687 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
688 struct spglist *free);
689 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
691 /********************/
692 /* Inline functions */
693 /********************/
695 /* Return a non-clipped PD index for a given VA */
696 static __inline vm_pindex_t
697 pmap_pde_pindex(vm_offset_t va)
699 return (va >> PDRSHIFT);
703 /* Return a pointer to the PML4 slot that corresponds to a VA */
704 static __inline pml4_entry_t *
705 pmap_pml4e(pmap_t pmap, vm_offset_t va)
708 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
711 /* Return a pointer to the PDP slot that corresponds to a VA */
712 static __inline pdp_entry_t *
713 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
717 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
718 return (&pdpe[pmap_pdpe_index(va)]);
721 /* Return a pointer to the PDP slot that corresponds to a VA */
722 static __inline pdp_entry_t *
723 pmap_pdpe(pmap_t pmap, vm_offset_t va)
728 PG_V = pmap_valid_bit(pmap);
729 pml4e = pmap_pml4e(pmap, va);
730 if ((*pml4e & PG_V) == 0)
732 return (pmap_pml4e_to_pdpe(pml4e, va));
735 /* Return a pointer to the PD slot that corresponds to a VA */
736 static __inline pd_entry_t *
737 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
741 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
742 return (&pde[pmap_pde_index(va)]);
745 /* Return a pointer to the PD slot that corresponds to a VA */
746 static __inline pd_entry_t *
747 pmap_pde(pmap_t pmap, vm_offset_t va)
752 PG_V = pmap_valid_bit(pmap);
753 pdpe = pmap_pdpe(pmap, va);
754 if (pdpe == NULL || (*pdpe & PG_V) == 0)
756 return (pmap_pdpe_to_pde(pdpe, va));
759 /* Return a pointer to the PT slot that corresponds to a VA */
760 static __inline pt_entry_t *
761 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
765 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
766 return (&pte[pmap_pte_index(va)]);
769 /* Return a pointer to the PT slot that corresponds to a VA */
770 static __inline pt_entry_t *
771 pmap_pte(pmap_t pmap, vm_offset_t va)
776 PG_V = pmap_valid_bit(pmap);
777 pde = pmap_pde(pmap, va);
778 if (pde == NULL || (*pde & PG_V) == 0)
780 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
781 return ((pt_entry_t *)pde);
782 return (pmap_pde_to_pte(pde, va));
786 pmap_resident_count_inc(pmap_t pmap, int count)
789 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
790 pmap->pm_stats.resident_count += count;
794 pmap_resident_count_dec(pmap_t pmap, int count)
797 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
798 KASSERT(pmap->pm_stats.resident_count >= count,
799 ("pmap %p resident count underflow %ld %d", pmap,
800 pmap->pm_stats.resident_count, count));
801 pmap->pm_stats.resident_count -= count;
804 PMAP_INLINE pt_entry_t *
805 vtopte(vm_offset_t va)
807 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
809 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
811 return (PTmap + ((va >> PAGE_SHIFT) & mask));
814 static __inline pd_entry_t *
815 vtopde(vm_offset_t va)
817 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
819 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
821 return (PDmap + ((va >> PDRSHIFT) & mask));
825 allocpages(vm_paddr_t *firstaddr, int n)
830 bzero((void *)ret, n * PAGE_SIZE);
831 *firstaddr += n * PAGE_SIZE;
835 CTASSERT(powerof2(NDMPML4E));
837 /* number of kernel PDP slots */
838 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
841 nkpt_init(vm_paddr_t addr)
848 pt_pages = howmany(addr, 1 << PDRSHIFT);
849 pt_pages += NKPDPE(pt_pages);
852 * Add some slop beyond the bare minimum required for bootstrapping
855 * This is quite important when allocating KVA for kernel modules.
856 * The modules are required to be linked in the negative 2GB of
857 * the address space. If we run out of KVA in this region then
858 * pmap_growkernel() will need to allocate page table pages to map
859 * the entire 512GB of KVA space which is an unnecessary tax on
862 * Secondly, device memory mapped as part of setting up the low-
863 * level console(s) is taken from KVA, starting at virtual_avail.
864 * This is because cninit() is called after pmap_bootstrap() but
865 * before vm_init() and pmap_init(). 20MB for a frame buffer is
868 pt_pages += 32; /* 64MB additional slop. */
874 * Returns the proper write/execute permission for a physical page that is
875 * part of the initial boot allocations.
877 * If the page has kernel text, it is marked as read-only. If the page has
878 * kernel read-only data, it is marked as read-only/not-executable. If the
879 * page has only read-write data, it is marked as read-write/not-executable.
880 * If the page is below/above the kernel range, it is marked as read-write.
882 * This function operates on 2M pages, since we map the kernel space that
885 * Note that this doesn't currently provide any protection for modules.
887 static inline pt_entry_t
888 bootaddr_rwx(vm_paddr_t pa)
892 * Everything in the same 2M page as the start of the kernel
893 * should be static. On the other hand, things in the same 2M
894 * page as the end of the kernel could be read-write/executable,
895 * as the kernel image is not guaranteed to end on a 2M boundary.
897 if (pa < trunc_2mpage(btext - KERNBASE) ||
898 pa >= trunc_2mpage(_end - KERNBASE))
901 * The linker should ensure that the read-only and read-write
902 * portions don't share the same 2M page, so this shouldn't
903 * impact read-only data. However, in any case, any page with
904 * read-write data needs to be read-write.
906 if (pa >= trunc_2mpage(brwsection - KERNBASE))
907 return (X86_PG_RW | pg_nx);
909 * Mark any 2M page containing kernel text as read-only. Mark
910 * other pages with read-only data as read-only and not executable.
911 * (It is likely a small portion of the read-only data section will
912 * be marked as read-only, but executable. This should be acceptable
913 * since the read-only protection will keep the data from changing.)
914 * Note that fixups to the .text section will still work until we
917 if (pa < round_2mpage(etext - KERNBASE))
923 create_pagetables(vm_paddr_t *firstaddr)
925 int i, j, ndm1g, nkpdpe, nkdmpde;
930 uint64_t DMPDkernphys;
932 /* Allocate page table pages for the direct map */
933 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
934 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
936 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
937 if (ndmpdpphys > NDMPML4E) {
939 * Each NDMPML4E allows 512 GB, so limit to that,
940 * and then readjust ndmpdp and ndmpdpphys.
942 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
943 Maxmem = atop(NDMPML4E * NBPML4);
944 ndmpdpphys = NDMPML4E;
945 ndmpdp = NDMPML4E * NPDEPG;
947 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
949 if ((amd_feature & AMDID_PAGE1GB) != 0) {
951 * Calculate the number of 1G pages that will fully fit in
954 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
957 * Allocate 2M pages for the kernel. These will be used in
958 * place of the first one or more 1G pages from ndm1g.
960 nkdmpde = howmany((vm_offset_t)(brwsection - KERNBASE), NBPDP);
961 DMPDkernphys = allocpages(firstaddr, nkdmpde);
964 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
965 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
968 KPML4phys = allocpages(firstaddr, 1);
969 KPDPphys = allocpages(firstaddr, NKPML4E);
972 * Allocate the initial number of kernel page table pages required to
973 * bootstrap. We defer this until after all memory-size dependent
974 * allocations are done (e.g. direct map), so that we don't have to
975 * build in too much slop in our estimate.
977 * Note that when NKPML4E > 1, we have an empty page underneath
978 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
979 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
981 nkpt_init(*firstaddr);
982 nkpdpe = NKPDPE(nkpt);
984 KPTphys = allocpages(firstaddr, nkpt);
985 KPDphys = allocpages(firstaddr, nkpdpe);
987 /* Fill in the underlying page table pages */
988 /* XXX not fully used, underneath 2M pages */
989 pt_p = (pt_entry_t *)KPTphys;
990 for (i = 0; ptoa(i) < *firstaddr; i++)
991 pt_p[i] = ptoa(i) | X86_PG_V | pg_g | bootaddr_rwx(ptoa(i));
993 /* Now map the page tables at their location within PTmap */
994 pd_p = (pd_entry_t *)KPDphys;
995 for (i = 0; i < nkpt; i++)
996 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
998 /* Map from zero to end of allocations under 2M pages */
999 /* This replaces some of the KPTphys entries above */
1000 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
1001 pd_p[i] = (i << PDRSHIFT) | X86_PG_V | PG_PS | pg_g |
1002 bootaddr_rwx(i << PDRSHIFT);
1005 * Because we map the physical blocks in 2M pages, adjust firstaddr
1006 * to record the physical blocks we've actually mapped into kernel
1007 * virtual address space.
1009 *firstaddr = round_2mpage(*firstaddr);
1011 /* And connect up the PD to the PDP (leaving room for L4 pages) */
1012 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
1013 for (i = 0; i < nkpdpe; i++)
1014 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
1017 * Now, set up the direct map region using 2MB and/or 1GB pages. If
1018 * the end of physical memory is not aligned to a 1GB page boundary,
1019 * then the residual physical memory is mapped with 2MB pages. Later,
1020 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
1021 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
1022 * that are partially used.
1024 pd_p = (pd_entry_t *)DMPDphys;
1025 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
1026 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
1027 /* Preset PG_M and PG_A because demotion expects it. */
1028 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1029 X86_PG_M | X86_PG_A | pg_nx;
1031 pdp_p = (pdp_entry_t *)DMPDPphys;
1032 for (i = 0; i < ndm1g; i++) {
1033 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
1034 /* Preset PG_M and PG_A because demotion expects it. */
1035 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1036 X86_PG_M | X86_PG_A | pg_nx;
1038 for (j = 0; i < ndmpdp; i++, j++) {
1039 pdp_p[i] = DMPDphys + ptoa(j);
1040 pdp_p[i] |= X86_PG_RW | X86_PG_V;
1044 * Instead of using a 1G page for the memory containing the kernel,
1045 * use 2M pages with appropriate permissions. (If using 1G pages,
1046 * this will partially overwrite the PDPEs above.)
1049 pd_p = (pd_entry_t *)DMPDkernphys;
1050 for (i = 0; i < (NPDEPG * nkdmpde); i++)
1051 pd_p[i] = (i << PDRSHIFT) | X86_PG_V | PG_PS | pg_g |
1052 X86_PG_M | X86_PG_A | pg_nx |
1053 bootaddr_rwx(i << PDRSHIFT);
1054 for (i = 0; i < nkdmpde; i++)
1055 pdp_p[i] = (DMPDkernphys + ptoa(i)) | X86_PG_RW |
1059 /* And recursively map PML4 to itself in order to get PTmap */
1060 p4_p = (pml4_entry_t *)KPML4phys;
1061 p4_p[PML4PML4I] = KPML4phys;
1062 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | pg_nx;
1064 /* Connect the Direct Map slot(s) up to the PML4. */
1065 for (i = 0; i < ndmpdpphys; i++) {
1066 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
1067 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V;
1070 /* Connect the KVA slots up to the PML4 */
1071 for (i = 0; i < NKPML4E; i++) {
1072 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
1073 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V;
1078 * Bootstrap the system enough to run with virtual memory.
1080 * On amd64 this is called after mapping has already been enabled
1081 * and just syncs the pmap module with what has already been done.
1082 * [We can't call it easily with mapping off since the kernel is not
1083 * mapped with PA == VA, hence we would have to relocate every address
1084 * from the linked base (virtual) address "KERNBASE" to the actual
1085 * (physical) address starting relative to 0]
1088 pmap_bootstrap(vm_paddr_t *firstaddr)
1098 * Create an initial set of page tables to run the kernel in.
1100 create_pagetables(firstaddr);
1103 * Add a physical memory segment (vm_phys_seg) corresponding to the
1104 * preallocated kernel page table pages so that vm_page structures
1105 * representing these pages will be created. The vm_page structures
1106 * are required for promotion of the corresponding kernel virtual
1107 * addresses to superpage mappings.
1109 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1111 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
1113 virtual_end = VM_MAX_KERNEL_ADDRESS;
1116 /* XXX do %cr0 as well */
1117 load_cr4(rcr4() | CR4_PGE);
1118 load_cr3(KPML4phys);
1119 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1120 load_cr4(rcr4() | CR4_SMEP);
1123 * Initialize the kernel pmap (which is statically allocated).
1125 PMAP_LOCK_INIT(kernel_pmap);
1126 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1127 kernel_pmap->pm_cr3 = KPML4phys;
1128 kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
1129 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1130 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1131 kernel_pmap->pm_flags = pmap_flags;
1134 * Initialize the TLB invalidations generation number lock.
1136 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1139 * Reserve some special page table entries/VA space for temporary
1142 #define SYSMAP(c, p, v, n) \
1143 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1149 * Crashdump maps. The first page is reused as CMAP1 for the
1152 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1153 CADDR1 = crashdumpmap;
1158 * Initialize the PAT MSR.
1159 * pmap_init_pat() clears and sets CR4_PGE, which, as a
1160 * side-effect, invalidates stale PG_G TLB entries that might
1161 * have been created in our pre-boot environment.
1165 /* Initialize TLB Context Id. */
1166 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1167 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1168 /* Check for INVPCID support */
1169 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1171 for (i = 0; i < MAXCPU; i++) {
1172 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1173 kernel_pmap->pm_pcids[i].pm_gen = 1;
1175 PCPU_SET(pcid_next, PMAP_PCID_KERN + 1);
1176 PCPU_SET(pcid_gen, 1);
1178 * pcpu area for APs is zeroed during AP startup.
1179 * pc_pcid_next and pc_pcid_gen are initialized by AP
1180 * during pcpu setup.
1182 load_cr4(rcr4() | CR4_PCIDE);
1184 pmap_pcid_enabled = 0;
1189 * Setup the PAT MSR.
1194 int pat_table[PAT_INDEX_SIZE];
1199 /* Bail if this CPU doesn't implement PAT. */
1200 if ((cpu_feature & CPUID_PAT) == 0)
1203 /* Set default PAT index table. */
1204 for (i = 0; i < PAT_INDEX_SIZE; i++)
1206 pat_table[PAT_WRITE_BACK] = 0;
1207 pat_table[PAT_WRITE_THROUGH] = 1;
1208 pat_table[PAT_UNCACHEABLE] = 3;
1209 pat_table[PAT_WRITE_COMBINING] = 3;
1210 pat_table[PAT_WRITE_PROTECTED] = 3;
1211 pat_table[PAT_UNCACHED] = 3;
1213 /* Initialize default PAT entries. */
1214 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1215 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1216 PAT_VALUE(2, PAT_UNCACHED) |
1217 PAT_VALUE(3, PAT_UNCACHEABLE) |
1218 PAT_VALUE(4, PAT_WRITE_BACK) |
1219 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1220 PAT_VALUE(6, PAT_UNCACHED) |
1221 PAT_VALUE(7, PAT_UNCACHEABLE);
1225 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1226 * Program 5 and 6 as WP and WC.
1227 * Leave 4 and 7 as WB and UC.
1229 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1230 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1231 PAT_VALUE(6, PAT_WRITE_COMBINING);
1232 pat_table[PAT_UNCACHED] = 2;
1233 pat_table[PAT_WRITE_PROTECTED] = 5;
1234 pat_table[PAT_WRITE_COMBINING] = 6;
1237 * Just replace PAT Index 2 with WC instead of UC-.
1239 pat_msr &= ~PAT_MASK(2);
1240 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1241 pat_table[PAT_WRITE_COMBINING] = 2;
1246 load_cr4(cr4 & ~CR4_PGE);
1248 /* Disable caches (CD = 1, NW = 0). */
1250 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1252 /* Flushes caches and TLBs. */
1256 /* Update PAT and index table. */
1257 wrmsr(MSR_PAT, pat_msr);
1258 for (i = 0; i < PAT_INDEX_SIZE; i++)
1259 pat_index[i] = pat_table[i];
1261 /* Flush caches and TLBs again. */
1265 /* Restore caches and PGE. */
1271 * Initialize a vm_page's machine-dependent fields.
1274 pmap_page_init(vm_page_t m)
1277 TAILQ_INIT(&m->md.pv_list);
1278 m->md.pat_mode = PAT_WRITE_BACK;
1282 * Initialize the pmap module.
1283 * Called by vm_init, to initialize any structures that the pmap
1284 * system needs to map virtual memory.
1289 struct pmap_preinit_mapping *ppim;
1292 int error, i, pv_npg, ret, skz63;
1294 /* Detect bare-metal Skylake Server and Skylake-X. */
1295 if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
1296 CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
1298 * Skylake-X errata SKZ63. Processor May Hang When
1299 * Executing Code In an HLE Transaction Region between
1300 * 40000000H and 403FFFFFH.
1302 * Mark the pages in the range as preallocated. It
1303 * seems to be impossible to distinguish between
1304 * Skylake Server and Skylake X.
1307 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
1310 printf("SKZ63: skipping 4M RAM starting "
1311 "at physical 1G\n");
1312 for (i = 0; i < atop(0x400000); i++) {
1313 ret = vm_page_blacklist_add(0x40000000 +
1315 if (!ret && bootverbose)
1316 printf("page at %#lx already used\n",
1317 0x40000000 + ptoa(i));
1323 * Initialize the vm page array entries for the kernel pmap's
1326 for (i = 0; i < nkpt; i++) {
1327 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1328 KASSERT(mpte >= vm_page_array &&
1329 mpte < &vm_page_array[vm_page_array_size],
1330 ("pmap_init: page table page is out of range"));
1331 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1332 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1333 mpte->wire_count = 1;
1338 * If the kernel is running on a virtual machine, then it must assume
1339 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1340 * be prepared for the hypervisor changing the vendor and family that
1341 * are reported by CPUID. Consequently, the workaround for AMD Family
1342 * 10h Erratum 383 is enabled if the processor's feature set does not
1343 * include at least one feature that is only supported by older Intel
1344 * or newer AMD processors.
1346 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1347 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1348 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1350 workaround_erratum383 = 1;
1353 * Are large page mappings enabled?
1355 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1356 if (pg_ps_enabled) {
1357 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1358 ("pmap_init: can't assign to pagesizes[1]"));
1359 pagesizes[1] = NBPDR;
1363 * Initialize the pv chunk list mutex.
1365 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1368 * Initialize the pool of pv list locks.
1370 for (i = 0; i < NPV_LIST_LOCKS; i++)
1371 rw_init(&pv_list_locks[i], "pmap pv list");
1374 * Calculate the size of the pv head table for superpages.
1376 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1379 * Allocate memory for the pv head table for superpages.
1381 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1383 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1385 for (i = 0; i < pv_npg; i++)
1386 TAILQ_INIT(&pv_table[i].pv_list);
1387 TAILQ_INIT(&pv_dummy.pv_list);
1389 pmap_initialized = 1;
1390 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1391 ppim = pmap_preinit_mapping + i;
1394 /* Make the direct map consistent */
1395 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1396 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1397 ppim->sz, ppim->mode);
1401 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1402 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1405 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1406 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1407 (vmem_addr_t *)&qframe);
1409 panic("qframe allocation failed");
1412 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1413 "2MB page mapping counters");
1415 static u_long pmap_pde_demotions;
1416 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1417 &pmap_pde_demotions, 0, "2MB page demotions");
1419 static u_long pmap_pde_mappings;
1420 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1421 &pmap_pde_mappings, 0, "2MB page mappings");
1423 static u_long pmap_pde_p_failures;
1424 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1425 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1427 static u_long pmap_pde_promotions;
1428 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1429 &pmap_pde_promotions, 0, "2MB page promotions");
1431 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1432 "1GB page mapping counters");
1434 static u_long pmap_pdpe_demotions;
1435 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1436 &pmap_pdpe_demotions, 0, "1GB page demotions");
1438 /***************************************************
1439 * Low level helper routines.....
1440 ***************************************************/
1443 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1445 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1447 switch (pmap->pm_type) {
1450 /* Verify that both PAT bits are not set at the same time */
1451 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1452 ("Invalid PAT bits in entry %#lx", entry));
1454 /* Swap the PAT bits if one of them is set */
1455 if ((entry & x86_pat_bits) != 0)
1456 entry ^= x86_pat_bits;
1460 * Nothing to do - the memory attributes are represented
1461 * the same way for regular pages and superpages.
1465 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1472 * Determine the appropriate bits to set in a PTE or PDE for a specified
1476 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1478 int cache_bits, pat_flag, pat_idx;
1480 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1481 panic("Unknown caching mode %d\n", mode);
1483 switch (pmap->pm_type) {
1486 /* The PAT bit is different for PTE's and PDE's. */
1487 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1489 /* Map the caching mode to a PAT index. */
1490 pat_idx = pat_index[mode];
1492 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1495 cache_bits |= pat_flag;
1497 cache_bits |= PG_NC_PCD;
1499 cache_bits |= PG_NC_PWT;
1503 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1507 panic("unsupported pmap type %d", pmap->pm_type);
1510 return (cache_bits);
1514 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1518 switch (pmap->pm_type) {
1521 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1524 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1527 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1534 pmap_ps_enabled(pmap_t pmap)
1537 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1541 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1544 switch (pmap->pm_type) {
1551 * This is a little bogus since the generation number is
1552 * supposed to be bumped up when a region of the address
1553 * space is invalidated in the page tables.
1555 * In this case the old PDE entry is valid but yet we want
1556 * to make sure that any mappings using the old entry are
1557 * invalidated in the TLB.
1559 * The reason this works as expected is because we rendezvous
1560 * "all" host cpus and force any vcpu context to exit as a
1563 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1566 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1568 pde_store(pde, newpde);
1572 * After changing the page size for the specified virtual address in the page
1573 * table, flush the corresponding entries from the processor's TLB. Only the
1574 * calling processor's TLB is affected.
1576 * The calling thread must be pinned to a processor.
1579 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1583 if (pmap_type_guest(pmap))
1586 KASSERT(pmap->pm_type == PT_X86,
1587 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1589 PG_G = pmap_global_bit(pmap);
1591 if ((newpde & PG_PS) == 0)
1592 /* Demotion: flush a specific 2MB page mapping. */
1594 else if ((newpde & PG_G) == 0)
1596 * Promotion: flush every 4KB page mapping from the TLB
1597 * because there are too many to flush individually.
1602 * Promotion: flush every 4KB page mapping from the TLB,
1603 * including any global (PG_G) mappings.
1611 * For SMP, these functions have to use the IPI mechanism for coherence.
1613 * N.B.: Before calling any of the following TLB invalidation functions,
1614 * the calling processor must ensure that all stores updating a non-
1615 * kernel page table are globally performed. Otherwise, another
1616 * processor could cache an old, pre-update entry without being
1617 * invalidated. This can happen one of two ways: (1) The pmap becomes
1618 * active on another processor after its pm_active field is checked by
1619 * one of the following functions but before a store updating the page
1620 * table is globally performed. (2) The pmap becomes active on another
1621 * processor before its pm_active field is checked but due to
1622 * speculative loads one of the following functions stills reads the
1623 * pmap as inactive on the other processor.
1625 * The kernel page table is exempt because its pm_active field is
1626 * immutable. The kernel page table is always active on every
1631 * Interrupt the cpus that are executing in the guest context.
1632 * This will force the vcpu to exit and the cached EPT mappings
1633 * will be invalidated by the host before the next vmresume.
1635 static __inline void
1636 pmap_invalidate_ept(pmap_t pmap)
1641 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1642 ("pmap_invalidate_ept: absurd pm_active"));
1645 * The TLB mappings associated with a vcpu context are not
1646 * flushed each time a different vcpu is chosen to execute.
1648 * This is in contrast with a process's vtop mappings that
1649 * are flushed from the TLB on each context switch.
1651 * Therefore we need to do more than just a TLB shootdown on
1652 * the active cpus in 'pmap->pm_active'. To do this we keep
1653 * track of the number of invalidations performed on this pmap.
1655 * Each vcpu keeps a cache of this counter and compares it
1656 * just before a vmresume. If the counter is out-of-date an
1657 * invept will be done to flush stale mappings from the TLB.
1659 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1662 * Force the vcpu to exit and trap back into the hypervisor.
1664 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1665 ipi_selected(pmap->pm_active, ipinum);
1670 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1673 struct invpcid_descr d;
1674 uint64_t kcr3, ucr3;
1678 if (pmap_type_guest(pmap)) {
1679 pmap_invalidate_ept(pmap);
1683 KASSERT(pmap->pm_type == PT_X86,
1684 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1687 if (pmap == kernel_pmap) {
1691 cpuid = PCPU_GET(cpuid);
1692 if (pmap == PCPU_GET(curpmap)) {
1694 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1696 * Disable context switching. pm_pcid
1697 * is recalculated on switch, which
1698 * might make us use wrong pcid below.
1701 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1703 if (invpcid_works) {
1704 d.pcid = pcid | PMAP_PCID_USER_PT;
1707 invpcid(&d, INVPCID_ADDR);
1709 kcr3 = pmap->pm_cr3 | pcid |
1711 ucr3 = pmap->pm_ucr3 | pcid |
1712 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1713 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1717 } else if (pmap_pcid_enabled)
1718 pmap->pm_pcids[cpuid].pm_gen = 0;
1719 if (pmap_pcid_enabled) {
1722 pmap->pm_pcids[i].pm_gen = 0;
1726 * The fence is between stores to pm_gen and the read of
1727 * the pm_active mask. We need to ensure that it is
1728 * impossible for us to miss the bit update in pm_active
1729 * and simultaneously observe a non-zero pm_gen in
1730 * pmap_activate_sw(), otherwise TLB update is missed.
1731 * Without the fence, IA32 allows such an outcome.
1732 * Note that pm_active is updated by a locked operation,
1733 * which provides the reciprocal fence.
1735 atomic_thread_fence_seq_cst();
1737 mask = &pmap->pm_active;
1739 smp_masked_invlpg(*mask, va, pmap);
1743 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1744 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1747 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1750 struct invpcid_descr d;
1752 uint64_t kcr3, ucr3;
1756 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1757 pmap_invalidate_all(pmap);
1761 if (pmap_type_guest(pmap)) {
1762 pmap_invalidate_ept(pmap);
1766 KASSERT(pmap->pm_type == PT_X86,
1767 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1770 cpuid = PCPU_GET(cpuid);
1771 if (pmap == kernel_pmap) {
1772 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1776 if (pmap == PCPU_GET(curpmap)) {
1777 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1779 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1781 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1782 if (invpcid_works) {
1783 d.pcid = pcid | PMAP_PCID_USER_PT;
1786 for (; d.addr < eva; d.addr +=
1788 invpcid(&d, INVPCID_ADDR);
1790 kcr3 = pmap->pm_cr3 | pcid |
1792 ucr3 = pmap->pm_ucr3 | pcid |
1793 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1794 pmap_pti_pcid_invlrng(ucr3, kcr3, sva,
1799 } else if (pmap_pcid_enabled) {
1800 pmap->pm_pcids[cpuid].pm_gen = 0;
1802 if (pmap_pcid_enabled) {
1805 pmap->pm_pcids[i].pm_gen = 0;
1807 /* See the comment in pmap_invalidate_page(). */
1808 atomic_thread_fence_seq_cst();
1810 mask = &pmap->pm_active;
1812 smp_masked_invlpg_range(*mask, sva, eva, pmap);
1817 pmap_invalidate_all(pmap_t pmap)
1820 struct invpcid_descr d;
1821 uint64_t kcr3, ucr3;
1825 if (pmap_type_guest(pmap)) {
1826 pmap_invalidate_ept(pmap);
1830 KASSERT(pmap->pm_type == PT_X86,
1831 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1834 if (pmap == kernel_pmap) {
1835 if (pmap_pcid_enabled && invpcid_works) {
1836 bzero(&d, sizeof(d));
1837 invpcid(&d, INVPCID_CTXGLOB);
1843 cpuid = PCPU_GET(cpuid);
1844 if (pmap == PCPU_GET(curpmap)) {
1845 if (pmap_pcid_enabled) {
1847 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1848 if (invpcid_works) {
1852 invpcid(&d, INVPCID_CTX);
1853 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1854 d.pcid |= PMAP_PCID_USER_PT;
1855 invpcid(&d, INVPCID_CTX);
1858 kcr3 = pmap->pm_cr3 | pcid;
1859 ucr3 = pmap->pm_ucr3;
1860 if (ucr3 != PMAP_NO_CR3) {
1861 ucr3 |= pcid | PMAP_PCID_USER_PT;
1862 pmap_pti_pcid_invalidate(ucr3,
1872 } else if (pmap_pcid_enabled) {
1873 pmap->pm_pcids[cpuid].pm_gen = 0;
1875 if (pmap_pcid_enabled) {
1878 pmap->pm_pcids[i].pm_gen = 0;
1880 /* See the comment in pmap_invalidate_page(). */
1881 atomic_thread_fence_seq_cst();
1883 mask = &pmap->pm_active;
1885 smp_masked_invltlb(*mask, pmap);
1890 pmap_invalidate_cache(void)
1900 cpuset_t invalidate; /* processors that invalidate their TLB */
1905 u_int store; /* processor that updates the PDE */
1909 pmap_update_pde_action(void *arg)
1911 struct pde_action *act = arg;
1913 if (act->store == PCPU_GET(cpuid))
1914 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1918 pmap_update_pde_teardown(void *arg)
1920 struct pde_action *act = arg;
1922 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1923 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1927 * Change the page size for the specified virtual address in a way that
1928 * prevents any possibility of the TLB ever having two entries that map the
1929 * same virtual address using different page sizes. This is the recommended
1930 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1931 * machine check exception for a TLB state that is improperly diagnosed as a
1935 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1937 struct pde_action act;
1938 cpuset_t active, other_cpus;
1942 cpuid = PCPU_GET(cpuid);
1943 other_cpus = all_cpus;
1944 CPU_CLR(cpuid, &other_cpus);
1945 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1948 active = pmap->pm_active;
1950 if (CPU_OVERLAP(&active, &other_cpus)) {
1952 act.invalidate = active;
1956 act.newpde = newpde;
1957 CPU_SET(cpuid, &active);
1958 smp_rendezvous_cpus(active,
1959 smp_no_rendezvous_barrier, pmap_update_pde_action,
1960 pmap_update_pde_teardown, &act);
1962 pmap_update_pde_store(pmap, pde, newpde);
1963 if (CPU_ISSET(cpuid, &active))
1964 pmap_update_pde_invalidate(pmap, va, newpde);
1970 * Normal, non-SMP, invalidation functions.
1973 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1975 struct invpcid_descr d;
1976 uint64_t kcr3, ucr3;
1979 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1983 KASSERT(pmap->pm_type == PT_X86,
1984 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1986 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1988 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
1989 pmap->pm_ucr3 != PMAP_NO_CR3) {
1991 pcid = pmap->pm_pcids[0].pm_pcid;
1992 if (invpcid_works) {
1993 d.pcid = pcid | PMAP_PCID_USER_PT;
1996 invpcid(&d, INVPCID_ADDR);
1998 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
1999 ucr3 = pmap->pm_ucr3 | pcid |
2000 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
2001 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
2005 } else if (pmap_pcid_enabled)
2006 pmap->pm_pcids[0].pm_gen = 0;
2010 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2012 struct invpcid_descr d;
2014 uint64_t kcr3, ucr3;
2016 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
2020 KASSERT(pmap->pm_type == PT_X86,
2021 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
2023 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
2024 for (addr = sva; addr < eva; addr += PAGE_SIZE)
2026 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
2027 pmap->pm_ucr3 != PMAP_NO_CR3) {
2029 if (invpcid_works) {
2030 d.pcid = pmap->pm_pcids[0].pm_pcid |
2034 for (; d.addr < eva; d.addr += PAGE_SIZE)
2035 invpcid(&d, INVPCID_ADDR);
2037 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].
2038 pm_pcid | CR3_PCID_SAVE;
2039 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[0].
2040 pm_pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
2041 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
2045 } else if (pmap_pcid_enabled) {
2046 pmap->pm_pcids[0].pm_gen = 0;
2051 pmap_invalidate_all(pmap_t pmap)
2053 struct invpcid_descr d;
2054 uint64_t kcr3, ucr3;
2056 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
2060 KASSERT(pmap->pm_type == PT_X86,
2061 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
2063 if (pmap == kernel_pmap) {
2064 if (pmap_pcid_enabled && invpcid_works) {
2065 bzero(&d, sizeof(d));
2066 invpcid(&d, INVPCID_CTXGLOB);
2070 } else if (pmap == PCPU_GET(curpmap)) {
2071 if (pmap_pcid_enabled) {
2073 if (invpcid_works) {
2074 d.pcid = pmap->pm_pcids[0].pm_pcid;
2077 invpcid(&d, INVPCID_CTX);
2078 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2079 d.pcid |= PMAP_PCID_USER_PT;
2080 invpcid(&d, INVPCID_CTX);
2083 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].pm_pcid;
2084 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2085 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[
2086 0].pm_pcid | PMAP_PCID_USER_PT;
2087 pmap_pti_pcid_invalidate(ucr3, kcr3);
2095 } else if (pmap_pcid_enabled) {
2096 pmap->pm_pcids[0].pm_gen = 0;
2101 pmap_invalidate_cache(void)
2108 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
2111 pmap_update_pde_store(pmap, pde, newpde);
2112 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
2113 pmap_update_pde_invalidate(pmap, va, newpde);
2115 pmap->pm_pcids[0].pm_gen = 0;
2120 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
2124 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
2125 * by a promotion that did not invalidate the 512 4KB page mappings
2126 * that might exist in the TLB. Consequently, at this point, the TLB
2127 * may hold both 4KB and 2MB page mappings for the address range [va,
2128 * va + NBPDR). Therefore, the entire range must be invalidated here.
2129 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
2130 * 4KB page mappings for the address range [va, va + NBPDR), and so a
2131 * single INVLPG suffices to invalidate the 2MB page mapping from the
2134 if ((pde & PG_PROMOTED) != 0)
2135 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
2137 pmap_invalidate_page(pmap, va);
2140 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
2143 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
2147 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
2149 KASSERT((sva & PAGE_MASK) == 0,
2150 ("pmap_invalidate_cache_range: sva not page-aligned"));
2151 KASSERT((eva & PAGE_MASK) == 0,
2152 ("pmap_invalidate_cache_range: eva not page-aligned"));
2155 if ((cpu_feature & CPUID_SS) != 0 && !force)
2156 ; /* If "Self Snoop" is supported and allowed, do nothing. */
2157 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
2158 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2160 * XXX: Some CPUs fault, hang, or trash the local APIC
2161 * registers if we use CLFLUSH on the local APIC
2162 * range. The local APIC is always uncached, so we
2163 * don't need to flush for that range anyway.
2165 if (pmap_kextract(sva) == lapic_paddr)
2169 * Otherwise, do per-cache line flush. Use the sfence
2170 * instruction to insure that previous stores are
2171 * included in the write-back. The processor
2172 * propagates flush to other processors in the cache
2176 for (; sva < eva; sva += cpu_clflush_line_size)
2179 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
2180 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2181 if (pmap_kextract(sva) == lapic_paddr)
2184 * Writes are ordered by CLFLUSH on Intel CPUs.
2186 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2188 for (; sva < eva; sva += cpu_clflush_line_size)
2190 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2195 * No targeted cache flush methods are supported by CPU,
2196 * or the supplied range is bigger than 2MB.
2197 * Globally invalidate cache.
2199 pmap_invalidate_cache();
2204 * Remove the specified set of pages from the data and instruction caches.
2206 * In contrast to pmap_invalidate_cache_range(), this function does not
2207 * rely on the CPU's self-snoop feature, because it is intended for use
2208 * when moving pages into a different cache domain.
2211 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
2213 vm_offset_t daddr, eva;
2217 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
2218 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
2219 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
2220 pmap_invalidate_cache();
2224 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2226 for (i = 0; i < count; i++) {
2227 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
2228 eva = daddr + PAGE_SIZE;
2229 for (; daddr < eva; daddr += cpu_clflush_line_size) {
2238 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2244 * Routine: pmap_extract
2246 * Extract the physical page address associated
2247 * with the given map/virtual_address pair.
2250 pmap_extract(pmap_t pmap, vm_offset_t va)
2254 pt_entry_t *pte, PG_V;
2258 PG_V = pmap_valid_bit(pmap);
2260 pdpe = pmap_pdpe(pmap, va);
2261 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2262 if ((*pdpe & PG_PS) != 0)
2263 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
2265 pde = pmap_pdpe_to_pde(pdpe, va);
2266 if ((*pde & PG_V) != 0) {
2267 if ((*pde & PG_PS) != 0) {
2268 pa = (*pde & PG_PS_FRAME) |
2271 pte = pmap_pde_to_pte(pde, va);
2272 pa = (*pte & PG_FRAME) |
2283 * Routine: pmap_extract_and_hold
2285 * Atomically extract and hold the physical page
2286 * with the given pmap and virtual address pair
2287 * if that mapping permits the given protection.
2290 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
2292 pd_entry_t pde, *pdep;
2293 pt_entry_t pte, PG_RW, PG_V;
2299 PG_RW = pmap_rw_bit(pmap);
2300 PG_V = pmap_valid_bit(pmap);
2303 pdep = pmap_pde(pmap, va);
2304 if (pdep != NULL && (pde = *pdep)) {
2306 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2307 if (vm_page_pa_tryrelock(pmap, (pde &
2308 PG_PS_FRAME) | (va & PDRMASK), &pa))
2310 m = PHYS_TO_VM_PAGE(pa);
2314 pte = *pmap_pde_to_pte(pdep, va);
2316 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2317 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2320 m = PHYS_TO_VM_PAGE(pa);
2332 pmap_kextract(vm_offset_t va)
2337 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2338 pa = DMAP_TO_PHYS(va);
2342 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2345 * Beware of a concurrent promotion that changes the
2346 * PDE at this point! For example, vtopte() must not
2347 * be used to access the PTE because it would use the
2348 * new PDE. It is, however, safe to use the old PDE
2349 * because the page table page is preserved by the
2352 pa = *pmap_pde_to_pte(&pde, va);
2353 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2359 /***************************************************
2360 * Low level mapping routines.....
2361 ***************************************************/
2364 * Add a wired page to the kva.
2365 * Note: not SMP coherent.
2368 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2373 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g);
2376 static __inline void
2377 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2383 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2384 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | cache_bits);
2388 * Remove a page from the kernel pagetables.
2389 * Note: not SMP coherent.
2392 pmap_kremove(vm_offset_t va)
2401 * Used to map a range of physical addresses into kernel
2402 * virtual address space.
2404 * The value passed in '*virt' is a suggested virtual address for
2405 * the mapping. Architectures which can support a direct-mapped
2406 * physical to virtual region can return the appropriate address
2407 * within that region, leaving '*virt' unchanged. Other
2408 * architectures should map the pages starting at '*virt' and
2409 * update '*virt' with the first usable address after the mapped
2413 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2415 return PHYS_TO_DMAP(start);
2420 * Add a list of wired pages to the kva
2421 * this routine is only used for temporary
2422 * kernel mappings that do not need to have
2423 * page modification or references recorded.
2424 * Note that old mappings are simply written
2425 * over. The page *must* be wired.
2426 * Note: SMP coherent. Uses a ranged shootdown IPI.
2429 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2431 pt_entry_t *endpte, oldpte, pa, *pte;
2437 endpte = pte + count;
2438 while (pte < endpte) {
2440 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2441 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2442 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2444 pte_store(pte, pa | pg_g | pg_nx | X86_PG_RW | X86_PG_V);
2448 if (__predict_false((oldpte & X86_PG_V) != 0))
2449 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2454 * This routine tears out page mappings from the
2455 * kernel -- it is meant only for temporary mappings.
2456 * Note: SMP coherent. Uses a ranged shootdown IPI.
2459 pmap_qremove(vm_offset_t sva, int count)
2464 while (count-- > 0) {
2465 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2469 pmap_invalidate_range(kernel_pmap, sva, va);
2472 /***************************************************
2473 * Page table page management routines.....
2474 ***************************************************/
2476 * Schedule the specified unused page table page to be freed. Specifically,
2477 * add the page to the specified list of pages that will be released to the
2478 * physical memory manager after the TLB has been updated.
2480 static __inline void
2481 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2482 boolean_t set_PG_ZERO)
2486 m->flags |= PG_ZERO;
2488 m->flags &= ~PG_ZERO;
2489 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2493 * Inserts the specified page table page into the specified pmap's collection
2494 * of idle page table pages. Each of a pmap's page table pages is responsible
2495 * for mapping a distinct range of virtual addresses. The pmap's collection is
2496 * ordered by this virtual address range.
2499 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2502 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2503 return (vm_radix_insert(&pmap->pm_root, mpte));
2507 * Removes the page table page mapping the specified virtual address from the
2508 * specified pmap's collection of idle page table pages, and returns it.
2509 * Otherwise, returns NULL if there is no page table page corresponding to the
2510 * specified virtual address.
2512 static __inline vm_page_t
2513 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
2516 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2517 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
2521 * Decrements a page table page's wire count, which is used to record the
2522 * number of valid page table entries within the page. If the wire count
2523 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2524 * page table page was unmapped and FALSE otherwise.
2526 static inline boolean_t
2527 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2531 if (m->wire_count == 0) {
2532 _pmap_unwire_ptp(pmap, va, m, free);
2539 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2542 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2544 * unmap the page table page
2546 if (m->pindex >= (NUPDE + NUPDPE)) {
2549 pml4 = pmap_pml4e(pmap, va);
2551 if (pmap->pm_pml4u != NULL && va <= VM_MAXUSER_ADDRESS) {
2552 pml4 = &pmap->pm_pml4u[pmap_pml4e_index(va)];
2555 } else if (m->pindex >= NUPDE) {
2558 pdp = pmap_pdpe(pmap, va);
2563 pd = pmap_pde(pmap, va);
2566 pmap_resident_count_dec(pmap, 1);
2567 if (m->pindex < NUPDE) {
2568 /* We just released a PT, unhold the matching PD */
2571 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2572 pmap_unwire_ptp(pmap, va, pdpg, free);
2574 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2575 /* We just released a PD, unhold the matching PDP */
2578 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2579 pmap_unwire_ptp(pmap, va, pdppg, free);
2583 * Put page on a list so that it is released after
2584 * *ALL* TLB shootdown is done
2586 pmap_add_delayed_free_list(m, free, TRUE);
2590 * After removing a page table entry, this routine is used to
2591 * conditionally free the page, and manage the hold/wire counts.
2594 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2595 struct spglist *free)
2599 if (va >= VM_MAXUSER_ADDRESS)
2601 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2602 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2603 return (pmap_unwire_ptp(pmap, va, mpte, free));
2607 pmap_pinit0(pmap_t pmap)
2611 PMAP_LOCK_INIT(pmap);
2612 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2613 pmap->pm_pml4u = NULL;
2614 pmap->pm_cr3 = KPML4phys;
2615 /* hack to keep pmap_pti_pcid_invalidate() alive */
2616 pmap->pm_ucr3 = PMAP_NO_CR3;
2617 pmap->pm_root.rt_root = 0;
2618 CPU_ZERO(&pmap->pm_active);
2619 TAILQ_INIT(&pmap->pm_pvchunk);
2620 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2621 pmap->pm_flags = pmap_flags;
2623 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2624 pmap->pm_pcids[i].pm_gen = 0;
2626 __pcpu[i].pc_kcr3 = PMAP_NO_CR3;
2627 __pcpu[i].pc_ucr3 = PMAP_NO_CR3;
2630 PCPU_SET(curpmap, kernel_pmap);
2631 pmap_activate(curthread);
2632 CPU_FILL(&kernel_pmap->pm_active);
2636 pmap_pinit_pml4(vm_page_t pml4pg)
2638 pml4_entry_t *pm_pml4;
2641 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2643 /* Wire in kernel global address entries. */
2644 for (i = 0; i < NKPML4E; i++) {
2645 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2648 for (i = 0; i < ndmpdpphys; i++) {
2649 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2653 /* install self-referential address mapping entry(s) */
2654 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2655 X86_PG_A | X86_PG_M;
2659 pmap_pinit_pml4_pti(vm_page_t pml4pg)
2661 pml4_entry_t *pm_pml4;
2664 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2665 for (i = 0; i < NPML4EPG; i++)
2666 pm_pml4[i] = pti_pml4[i];
2670 * Initialize a preallocated and zeroed pmap structure,
2671 * such as one in a vmspace structure.
2674 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2676 vm_page_t pml4pg, pml4pgu;
2677 vm_paddr_t pml4phys;
2681 * allocate the page directory page
2683 pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
2684 VM_ALLOC_WIRED | VM_ALLOC_ZERO | VM_ALLOC_WAITOK);
2686 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2687 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2689 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2690 pmap->pm_pcids[i].pm_gen = 0;
2692 pmap->pm_cr3 = PMAP_NO_CR3; /* initialize to an invalid value */
2693 pmap->pm_ucr3 = PMAP_NO_CR3;
2694 pmap->pm_pml4u = NULL;
2696 pmap->pm_type = pm_type;
2697 if ((pml4pg->flags & PG_ZERO) == 0)
2698 pagezero(pmap->pm_pml4);
2701 * Do not install the host kernel mappings in the nested page
2702 * tables. These mappings are meaningless in the guest physical
2704 * Install minimal kernel mappings in PTI case.
2706 if (pm_type == PT_X86) {
2707 pmap->pm_cr3 = pml4phys;
2708 pmap_pinit_pml4(pml4pg);
2710 pml4pgu = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2711 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2712 pmap->pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(
2713 VM_PAGE_TO_PHYS(pml4pgu));
2714 pmap_pinit_pml4_pti(pml4pgu);
2715 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pml4pgu);
2719 pmap->pm_root.rt_root = 0;
2720 CPU_ZERO(&pmap->pm_active);
2721 TAILQ_INIT(&pmap->pm_pvchunk);
2722 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2723 pmap->pm_flags = flags;
2724 pmap->pm_eptgen = 0;
2730 pmap_pinit(pmap_t pmap)
2733 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2737 * This routine is called if the desired page table page does not exist.
2739 * If page table page allocation fails, this routine may sleep before
2740 * returning NULL. It sleeps only if a lock pointer was given.
2742 * Note: If a page allocation fails at page table level two or three,
2743 * one or two pages may be held during the wait, only to be released
2744 * afterwards. This conservative approach is easily argued to avoid
2748 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2750 vm_page_t m, pdppg, pdpg;
2751 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2753 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2755 PG_A = pmap_accessed_bit(pmap);
2756 PG_M = pmap_modified_bit(pmap);
2757 PG_V = pmap_valid_bit(pmap);
2758 PG_RW = pmap_rw_bit(pmap);
2761 * Allocate a page table page.
2763 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2764 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2765 if (lockp != NULL) {
2766 RELEASE_PV_LIST_LOCK(lockp);
2768 PMAP_ASSERT_NOT_IN_DI();
2774 * Indicate the need to retry. While waiting, the page table
2775 * page may have been allocated.
2779 if ((m->flags & PG_ZERO) == 0)
2783 * Map the pagetable page into the process address space, if
2784 * it isn't already there.
2787 if (ptepindex >= (NUPDE + NUPDPE)) {
2788 pml4_entry_t *pml4, *pml4u;
2789 vm_pindex_t pml4index;
2791 /* Wire up a new PDPE page */
2792 pml4index = ptepindex - (NUPDE + NUPDPE);
2793 pml4 = &pmap->pm_pml4[pml4index];
2794 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2795 if (pmap->pm_pml4u != NULL && pml4index < NUPML4E) {
2797 * PTI: Make all user-space mappings in the
2798 * kernel-mode page table no-execute so that
2799 * we detect any programming errors that leave
2800 * the kernel-mode page table active on return
2803 if (pmap->pm_ucr3 != PMAP_NO_CR3)
2806 pml4u = &pmap->pm_pml4u[pml4index];
2807 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
2811 } else if (ptepindex >= NUPDE) {
2812 vm_pindex_t pml4index;
2813 vm_pindex_t pdpindex;
2817 /* Wire up a new PDE page */
2818 pdpindex = ptepindex - NUPDE;
2819 pml4index = pdpindex >> NPML4EPGSHIFT;
2821 pml4 = &pmap->pm_pml4[pml4index];
2822 if ((*pml4 & PG_V) == 0) {
2823 /* Have to allocate a new pdp, recurse */
2824 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2826 vm_page_unwire_noq(m);
2827 vm_page_free_zero(m);
2831 /* Add reference to pdp page */
2832 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2833 pdppg->wire_count++;
2835 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2837 /* Now find the pdp page */
2838 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2839 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2842 vm_pindex_t pml4index;
2843 vm_pindex_t pdpindex;
2848 /* Wire up a new PTE page */
2849 pdpindex = ptepindex >> NPDPEPGSHIFT;
2850 pml4index = pdpindex >> NPML4EPGSHIFT;
2852 /* First, find the pdp and check that its valid. */
2853 pml4 = &pmap->pm_pml4[pml4index];
2854 if ((*pml4 & PG_V) == 0) {
2855 /* Have to allocate a new pd, recurse */
2856 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2858 vm_page_unwire_noq(m);
2859 vm_page_free_zero(m);
2862 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2863 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2865 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2866 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2867 if ((*pdp & PG_V) == 0) {
2868 /* Have to allocate a new pd, recurse */
2869 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2871 vm_page_unwire_noq(m);
2872 vm_page_free_zero(m);
2876 /* Add reference to the pd page */
2877 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2881 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2883 /* Now we know where the page directory page is */
2884 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2885 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2888 pmap_resident_count_inc(pmap, 1);
2894 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2896 vm_pindex_t pdpindex, ptepindex;
2897 pdp_entry_t *pdpe, PG_V;
2900 PG_V = pmap_valid_bit(pmap);
2903 pdpe = pmap_pdpe(pmap, va);
2904 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2905 /* Add a reference to the pd page. */
2906 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2909 /* Allocate a pd page. */
2910 ptepindex = pmap_pde_pindex(va);
2911 pdpindex = ptepindex >> NPDPEPGSHIFT;
2912 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2913 if (pdpg == NULL && lockp != NULL)
2920 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2922 vm_pindex_t ptepindex;
2923 pd_entry_t *pd, PG_V;
2926 PG_V = pmap_valid_bit(pmap);
2929 * Calculate pagetable page index
2931 ptepindex = pmap_pde_pindex(va);
2934 * Get the page directory entry
2936 pd = pmap_pde(pmap, va);
2939 * This supports switching from a 2MB page to a
2942 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2943 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2945 * Invalidation of the 2MB page mapping may have caused
2946 * the deallocation of the underlying PD page.
2953 * If the page table page is mapped, we just increment the
2954 * hold count, and activate it.
2956 if (pd != NULL && (*pd & PG_V) != 0) {
2957 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2961 * Here if the pte page isn't mapped, or if it has been
2964 m = _pmap_allocpte(pmap, ptepindex, lockp);
2965 if (m == NULL && lockp != NULL)
2972 /***************************************************
2973 * Pmap allocation/deallocation routines.
2974 ***************************************************/
2977 * Release any resources held by the given physical map.
2978 * Called when a pmap initialized by pmap_pinit is being released.
2979 * Should only be called if the map contains no valid mappings.
2982 pmap_release(pmap_t pmap)
2987 KASSERT(pmap->pm_stats.resident_count == 0,
2988 ("pmap_release: pmap resident count %ld != 0",
2989 pmap->pm_stats.resident_count));
2990 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2991 ("pmap_release: pmap has reserved page table page(s)"));
2992 KASSERT(CPU_EMPTY(&pmap->pm_active),
2993 ("releasing active pmap %p", pmap));
2995 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2997 for (i = 0; i < NKPML4E; i++) /* KVA */
2998 pmap->pm_pml4[KPML4BASE + i] = 0;
2999 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
3000 pmap->pm_pml4[DMPML4I + i] = 0;
3001 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
3003 vm_page_unwire_noq(m);
3004 vm_page_free_zero(m);
3006 if (pmap->pm_pml4u != NULL) {
3007 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4u));
3008 vm_page_unwire_noq(m);
3014 kvm_size(SYSCTL_HANDLER_ARGS)
3016 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
3018 return sysctl_handle_long(oidp, &ksize, 0, req);
3020 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
3021 0, 0, kvm_size, "LU", "Size of KVM");
3024 kvm_free(SYSCTL_HANDLER_ARGS)
3026 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
3028 return sysctl_handle_long(oidp, &kfree, 0, req);
3030 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
3031 0, 0, kvm_free, "LU", "Amount of KVM free");
3034 * grow the number of kernel page table entries, if needed
3037 pmap_growkernel(vm_offset_t addr)
3041 pd_entry_t *pde, newpdir;
3044 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
3047 * Return if "addr" is within the range of kernel page table pages
3048 * that were preallocated during pmap bootstrap. Moreover, leave
3049 * "kernel_vm_end" and the kernel page table as they were.
3051 * The correctness of this action is based on the following
3052 * argument: vm_map_insert() allocates contiguous ranges of the
3053 * kernel virtual address space. It calls this function if a range
3054 * ends after "kernel_vm_end". If the kernel is mapped between
3055 * "kernel_vm_end" and "addr", then the range cannot begin at
3056 * "kernel_vm_end". In fact, its beginning address cannot be less
3057 * than the kernel. Thus, there is no immediate need to allocate
3058 * any new kernel page table pages between "kernel_vm_end" and
3061 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
3064 addr = roundup2(addr, NBPDR);
3065 if (addr - 1 >= kernel_map->max_offset)
3066 addr = kernel_map->max_offset;
3067 while (kernel_vm_end < addr) {
3068 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
3069 if ((*pdpe & X86_PG_V) == 0) {
3070 /* We need a new PDP entry */
3071 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
3072 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
3073 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
3075 panic("pmap_growkernel: no memory to grow kernel");
3076 if ((nkpg->flags & PG_ZERO) == 0)
3077 pmap_zero_page(nkpg);
3078 paddr = VM_PAGE_TO_PHYS(nkpg);
3079 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
3080 X86_PG_A | X86_PG_M);
3081 continue; /* try again */
3083 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
3084 if ((*pde & X86_PG_V) != 0) {
3085 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3086 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
3087 kernel_vm_end = kernel_map->max_offset;
3093 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
3094 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
3097 panic("pmap_growkernel: no memory to grow kernel");
3098 if ((nkpg->flags & PG_ZERO) == 0)
3099 pmap_zero_page(nkpg);
3100 paddr = VM_PAGE_TO_PHYS(nkpg);
3101 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
3102 pde_store(pde, newpdir);
3104 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3105 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
3106 kernel_vm_end = kernel_map->max_offset;
3113 /***************************************************
3114 * page management routines.
3115 ***************************************************/
3117 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
3118 CTASSERT(_NPCM == 3);
3119 CTASSERT(_NPCPV == 168);
3121 static __inline struct pv_chunk *
3122 pv_to_chunk(pv_entry_t pv)
3125 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
3128 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
3130 #define PC_FREE0 0xfffffffffffffffful
3131 #define PC_FREE1 0xfffffffffffffffful
3132 #define PC_FREE2 0x000000fffffffffful
3134 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
3137 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
3139 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
3140 "Current number of pv entry chunks");
3141 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
3142 "Current number of pv entry chunks allocated");
3143 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
3144 "Current number of pv entry chunks frees");
3145 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
3146 "Number of times tried to get a chunk page but failed.");
3148 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
3149 static int pv_entry_spare;
3151 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
3152 "Current number of pv entry frees");
3153 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
3154 "Current number of pv entry allocs");
3155 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
3156 "Current number of pv entries");
3157 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
3158 "Current number of spare pv entries");
3162 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
3167 pmap_invalidate_all(pmap);
3168 if (pmap != locked_pmap)
3171 pmap_delayed_invl_finished();
3175 * We are in a serious low memory condition. Resort to
3176 * drastic measures to free some pages so we can allocate
3177 * another pv entry chunk.
3179 * Returns NULL if PV entries were reclaimed from the specified pmap.
3181 * We do not, however, unmap 2mpages because subsequent accesses will
3182 * allocate per-page pv entries until repromotion occurs, thereby
3183 * exacerbating the shortage of free pv entries.
3186 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
3188 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
3189 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
3190 struct md_page *pvh;
3192 pmap_t next_pmap, pmap;
3193 pt_entry_t *pte, tpte;
3194 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3198 struct spglist free;
3200 int bit, field, freed;
3202 static int active_reclaims = 0;
3204 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
3205 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
3208 PG_G = PG_A = PG_M = PG_RW = 0;
3210 bzero(&pc_marker_b, sizeof(pc_marker_b));
3211 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
3212 pc_marker = (struct pv_chunk *)&pc_marker_b;
3213 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
3216 * A delayed invalidation block should already be active if
3217 * pmap_advise() or pmap_remove() called this function by way
3218 * of pmap_demote_pde_locked().
3220 start_di = pmap_not_in_di();
3222 mtx_lock(&pv_chunks_mutex);
3224 TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
3225 TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
3226 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
3227 SLIST_EMPTY(&free)) {
3228 next_pmap = pc->pc_pmap;
3229 if (next_pmap == NULL) {
3231 * The next chunk is a marker. However, it is
3232 * not our marker, so active_reclaims must be
3233 * > 1. Consequently, the next_chunk code
3234 * will not rotate the pv_chunks list.
3238 mtx_unlock(&pv_chunks_mutex);
3241 * A pv_chunk can only be removed from the pc_lru list
3242 * when both pc_chunks_mutex is owned and the
3243 * corresponding pmap is locked.
3245 if (pmap != next_pmap) {
3246 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
3249 /* Avoid deadlock and lock recursion. */
3250 if (pmap > locked_pmap) {
3251 RELEASE_PV_LIST_LOCK(lockp);
3254 pmap_delayed_invl_started();
3255 mtx_lock(&pv_chunks_mutex);
3257 } else if (pmap != locked_pmap) {
3258 if (PMAP_TRYLOCK(pmap)) {
3260 pmap_delayed_invl_started();
3261 mtx_lock(&pv_chunks_mutex);
3264 pmap = NULL; /* pmap is not locked */
3265 mtx_lock(&pv_chunks_mutex);
3266 pc = TAILQ_NEXT(pc_marker, pc_lru);
3268 pc->pc_pmap != next_pmap)
3272 } else if (start_di)
3273 pmap_delayed_invl_started();
3274 PG_G = pmap_global_bit(pmap);
3275 PG_A = pmap_accessed_bit(pmap);
3276 PG_M = pmap_modified_bit(pmap);
3277 PG_RW = pmap_rw_bit(pmap);
3281 * Destroy every non-wired, 4 KB page mapping in the chunk.
3284 for (field = 0; field < _NPCM; field++) {
3285 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
3286 inuse != 0; inuse &= ~(1UL << bit)) {
3288 pv = &pc->pc_pventry[field * 64 + bit];
3290 pde = pmap_pde(pmap, va);
3291 if ((*pde & PG_PS) != 0)
3293 pte = pmap_pde_to_pte(pde, va);
3294 if ((*pte & PG_W) != 0)
3296 tpte = pte_load_clear(pte);
3297 if ((tpte & PG_G) != 0)
3298 pmap_invalidate_page(pmap, va);
3299 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3300 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3302 if ((tpte & PG_A) != 0)
3303 vm_page_aflag_set(m, PGA_REFERENCED);
3304 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3305 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3307 if (TAILQ_EMPTY(&m->md.pv_list) &&
3308 (m->flags & PG_FICTITIOUS) == 0) {
3309 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3310 if (TAILQ_EMPTY(&pvh->pv_list)) {
3311 vm_page_aflag_clear(m,
3315 pmap_delayed_invl_page(m);
3316 pc->pc_map[field] |= 1UL << bit;
3317 pmap_unuse_pt(pmap, va, *pde, &free);
3322 mtx_lock(&pv_chunks_mutex);
3325 /* Every freed mapping is for a 4 KB page. */
3326 pmap_resident_count_dec(pmap, freed);
3327 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
3328 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
3329 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
3330 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3331 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
3332 pc->pc_map[2] == PC_FREE2) {
3333 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3334 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3335 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3336 /* Entire chunk is free; return it. */
3337 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3338 dump_drop_page(m_pc->phys_addr);
3339 mtx_lock(&pv_chunks_mutex);
3340 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3343 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3344 mtx_lock(&pv_chunks_mutex);
3345 /* One freed pv entry in locked_pmap is sufficient. */
3346 if (pmap == locked_pmap)
3349 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3350 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
3351 if (active_reclaims == 1 && pmap != NULL) {
3353 * Rotate the pv chunks list so that we do not
3354 * scan the same pv chunks that could not be
3355 * freed (because they contained a wired
3356 * and/or superpage mapping) on every
3357 * invocation of reclaim_pv_chunk().
3359 while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
3360 MPASS(pc->pc_pmap != NULL);
3361 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3362 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3366 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3367 TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
3369 mtx_unlock(&pv_chunks_mutex);
3370 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
3371 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
3372 m_pc = SLIST_FIRST(&free);
3373 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3374 /* Recycle a freed page table page. */
3375 m_pc->wire_count = 1;
3377 vm_page_free_pages_toq(&free, true);
3382 * free the pv_entry back to the free list
3385 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3387 struct pv_chunk *pc;
3388 int idx, field, bit;
3390 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3391 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3392 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3393 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3394 pc = pv_to_chunk(pv);
3395 idx = pv - &pc->pc_pventry[0];
3398 pc->pc_map[field] |= 1ul << bit;
3399 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3400 pc->pc_map[2] != PC_FREE2) {
3401 /* 98% of the time, pc is already at the head of the list. */
3402 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3403 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3404 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3408 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3413 free_pv_chunk(struct pv_chunk *pc)
3417 mtx_lock(&pv_chunks_mutex);
3418 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3419 mtx_unlock(&pv_chunks_mutex);
3420 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3421 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3422 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3423 /* entire chunk is free, return it */
3424 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3425 dump_drop_page(m->phys_addr);
3426 vm_page_unwire(m, PQ_NONE);
3431 * Returns a new PV entry, allocating a new PV chunk from the system when
3432 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3433 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3436 * The given PV list lock may be released.
3439 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3443 struct pv_chunk *pc;
3446 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3447 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3449 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3451 for (field = 0; field < _NPCM; field++) {
3452 if (pc->pc_map[field]) {
3453 bit = bsfq(pc->pc_map[field]);
3457 if (field < _NPCM) {
3458 pv = &pc->pc_pventry[field * 64 + bit];
3459 pc->pc_map[field] &= ~(1ul << bit);
3460 /* If this was the last item, move it to tail */
3461 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3462 pc->pc_map[2] == 0) {
3463 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3464 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3467 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3468 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3472 /* No free items, allocate another chunk */
3473 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3476 if (lockp == NULL) {
3477 PV_STAT(pc_chunk_tryfail++);
3480 m = reclaim_pv_chunk(pmap, lockp);
3484 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3485 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3486 dump_add_page(m->phys_addr);
3487 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3489 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3490 pc->pc_map[1] = PC_FREE1;
3491 pc->pc_map[2] = PC_FREE2;
3492 mtx_lock(&pv_chunks_mutex);
3493 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3494 mtx_unlock(&pv_chunks_mutex);
3495 pv = &pc->pc_pventry[0];
3496 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3497 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3498 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3503 * Returns the number of one bits within the given PV chunk map.
3505 * The erratas for Intel processors state that "POPCNT Instruction May
3506 * Take Longer to Execute Than Expected". It is believed that the
3507 * issue is the spurious dependency on the destination register.
3508 * Provide a hint to the register rename logic that the destination
3509 * value is overwritten, by clearing it, as suggested in the
3510 * optimization manual. It should be cheap for unaffected processors
3513 * Reference numbers for erratas are
3514 * 4th Gen Core: HSD146
3515 * 5th Gen Core: BDM85
3516 * 6th Gen Core: SKL029
3519 popcnt_pc_map_pq(uint64_t *map)
3523 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3524 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3525 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3526 : "=&r" (result), "=&r" (tmp)
3527 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3532 * Ensure that the number of spare PV entries in the specified pmap meets or
3533 * exceeds the given count, "needed".
3535 * The given PV list lock may be released.
3538 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3540 struct pch new_tail;
3541 struct pv_chunk *pc;
3546 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3547 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3550 * Newly allocated PV chunks must be stored in a private list until
3551 * the required number of PV chunks have been allocated. Otherwise,
3552 * reclaim_pv_chunk() could recycle one of these chunks. In
3553 * contrast, these chunks must be added to the pmap upon allocation.
3555 TAILQ_INIT(&new_tail);
3558 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3560 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3561 bit_count((bitstr_t *)pc->pc_map, 0,
3562 sizeof(pc->pc_map) * NBBY, &free);
3565 free = popcnt_pc_map_pq(pc->pc_map);
3569 if (avail >= needed)
3572 for (reclaimed = false; avail < needed; avail += _NPCPV) {
3573 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3576 m = reclaim_pv_chunk(pmap, lockp);
3581 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3582 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3583 dump_add_page(m->phys_addr);
3584 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3586 pc->pc_map[0] = PC_FREE0;
3587 pc->pc_map[1] = PC_FREE1;
3588 pc->pc_map[2] = PC_FREE2;
3589 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3590 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3591 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3594 * The reclaim might have freed a chunk from the current pmap.
3595 * If that chunk contained available entries, we need to
3596 * re-count the number of available entries.
3601 if (!TAILQ_EMPTY(&new_tail)) {
3602 mtx_lock(&pv_chunks_mutex);
3603 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3604 mtx_unlock(&pv_chunks_mutex);
3609 * First find and then remove the pv entry for the specified pmap and virtual
3610 * address from the specified pv list. Returns the pv entry if found and NULL
3611 * otherwise. This operation can be performed on pv lists for either 4KB or
3612 * 2MB page mappings.
3614 static __inline pv_entry_t
3615 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3619 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3620 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3621 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3630 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3631 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3632 * entries for each of the 4KB page mappings.
3635 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3636 struct rwlock **lockp)
3638 struct md_page *pvh;
3639 struct pv_chunk *pc;
3641 vm_offset_t va_last;
3645 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3646 KASSERT((pa & PDRMASK) == 0,
3647 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3648 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3651 * Transfer the 2mpage's pv entry for this mapping to the first
3652 * page's pv list. Once this transfer begins, the pv list lock
3653 * must not be released until the last pv entry is reinstantiated.
3655 pvh = pa_to_pvh(pa);
3656 va = trunc_2mpage(va);
3657 pv = pmap_pvh_remove(pvh, pmap, va);
3658 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3659 m = PHYS_TO_VM_PAGE(pa);
3660 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3662 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3663 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3664 va_last = va + NBPDR - PAGE_SIZE;
3666 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3667 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3668 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3669 for (field = 0; field < _NPCM; field++) {
3670 while (pc->pc_map[field]) {
3671 bit = bsfq(pc->pc_map[field]);
3672 pc->pc_map[field] &= ~(1ul << bit);
3673 pv = &pc->pc_pventry[field * 64 + bit];
3677 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3678 ("pmap_pv_demote_pde: page %p is not managed", m));
3679 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3685 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3686 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3689 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3690 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3691 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3693 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3694 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3697 #if VM_NRESERVLEVEL > 0
3699 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3700 * replace the many pv entries for the 4KB page mappings by a single pv entry
3701 * for the 2MB page mapping.
3704 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3705 struct rwlock **lockp)
3707 struct md_page *pvh;
3709 vm_offset_t va_last;
3712 KASSERT((pa & PDRMASK) == 0,
3713 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3714 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3717 * Transfer the first page's pv entry for this mapping to the 2mpage's
3718 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3719 * a transfer avoids the possibility that get_pv_entry() calls
3720 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3721 * mappings that is being promoted.
3723 m = PHYS_TO_VM_PAGE(pa);
3724 va = trunc_2mpage(va);
3725 pv = pmap_pvh_remove(&m->md, pmap, va);
3726 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3727 pvh = pa_to_pvh(pa);
3728 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3730 /* Free the remaining NPTEPG - 1 pv entries. */
3731 va_last = va + NBPDR - PAGE_SIZE;
3735 pmap_pvh_free(&m->md, pmap, va);
3736 } while (va < va_last);
3738 #endif /* VM_NRESERVLEVEL > 0 */
3741 * First find and then destroy the pv entry for the specified pmap and virtual
3742 * address. This operation can be performed on pv lists for either 4KB or 2MB
3746 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3750 pv = pmap_pvh_remove(pvh, pmap, va);
3751 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3752 free_pv_entry(pmap, pv);
3756 * Conditionally create the PV entry for a 4KB page mapping if the required
3757 * memory can be allocated without resorting to reclamation.
3760 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3761 struct rwlock **lockp)
3765 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3766 /* Pass NULL instead of the lock pointer to disable reclamation. */
3767 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3769 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3770 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3778 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3779 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3780 * false if the PV entry cannot be allocated without resorting to reclamation.
3783 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
3784 struct rwlock **lockp)
3786 struct md_page *pvh;
3790 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3791 /* Pass NULL instead of the lock pointer to disable reclamation. */
3792 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3793 NULL : lockp)) == NULL)
3796 pa = pde & PG_PS_FRAME;
3797 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3798 pvh = pa_to_pvh(pa);
3799 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3805 * Fills a page table page with mappings to consecutive physical pages.
3808 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3812 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3814 newpte += PAGE_SIZE;
3819 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3820 * mapping is invalidated.
3823 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3825 struct rwlock *lock;
3829 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3836 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3837 struct rwlock **lockp)
3839 pd_entry_t newpde, oldpde;
3840 pt_entry_t *firstpte, newpte;
3841 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3844 struct spglist free;
3848 PG_G = pmap_global_bit(pmap);
3849 PG_A = pmap_accessed_bit(pmap);
3850 PG_M = pmap_modified_bit(pmap);
3851 PG_RW = pmap_rw_bit(pmap);
3852 PG_V = pmap_valid_bit(pmap);
3853 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3855 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3857 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3858 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3859 if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
3861 KASSERT((oldpde & PG_W) == 0,
3862 ("pmap_demote_pde: page table page for a wired mapping"
3866 * Invalidate the 2MB page mapping and return "failure" if the
3867 * mapping was never accessed or the allocation of the new
3868 * page table page fails. If the 2MB page mapping belongs to
3869 * the direct map region of the kernel's address space, then
3870 * the page allocation request specifies the highest possible
3871 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3872 * normal. Page table pages are preallocated for every other
3873 * part of the kernel address space, so the direct map region
3874 * is the only part of the kernel address space that must be
3877 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3878 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3879 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3880 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3882 sva = trunc_2mpage(va);
3883 pmap_remove_pde(pmap, pde, sva, &free, lockp);
3884 if ((oldpde & PG_G) == 0)
3885 pmap_invalidate_pde_page(pmap, sva, oldpde);
3886 vm_page_free_pages_toq(&free, true);
3887 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3888 " in pmap %p", va, pmap);
3891 if (va < VM_MAXUSER_ADDRESS)
3892 pmap_resident_count_inc(pmap, 1);
3894 mptepa = VM_PAGE_TO_PHYS(mpte);
3895 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3896 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3897 KASSERT((oldpde & PG_A) != 0,
3898 ("pmap_demote_pde: oldpde is missing PG_A"));
3899 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3900 ("pmap_demote_pde: oldpde is missing PG_M"));
3901 newpte = oldpde & ~PG_PS;
3902 newpte = pmap_swap_pat(pmap, newpte);
3905 * If the page table page is new, initialize it.
3907 if (mpte->wire_count == 1) {
3908 mpte->wire_count = NPTEPG;
3909 pmap_fill_ptp(firstpte, newpte);
3911 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3912 ("pmap_demote_pde: firstpte and newpte map different physical"
3916 * If the mapping has changed attributes, update the page table
3919 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3920 pmap_fill_ptp(firstpte, newpte);
3923 * The spare PV entries must be reserved prior to demoting the
3924 * mapping, that is, prior to changing the PDE. Otherwise, the state
3925 * of the PDE and the PV lists will be inconsistent, which can result
3926 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3927 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3928 * PV entry for the 2MB page mapping that is being demoted.
3930 if ((oldpde & PG_MANAGED) != 0)
3931 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3934 * Demote the mapping. This pmap is locked. The old PDE has
3935 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3936 * set. Thus, there is no danger of a race with another
3937 * processor changing the setting of PG_A and/or PG_M between
3938 * the read above and the store below.
3940 if (workaround_erratum383)
3941 pmap_update_pde(pmap, va, pde, newpde);
3943 pde_store(pde, newpde);
3946 * Invalidate a stale recursive mapping of the page table page.
3948 if (va >= VM_MAXUSER_ADDRESS)
3949 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3952 * Demote the PV entry.
3954 if ((oldpde & PG_MANAGED) != 0)
3955 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3957 atomic_add_long(&pmap_pde_demotions, 1);
3958 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3959 " in pmap %p", va, pmap);
3964 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3967 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3973 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3974 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3975 mpte = pmap_remove_pt_page(pmap, va);
3977 panic("pmap_remove_kernel_pde: Missing pt page.");
3979 mptepa = VM_PAGE_TO_PHYS(mpte);
3980 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3983 * Initialize the page table page.
3985 pagezero((void *)PHYS_TO_DMAP(mptepa));
3988 * Demote the mapping.
3990 if (workaround_erratum383)
3991 pmap_update_pde(pmap, va, pde, newpde);
3993 pde_store(pde, newpde);
3996 * Invalidate a stale recursive mapping of the page table page.
3998 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
4002 * pmap_remove_pde: do the things to unmap a superpage in a process
4005 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
4006 struct spglist *free, struct rwlock **lockp)
4008 struct md_page *pvh;
4010 vm_offset_t eva, va;
4012 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
4014 PG_G = pmap_global_bit(pmap);
4015 PG_A = pmap_accessed_bit(pmap);
4016 PG_M = pmap_modified_bit(pmap);
4017 PG_RW = pmap_rw_bit(pmap);
4019 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4020 KASSERT((sva & PDRMASK) == 0,
4021 ("pmap_remove_pde: sva is not 2mpage aligned"));
4022 oldpde = pte_load_clear(pdq);
4024 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
4025 if ((oldpde & PG_G) != 0)
4026 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4027 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
4028 if (oldpde & PG_MANAGED) {
4029 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
4030 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
4031 pmap_pvh_free(pvh, pmap, sva);
4033 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4034 va < eva; va += PAGE_SIZE, m++) {
4035 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
4038 vm_page_aflag_set(m, PGA_REFERENCED);
4039 if (TAILQ_EMPTY(&m->md.pv_list) &&
4040 TAILQ_EMPTY(&pvh->pv_list))
4041 vm_page_aflag_clear(m, PGA_WRITEABLE);
4042 pmap_delayed_invl_page(m);
4045 if (pmap == kernel_pmap) {
4046 pmap_remove_kernel_pde(pmap, pdq, sva);
4048 mpte = pmap_remove_pt_page(pmap, sva);
4050 pmap_resident_count_dec(pmap, 1);
4051 KASSERT(mpte->wire_count == NPTEPG,
4052 ("pmap_remove_pde: pte page wire count error"));
4053 mpte->wire_count = 0;
4054 pmap_add_delayed_free_list(mpte, free, FALSE);
4057 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
4061 * pmap_remove_pte: do the things to unmap a page in a process
4064 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
4065 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
4067 struct md_page *pvh;
4068 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
4071 PG_A = pmap_accessed_bit(pmap);
4072 PG_M = pmap_modified_bit(pmap);
4073 PG_RW = pmap_rw_bit(pmap);
4075 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4076 oldpte = pte_load_clear(ptq);
4078 pmap->pm_stats.wired_count -= 1;
4079 pmap_resident_count_dec(pmap, 1);
4080 if (oldpte & PG_MANAGED) {
4081 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
4082 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4085 vm_page_aflag_set(m, PGA_REFERENCED);
4086 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
4087 pmap_pvh_free(&m->md, pmap, va);
4088 if (TAILQ_EMPTY(&m->md.pv_list) &&
4089 (m->flags & PG_FICTITIOUS) == 0) {
4090 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4091 if (TAILQ_EMPTY(&pvh->pv_list))
4092 vm_page_aflag_clear(m, PGA_WRITEABLE);
4094 pmap_delayed_invl_page(m);
4096 return (pmap_unuse_pt(pmap, va, ptepde, free));
4100 * Remove a single page from a process address space
4103 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
4104 struct spglist *free)
4106 struct rwlock *lock;
4107 pt_entry_t *pte, PG_V;
4109 PG_V = pmap_valid_bit(pmap);
4110 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4111 if ((*pde & PG_V) == 0)
4113 pte = pmap_pde_to_pte(pde, va);
4114 if ((*pte & PG_V) == 0)
4117 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
4120 pmap_invalidate_page(pmap, va);
4124 * Removes the specified range of addresses from the page table page.
4127 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
4128 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
4130 pt_entry_t PG_G, *pte;
4134 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4135 PG_G = pmap_global_bit(pmap);
4138 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
4142 pmap_invalidate_range(pmap, va, sva);
4147 if ((*pte & PG_G) == 0)
4151 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
4157 pmap_invalidate_range(pmap, va, sva);
4162 * Remove the given range of addresses from the specified map.
4164 * It is assumed that the start and end are properly
4165 * rounded to the page size.
4168 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4170 struct rwlock *lock;
4171 vm_offset_t va_next;
4172 pml4_entry_t *pml4e;
4174 pd_entry_t ptpaddr, *pde;
4175 pt_entry_t PG_G, PG_V;
4176 struct spglist free;
4179 PG_G = pmap_global_bit(pmap);
4180 PG_V = pmap_valid_bit(pmap);
4183 * Perform an unsynchronized read. This is, however, safe.
4185 if (pmap->pm_stats.resident_count == 0)
4191 pmap_delayed_invl_started();
4195 * special handling of removing one page. a very
4196 * common operation and easy to short circuit some
4199 if (sva + PAGE_SIZE == eva) {
4200 pde = pmap_pde(pmap, sva);
4201 if (pde && (*pde & PG_PS) == 0) {
4202 pmap_remove_page(pmap, sva, pde, &free);
4208 for (; sva < eva; sva = va_next) {
4210 if (pmap->pm_stats.resident_count == 0)
4213 pml4e = pmap_pml4e(pmap, sva);
4214 if ((*pml4e & PG_V) == 0) {
4215 va_next = (sva + NBPML4) & ~PML4MASK;
4221 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4222 if ((*pdpe & PG_V) == 0) {
4223 va_next = (sva + NBPDP) & ~PDPMASK;
4230 * Calculate index for next page table.
4232 va_next = (sva + NBPDR) & ~PDRMASK;
4236 pde = pmap_pdpe_to_pde(pdpe, sva);
4240 * Weed out invalid mappings.
4246 * Check for large page.
4248 if ((ptpaddr & PG_PS) != 0) {
4250 * Are we removing the entire large page? If not,
4251 * demote the mapping and fall through.
4253 if (sva + NBPDR == va_next && eva >= va_next) {
4255 * The TLB entry for a PG_G mapping is
4256 * invalidated by pmap_remove_pde().
4258 if ((ptpaddr & PG_G) == 0)
4260 pmap_remove_pde(pmap, pde, sva, &free, &lock);
4262 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
4264 /* The large page mapping was destroyed. */
4271 * Limit our scan to either the end of the va represented
4272 * by the current page table page, or to the end of the
4273 * range being removed.
4278 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
4285 pmap_invalidate_all(pmap);
4287 pmap_delayed_invl_finished();
4288 vm_page_free_pages_toq(&free, true);
4292 * Routine: pmap_remove_all
4294 * Removes this physical page from
4295 * all physical maps in which it resides.
4296 * Reflects back modify bits to the pager.
4299 * Original versions of this routine were very
4300 * inefficient because they iteratively called
4301 * pmap_remove (slow...)
4305 pmap_remove_all(vm_page_t m)
4307 struct md_page *pvh;
4310 struct rwlock *lock;
4311 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
4314 struct spglist free;
4315 int pvh_gen, md_gen;
4317 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4318 ("pmap_remove_all: page %p is not managed", m));
4320 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4321 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
4322 pa_to_pvh(VM_PAGE_TO_PHYS(m));
4325 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
4327 if (!PMAP_TRYLOCK(pmap)) {
4328 pvh_gen = pvh->pv_gen;
4332 if (pvh_gen != pvh->pv_gen) {
4339 pde = pmap_pde(pmap, va);
4340 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
4343 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4345 if (!PMAP_TRYLOCK(pmap)) {
4346 pvh_gen = pvh->pv_gen;
4347 md_gen = m->md.pv_gen;
4351 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
4357 PG_A = pmap_accessed_bit(pmap);
4358 PG_M = pmap_modified_bit(pmap);
4359 PG_RW = pmap_rw_bit(pmap);
4360 pmap_resident_count_dec(pmap, 1);
4361 pde = pmap_pde(pmap, pv->pv_va);
4362 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
4363 " a 2mpage in page %p's pv list", m));
4364 pte = pmap_pde_to_pte(pde, pv->pv_va);
4365 tpte = pte_load_clear(pte);
4367 pmap->pm_stats.wired_count--;
4369 vm_page_aflag_set(m, PGA_REFERENCED);
4372 * Update the vm_page_t clean and reference bits.
4374 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4376 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
4377 pmap_invalidate_page(pmap, pv->pv_va);
4378 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4380 free_pv_entry(pmap, pv);
4383 vm_page_aflag_clear(m, PGA_WRITEABLE);
4385 pmap_delayed_invl_wait(m);
4386 vm_page_free_pages_toq(&free, true);
4390 * pmap_protect_pde: do the things to protect a 2mpage in a process
4393 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
4395 pd_entry_t newpde, oldpde;
4396 vm_offset_t eva, va;
4398 boolean_t anychanged;
4399 pt_entry_t PG_G, PG_M, PG_RW;
4401 PG_G = pmap_global_bit(pmap);
4402 PG_M = pmap_modified_bit(pmap);
4403 PG_RW = pmap_rw_bit(pmap);
4405 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4406 KASSERT((sva & PDRMASK) == 0,
4407 ("pmap_protect_pde: sva is not 2mpage aligned"));
4410 oldpde = newpde = *pde;
4411 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4412 (PG_MANAGED | PG_M | PG_RW)) {
4414 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4415 va < eva; va += PAGE_SIZE, m++)
4418 if ((prot & VM_PROT_WRITE) == 0)
4419 newpde &= ~(PG_RW | PG_M);
4420 if ((prot & VM_PROT_EXECUTE) == 0)
4422 if (newpde != oldpde) {
4424 * As an optimization to future operations on this PDE, clear
4425 * PG_PROMOTED. The impending invalidation will remove any
4426 * lingering 4KB page mappings from the TLB.
4428 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
4430 if ((oldpde & PG_G) != 0)
4431 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4435 return (anychanged);
4439 * Set the physical protection on the
4440 * specified range of this map as requested.
4443 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4445 vm_offset_t va_next;
4446 pml4_entry_t *pml4e;
4448 pd_entry_t ptpaddr, *pde;
4449 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4450 boolean_t anychanged;
4452 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4453 if (prot == VM_PROT_NONE) {
4454 pmap_remove(pmap, sva, eva);
4458 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4459 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4462 PG_G = pmap_global_bit(pmap);
4463 PG_M = pmap_modified_bit(pmap);
4464 PG_V = pmap_valid_bit(pmap);
4465 PG_RW = pmap_rw_bit(pmap);
4469 * Although this function delays and batches the invalidation
4470 * of stale TLB entries, it does not need to call
4471 * pmap_delayed_invl_started() and
4472 * pmap_delayed_invl_finished(), because it does not
4473 * ordinarily destroy mappings. Stale TLB entries from
4474 * protection-only changes need only be invalidated before the
4475 * pmap lock is released, because protection-only changes do
4476 * not destroy PV entries. Even operations that iterate over
4477 * a physical page's PV list of mappings, like
4478 * pmap_remove_write(), acquire the pmap lock for each
4479 * mapping. Consequently, for protection-only changes, the
4480 * pmap lock suffices to synchronize both page table and TLB
4483 * This function only destroys a mapping if pmap_demote_pde()
4484 * fails. In that case, stale TLB entries are immediately
4489 for (; sva < eva; sva = va_next) {
4491 pml4e = pmap_pml4e(pmap, sva);
4492 if ((*pml4e & PG_V) == 0) {
4493 va_next = (sva + NBPML4) & ~PML4MASK;
4499 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4500 if ((*pdpe & PG_V) == 0) {
4501 va_next = (sva + NBPDP) & ~PDPMASK;
4507 va_next = (sva + NBPDR) & ~PDRMASK;
4511 pde = pmap_pdpe_to_pde(pdpe, sva);
4515 * Weed out invalid mappings.
4521 * Check for large page.
4523 if ((ptpaddr & PG_PS) != 0) {
4525 * Are we protecting the entire large page? If not,
4526 * demote the mapping and fall through.
4528 if (sva + NBPDR == va_next && eva >= va_next) {
4530 * The TLB entry for a PG_G mapping is
4531 * invalidated by pmap_protect_pde().
4533 if (pmap_protect_pde(pmap, pde, sva, prot))
4536 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4538 * The large page mapping was destroyed.
4547 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4549 pt_entry_t obits, pbits;
4553 obits = pbits = *pte;
4554 if ((pbits & PG_V) == 0)
4557 if ((prot & VM_PROT_WRITE) == 0) {
4558 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4559 (PG_MANAGED | PG_M | PG_RW)) {
4560 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4563 pbits &= ~(PG_RW | PG_M);
4565 if ((prot & VM_PROT_EXECUTE) == 0)
4568 if (pbits != obits) {
4569 if (!atomic_cmpset_long(pte, obits, pbits))
4572 pmap_invalidate_page(pmap, sva);
4579 pmap_invalidate_all(pmap);
4583 #if VM_NRESERVLEVEL > 0
4585 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4586 * single page table page (PTP) to a single 2MB page mapping. For promotion
4587 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4588 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4589 * identical characteristics.
4592 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4593 struct rwlock **lockp)
4596 pt_entry_t *firstpte, oldpte, pa, *pte;
4597 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4601 PG_A = pmap_accessed_bit(pmap);
4602 PG_G = pmap_global_bit(pmap);
4603 PG_M = pmap_modified_bit(pmap);
4604 PG_V = pmap_valid_bit(pmap);
4605 PG_RW = pmap_rw_bit(pmap);
4606 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4608 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4611 * Examine the first PTE in the specified PTP. Abort if this PTE is
4612 * either invalid, unused, or does not map the first 4KB physical page
4613 * within a 2MB page.
4615 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4618 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4619 atomic_add_long(&pmap_pde_p_failures, 1);
4620 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4621 " in pmap %p", va, pmap);
4624 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4626 * When PG_M is already clear, PG_RW can be cleared without
4627 * a TLB invalidation.
4629 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4635 * Examine each of the other PTEs in the specified PTP. Abort if this
4636 * PTE maps an unexpected 4KB physical page or does not have identical
4637 * characteristics to the first PTE.
4639 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4640 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4643 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4644 atomic_add_long(&pmap_pde_p_failures, 1);
4645 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4646 " in pmap %p", va, pmap);
4649 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4651 * When PG_M is already clear, PG_RW can be cleared
4652 * without a TLB invalidation.
4654 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4657 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4658 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4659 (va & ~PDRMASK), pmap);
4661 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4662 atomic_add_long(&pmap_pde_p_failures, 1);
4663 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4664 " in pmap %p", va, pmap);
4671 * Save the page table page in its current state until the PDE
4672 * mapping the superpage is demoted by pmap_demote_pde() or
4673 * destroyed by pmap_remove_pde().
4675 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4676 KASSERT(mpte >= vm_page_array &&
4677 mpte < &vm_page_array[vm_page_array_size],
4678 ("pmap_promote_pde: page table page is out of range"));
4679 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4680 ("pmap_promote_pde: page table page's pindex is wrong"));
4681 if (pmap_insert_pt_page(pmap, mpte)) {
4682 atomic_add_long(&pmap_pde_p_failures, 1);
4684 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4690 * Promote the pv entries.
4692 if ((newpde & PG_MANAGED) != 0)
4693 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4696 * Propagate the PAT index to its proper position.
4698 newpde = pmap_swap_pat(pmap, newpde);
4701 * Map the superpage.
4703 if (workaround_erratum383)
4704 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4706 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
4708 atomic_add_long(&pmap_pde_promotions, 1);
4709 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4710 " in pmap %p", va, pmap);
4712 #endif /* VM_NRESERVLEVEL > 0 */
4715 * Insert the given physical page (p) at
4716 * the specified virtual address (v) in the
4717 * target physical map with the protection requested.
4719 * If specified, the page will be wired down, meaning
4720 * that the related pte can not be reclaimed.
4722 * NB: This is the only routine which MAY NOT lazy-evaluate
4723 * or lose information. That is, this routine must actually
4724 * insert this page into the given map NOW.
4726 * When destroying both a page table and PV entry, this function
4727 * performs the TLB invalidation before releasing the PV list
4728 * lock, so we do not need pmap_delayed_invl_page() calls here.
4731 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4732 u_int flags, int8_t psind)
4734 struct rwlock *lock;
4736 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4737 pt_entry_t newpte, origpte;
4744 PG_A = pmap_accessed_bit(pmap);
4745 PG_G = pmap_global_bit(pmap);
4746 PG_M = pmap_modified_bit(pmap);
4747 PG_V = pmap_valid_bit(pmap);
4748 PG_RW = pmap_rw_bit(pmap);
4750 va = trunc_page(va);
4751 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4752 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4753 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4755 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4756 va >= kmi.clean_eva,
4757 ("pmap_enter: managed mapping within the clean submap"));
4758 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4759 VM_OBJECT_ASSERT_LOCKED(m->object);
4760 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
4761 ("pmap_enter: flags %u has reserved bits set", flags));
4762 pa = VM_PAGE_TO_PHYS(m);
4763 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4764 if ((flags & VM_PROT_WRITE) != 0)
4766 if ((prot & VM_PROT_WRITE) != 0)
4768 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4769 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4770 if ((prot & VM_PROT_EXECUTE) == 0)
4772 if ((flags & PMAP_ENTER_WIRED) != 0)
4774 if (va < VM_MAXUSER_ADDRESS)
4776 if (pmap == kernel_pmap)
4778 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
4781 * Set modified bit gratuitously for writeable mappings if
4782 * the page is unmanaged. We do not want to take a fault
4783 * to do the dirty bit accounting for these mappings.
4785 if ((m->oflags & VPO_UNMANAGED) != 0) {
4786 if ((newpte & PG_RW) != 0)
4789 newpte |= PG_MANAGED;
4794 /* Assert the required virtual and physical alignment. */
4795 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
4796 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4797 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
4803 * In the case that a page table page is not
4804 * resident, we are creating it here.
4807 pde = pmap_pde(pmap, va);
4808 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4809 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4810 pte = pmap_pde_to_pte(pde, va);
4811 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4812 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4815 } else if (va < VM_MAXUSER_ADDRESS) {
4817 * Here if the pte page isn't mapped, or if it has been
4820 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4821 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4822 nosleep ? NULL : &lock);
4823 if (mpte == NULL && nosleep) {
4824 rv = KERN_RESOURCE_SHORTAGE;
4829 panic("pmap_enter: invalid page directory va=%#lx", va);
4835 * Is the specified virtual address already mapped?
4837 if ((origpte & PG_V) != 0) {
4839 * Wiring change, just update stats. We don't worry about
4840 * wiring PT pages as they remain resident as long as there
4841 * are valid mappings in them. Hence, if a user page is wired,
4842 * the PT page will be also.
4844 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4845 pmap->pm_stats.wired_count++;
4846 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4847 pmap->pm_stats.wired_count--;
4850 * Remove the extra PT page reference.
4854 KASSERT(mpte->wire_count > 0,
4855 ("pmap_enter: missing reference to page table page,"
4860 * Has the physical page changed?
4862 opa = origpte & PG_FRAME;
4865 * No, might be a protection or wiring change.
4867 if ((origpte & PG_MANAGED) != 0 &&
4868 (newpte & PG_RW) != 0)
4869 vm_page_aflag_set(m, PGA_WRITEABLE);
4870 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4876 * The physical page has changed. Temporarily invalidate
4877 * the mapping. This ensures that all threads sharing the
4878 * pmap keep a consistent view of the mapping, which is
4879 * necessary for the correct handling of COW faults. It
4880 * also permits reuse of the old mapping's PV entry,
4881 * avoiding an allocation.
4883 * For consistency, handle unmanaged mappings the same way.
4885 origpte = pte_load_clear(pte);
4886 KASSERT((origpte & PG_FRAME) == opa,
4887 ("pmap_enter: unexpected pa update for %#lx", va));
4888 if ((origpte & PG_MANAGED) != 0) {
4889 om = PHYS_TO_VM_PAGE(opa);
4892 * The pmap lock is sufficient to synchronize with
4893 * concurrent calls to pmap_page_test_mappings() and
4894 * pmap_ts_referenced().
4896 if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4898 if ((origpte & PG_A) != 0)
4899 vm_page_aflag_set(om, PGA_REFERENCED);
4900 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4901 pv = pmap_pvh_remove(&om->md, pmap, va);
4902 if ((newpte & PG_MANAGED) == 0)
4903 free_pv_entry(pmap, pv);
4904 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4905 TAILQ_EMPTY(&om->md.pv_list) &&
4906 ((om->flags & PG_FICTITIOUS) != 0 ||
4907 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4908 vm_page_aflag_clear(om, PGA_WRITEABLE);
4910 if ((origpte & PG_A) != 0)
4911 pmap_invalidate_page(pmap, va);
4915 * Increment the counters.
4917 if ((newpte & PG_W) != 0)
4918 pmap->pm_stats.wired_count++;
4919 pmap_resident_count_inc(pmap, 1);
4923 * Enter on the PV list if part of our managed memory.
4925 if ((newpte & PG_MANAGED) != 0) {
4927 pv = get_pv_entry(pmap, &lock);
4930 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4931 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4933 if ((newpte & PG_RW) != 0)
4934 vm_page_aflag_set(m, PGA_WRITEABLE);
4940 if ((origpte & PG_V) != 0) {
4942 origpte = pte_load_store(pte, newpte);
4943 KASSERT((origpte & PG_FRAME) == pa,
4944 ("pmap_enter: unexpected pa update for %#lx", va));
4945 if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
4947 if ((origpte & PG_MANAGED) != 0)
4951 * Although the PTE may still have PG_RW set, TLB
4952 * invalidation may nonetheless be required because
4953 * the PTE no longer has PG_M set.
4955 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4957 * This PTE change does not require TLB invalidation.
4961 if ((origpte & PG_A) != 0)
4962 pmap_invalidate_page(pmap, va);
4964 pte_store(pte, newpte);
4968 #if VM_NRESERVLEVEL > 0
4970 * If both the page table page and the reservation are fully
4971 * populated, then attempt promotion.
4973 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4974 pmap_ps_enabled(pmap) &&
4975 (m->flags & PG_FICTITIOUS) == 0 &&
4976 vm_reserv_level_iffullpop(m) == 0)
4977 pmap_promote_pde(pmap, pde, va, &lock);
4989 * Tries to create a read- and/or execute-only 2MB page mapping. Returns true
4990 * if successful. Returns false if (1) a page table page cannot be allocated
4991 * without sleeping, (2) a mapping already exists at the specified virtual
4992 * address, or (3) a PV entry cannot be allocated without reclaiming another
4996 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4997 struct rwlock **lockp)
5002 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5003 PG_V = pmap_valid_bit(pmap);
5004 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
5006 if ((m->oflags & VPO_UNMANAGED) == 0)
5007 newpde |= PG_MANAGED;
5008 if ((prot & VM_PROT_EXECUTE) == 0)
5010 if (va < VM_MAXUSER_ADDRESS)
5012 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
5013 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
5018 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
5019 * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
5020 * otherwise. Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
5021 * a mapping already exists at the specified virtual address. Returns
5022 * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
5023 * page allocation failed. Returns KERN_RESOURCE_SHORTAGE if
5024 * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
5026 * The parameter "m" is only used when creating a managed, writeable mapping.
5029 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
5030 vm_page_t m, struct rwlock **lockp)
5032 struct spglist free;
5033 pd_entry_t oldpde, *pde;
5034 pt_entry_t PG_G, PG_RW, PG_V;
5037 PG_G = pmap_global_bit(pmap);
5038 PG_RW = pmap_rw_bit(pmap);
5039 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
5040 ("pmap_enter_pde: newpde is missing PG_M"));
5041 PG_V = pmap_valid_bit(pmap);
5042 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5044 if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
5045 NULL : lockp)) == NULL) {
5046 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5047 " in pmap %p", va, pmap);
5048 return (KERN_RESOURCE_SHORTAGE);
5050 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5051 pde = &pde[pmap_pde_index(va)];
5053 if ((oldpde & PG_V) != 0) {
5054 KASSERT(pdpg->wire_count > 1,
5055 ("pmap_enter_pde: pdpg's wire count is too low"));
5056 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
5058 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5059 " in pmap %p", va, pmap);
5060 return (KERN_FAILURE);
5062 /* Break the existing mapping(s). */
5064 if ((oldpde & PG_PS) != 0) {
5066 * The reference to the PD page that was acquired by
5067 * pmap_allocpde() ensures that it won't be freed.
5068 * However, if the PDE resulted from a promotion, then
5069 * a reserved PT page could be freed.
5071 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
5072 if ((oldpde & PG_G) == 0)
5073 pmap_invalidate_pde_page(pmap, va, oldpde);
5075 pmap_delayed_invl_started();
5076 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
5078 pmap_invalidate_all(pmap);
5079 pmap_delayed_invl_finished();
5081 vm_page_free_pages_toq(&free, true);
5082 if (va >= VM_MAXUSER_ADDRESS) {
5083 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
5084 if (pmap_insert_pt_page(pmap, mt)) {
5086 * XXX Currently, this can't happen because
5087 * we do not perform pmap_enter(psind == 1)
5088 * on the kernel pmap.
5090 panic("pmap_enter_pde: trie insert failed");
5093 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
5096 if ((newpde & PG_MANAGED) != 0) {
5098 * Abort this mapping if its PV entry could not be created.
5100 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
5102 if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
5104 * Although "va" is not mapped, paging-
5105 * structure caches could nonetheless have
5106 * entries that refer to the freed page table
5107 * pages. Invalidate those entries.
5109 pmap_invalidate_page(pmap, va);
5110 vm_page_free_pages_toq(&free, true);
5112 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5113 " in pmap %p", va, pmap);
5114 return (KERN_RESOURCE_SHORTAGE);
5116 if ((newpde & PG_RW) != 0) {
5117 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5118 vm_page_aflag_set(mt, PGA_WRITEABLE);
5123 * Increment counters.
5125 if ((newpde & PG_W) != 0)
5126 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
5127 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5130 * Map the superpage. (This is not a promoted mapping; there will not
5131 * be any lingering 4KB page mappings in the TLB.)
5133 pde_store(pde, newpde);
5135 atomic_add_long(&pmap_pde_mappings, 1);
5136 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
5137 " in pmap %p", va, pmap);
5138 return (KERN_SUCCESS);
5142 * Maps a sequence of resident pages belonging to the same object.
5143 * The sequence begins with the given page m_start. This page is
5144 * mapped at the given virtual address start. Each subsequent page is
5145 * mapped at a virtual address that is offset from start by the same
5146 * amount as the page is offset from m_start within the object. The
5147 * last page in the sequence is the page with the largest offset from
5148 * m_start that can be mapped at a virtual address less than the given
5149 * virtual address end. Not every virtual page between start and end
5150 * is mapped; only those for which a resident page exists with the
5151 * corresponding offset from m_start are mapped.
5154 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
5155 vm_page_t m_start, vm_prot_t prot)
5157 struct rwlock *lock;
5160 vm_pindex_t diff, psize;
5162 VM_OBJECT_ASSERT_LOCKED(m_start->object);
5164 psize = atop(end - start);
5169 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
5170 va = start + ptoa(diff);
5171 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
5172 m->psind == 1 && pmap_ps_enabled(pmap) &&
5173 pmap_enter_2mpage(pmap, va, m, prot, &lock))
5174 m = &m[NBPDR / PAGE_SIZE - 1];
5176 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
5178 m = TAILQ_NEXT(m, listq);
5186 * this code makes some *MAJOR* assumptions:
5187 * 1. Current pmap & pmap exists.
5190 * 4. No page table pages.
5191 * but is *MUCH* faster than pmap_enter...
5195 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
5197 struct rwlock *lock;
5201 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
5208 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
5209 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
5211 struct spglist free;
5212 pt_entry_t *pte, PG_V;
5215 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
5216 (m->oflags & VPO_UNMANAGED) != 0,
5217 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
5218 PG_V = pmap_valid_bit(pmap);
5219 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5222 * In the case that a page table page is not
5223 * resident, we are creating it here.
5225 if (va < VM_MAXUSER_ADDRESS) {
5226 vm_pindex_t ptepindex;
5230 * Calculate pagetable page index
5232 ptepindex = pmap_pde_pindex(va);
5233 if (mpte && (mpte->pindex == ptepindex)) {
5237 * Get the page directory entry
5239 ptepa = pmap_pde(pmap, va);
5242 * If the page table page is mapped, we just increment
5243 * the hold count, and activate it. Otherwise, we
5244 * attempt to allocate a page table page. If this
5245 * attempt fails, we don't retry. Instead, we give up.
5247 if (ptepa && (*ptepa & PG_V) != 0) {
5250 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
5254 * Pass NULL instead of the PV list lock
5255 * pointer, because we don't intend to sleep.
5257 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
5262 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
5263 pte = &pte[pmap_pte_index(va)];
5277 * Enter on the PV list if part of our managed memory.
5279 if ((m->oflags & VPO_UNMANAGED) == 0 &&
5280 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
5283 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
5285 * Although "va" is not mapped, paging-
5286 * structure caches could nonetheless have
5287 * entries that refer to the freed page table
5288 * pages. Invalidate those entries.
5290 pmap_invalidate_page(pmap, va);
5291 vm_page_free_pages_toq(&free, true);
5299 * Increment counters
5301 pmap_resident_count_inc(pmap, 1);
5303 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
5304 if ((prot & VM_PROT_EXECUTE) == 0)
5308 * Now validate mapping with RO protection
5310 if ((m->oflags & VPO_UNMANAGED) != 0)
5311 pte_store(pte, pa | PG_V | PG_U);
5313 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
5318 * Make a temporary mapping for a physical address. This is only intended
5319 * to be used for panic dumps.
5322 pmap_kenter_temporary(vm_paddr_t pa, int i)
5326 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
5327 pmap_kenter(va, pa);
5329 return ((void *)crashdumpmap);
5333 * This code maps large physical mmap regions into the
5334 * processor address space. Note that some shortcuts
5335 * are taken, but the code works.
5338 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
5339 vm_pindex_t pindex, vm_size_t size)
5342 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5343 vm_paddr_t pa, ptepa;
5347 PG_A = pmap_accessed_bit(pmap);
5348 PG_M = pmap_modified_bit(pmap);
5349 PG_V = pmap_valid_bit(pmap);
5350 PG_RW = pmap_rw_bit(pmap);
5352 VM_OBJECT_ASSERT_WLOCKED(object);
5353 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
5354 ("pmap_object_init_pt: non-device object"));
5355 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
5356 if (!pmap_ps_enabled(pmap))
5358 if (!vm_object_populate(object, pindex, pindex + atop(size)))
5360 p = vm_page_lookup(object, pindex);
5361 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5362 ("pmap_object_init_pt: invalid page %p", p));
5363 pat_mode = p->md.pat_mode;
5366 * Abort the mapping if the first page is not physically
5367 * aligned to a 2MB page boundary.
5369 ptepa = VM_PAGE_TO_PHYS(p);
5370 if (ptepa & (NBPDR - 1))
5374 * Skip the first page. Abort the mapping if the rest of
5375 * the pages are not physically contiguous or have differing
5376 * memory attributes.
5378 p = TAILQ_NEXT(p, listq);
5379 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
5381 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5382 ("pmap_object_init_pt: invalid page %p", p));
5383 if (pa != VM_PAGE_TO_PHYS(p) ||
5384 pat_mode != p->md.pat_mode)
5386 p = TAILQ_NEXT(p, listq);
5390 * Map using 2MB pages. Since "ptepa" is 2M aligned and
5391 * "size" is a multiple of 2M, adding the PAT setting to "pa"
5392 * will not affect the termination of this loop.
5395 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
5396 pa < ptepa + size; pa += NBPDR) {
5397 pdpg = pmap_allocpde(pmap, addr, NULL);
5400 * The creation of mappings below is only an
5401 * optimization. If a page directory page
5402 * cannot be allocated without blocking,
5403 * continue on to the next mapping rather than
5409 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5410 pde = &pde[pmap_pde_index(addr)];
5411 if ((*pde & PG_V) == 0) {
5412 pde_store(pde, pa | PG_PS | PG_M | PG_A |
5413 PG_U | PG_RW | PG_V);
5414 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5415 atomic_add_long(&pmap_pde_mappings, 1);
5417 /* Continue on if the PDE is already valid. */
5419 KASSERT(pdpg->wire_count > 0,
5420 ("pmap_object_init_pt: missing reference "
5421 "to page directory page, va: 0x%lx", addr));
5430 * Clear the wired attribute from the mappings for the specified range of
5431 * addresses in the given pmap. Every valid mapping within that range
5432 * must have the wired attribute set. In contrast, invalid mappings
5433 * cannot have the wired attribute set, so they are ignored.
5435 * The wired attribute of the page table entry is not a hardware
5436 * feature, so there is no need to invalidate any TLB entries.
5437 * Since pmap_demote_pde() for the wired entry must never fail,
5438 * pmap_delayed_invl_started()/finished() calls around the
5439 * function are not needed.
5442 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5444 vm_offset_t va_next;
5445 pml4_entry_t *pml4e;
5448 pt_entry_t *pte, PG_V;
5450 PG_V = pmap_valid_bit(pmap);
5452 for (; sva < eva; sva = va_next) {
5453 pml4e = pmap_pml4e(pmap, sva);
5454 if ((*pml4e & PG_V) == 0) {
5455 va_next = (sva + NBPML4) & ~PML4MASK;
5460 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5461 if ((*pdpe & PG_V) == 0) {
5462 va_next = (sva + NBPDP) & ~PDPMASK;
5467 va_next = (sva + NBPDR) & ~PDRMASK;
5470 pde = pmap_pdpe_to_pde(pdpe, sva);
5471 if ((*pde & PG_V) == 0)
5473 if ((*pde & PG_PS) != 0) {
5474 if ((*pde & PG_W) == 0)
5475 panic("pmap_unwire: pde %#jx is missing PG_W",
5479 * Are we unwiring the entire large page? If not,
5480 * demote the mapping and fall through.
5482 if (sva + NBPDR == va_next && eva >= va_next) {
5483 atomic_clear_long(pde, PG_W);
5484 pmap->pm_stats.wired_count -= NBPDR /
5487 } else if (!pmap_demote_pde(pmap, pde, sva))
5488 panic("pmap_unwire: demotion failed");
5492 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
5494 if ((*pte & PG_V) == 0)
5496 if ((*pte & PG_W) == 0)
5497 panic("pmap_unwire: pte %#jx is missing PG_W",
5501 * PG_W must be cleared atomically. Although the pmap
5502 * lock synchronizes access to PG_W, another processor
5503 * could be setting PG_M and/or PG_A concurrently.
5505 atomic_clear_long(pte, PG_W);
5506 pmap->pm_stats.wired_count--;
5513 * Copy the range specified by src_addr/len
5514 * from the source map to the range dst_addr/len
5515 * in the destination map.
5517 * This routine is only advisory and need not do anything.
5521 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5522 vm_offset_t src_addr)
5524 struct rwlock *lock;
5525 struct spglist free;
5527 vm_offset_t end_addr = src_addr + len;
5528 vm_offset_t va_next;
5529 vm_page_t dst_pdpg, dstmpte, srcmpte;
5530 pt_entry_t PG_A, PG_M, PG_V;
5532 if (dst_addr != src_addr)
5535 if (dst_pmap->pm_type != src_pmap->pm_type)
5539 * EPT page table entries that require emulation of A/D bits are
5540 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5541 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5542 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5543 * implementations flag an EPT misconfiguration for exec-only
5544 * mappings we skip this function entirely for emulated pmaps.
5546 if (pmap_emulate_ad_bits(dst_pmap))
5550 if (dst_pmap < src_pmap) {
5551 PMAP_LOCK(dst_pmap);
5552 PMAP_LOCK(src_pmap);
5554 PMAP_LOCK(src_pmap);
5555 PMAP_LOCK(dst_pmap);
5558 PG_A = pmap_accessed_bit(dst_pmap);
5559 PG_M = pmap_modified_bit(dst_pmap);
5560 PG_V = pmap_valid_bit(dst_pmap);
5562 for (addr = src_addr; addr < end_addr; addr = va_next) {
5563 pt_entry_t *src_pte, *dst_pte;
5564 pml4_entry_t *pml4e;
5566 pd_entry_t srcptepaddr, *pde;
5568 KASSERT(addr < UPT_MIN_ADDRESS,
5569 ("pmap_copy: invalid to pmap_copy page tables"));
5571 pml4e = pmap_pml4e(src_pmap, addr);
5572 if ((*pml4e & PG_V) == 0) {
5573 va_next = (addr + NBPML4) & ~PML4MASK;
5579 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5580 if ((*pdpe & PG_V) == 0) {
5581 va_next = (addr + NBPDP) & ~PDPMASK;
5587 va_next = (addr + NBPDR) & ~PDRMASK;
5591 pde = pmap_pdpe_to_pde(pdpe, addr);
5593 if (srcptepaddr == 0)
5596 if (srcptepaddr & PG_PS) {
5597 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5599 dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
5600 if (dst_pdpg == NULL)
5602 pde = (pd_entry_t *)
5603 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
5604 pde = &pde[pmap_pde_index(addr)];
5605 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5606 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
5607 PMAP_ENTER_NORECLAIM, &lock))) {
5608 *pde = srcptepaddr & ~PG_W;
5609 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5610 atomic_add_long(&pmap_pde_mappings, 1);
5612 dst_pdpg->wire_count--;
5616 srcptepaddr &= PG_FRAME;
5617 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5618 KASSERT(srcmpte->wire_count > 0,
5619 ("pmap_copy: source page table page is unused"));
5621 if (va_next > end_addr)
5624 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5625 src_pte = &src_pte[pmap_pte_index(addr)];
5627 while (addr < va_next) {
5631 * we only virtual copy managed pages
5633 if ((ptetemp & PG_MANAGED) != 0) {
5634 if (dstmpte != NULL &&
5635 dstmpte->pindex == pmap_pde_pindex(addr))
5636 dstmpte->wire_count++;
5637 else if ((dstmpte = pmap_allocpte(dst_pmap,
5638 addr, NULL)) == NULL)
5640 dst_pte = (pt_entry_t *)
5641 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5642 dst_pte = &dst_pte[pmap_pte_index(addr)];
5643 if (*dst_pte == 0 &&
5644 pmap_try_insert_pv_entry(dst_pmap, addr,
5645 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5648 * Clear the wired, modified, and
5649 * accessed (referenced) bits
5652 *dst_pte = ptetemp & ~(PG_W | PG_M |
5654 pmap_resident_count_inc(dst_pmap, 1);
5657 if (pmap_unwire_ptp(dst_pmap, addr,
5660 * Although "addr" is not
5661 * mapped, paging-structure
5662 * caches could nonetheless
5663 * have entries that refer to
5664 * the freed page table pages.
5665 * Invalidate those entries.
5667 pmap_invalidate_page(dst_pmap,
5669 vm_page_free_pages_toq(&free,
5674 if (dstmpte->wire_count >= srcmpte->wire_count)
5684 PMAP_UNLOCK(src_pmap);
5685 PMAP_UNLOCK(dst_pmap);
5689 * Zero the specified hardware page.
5692 pmap_zero_page(vm_page_t m)
5694 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5696 pagezero((void *)va);
5700 * Zero an an area within a single hardware page. off and size must not
5701 * cover an area beyond a single hardware page.
5704 pmap_zero_page_area(vm_page_t m, int off, int size)
5706 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5708 if (off == 0 && size == PAGE_SIZE)
5709 pagezero((void *)va);
5711 bzero((char *)va + off, size);
5715 * Copy 1 specified hardware page to another.
5718 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5720 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5721 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5723 pagecopy((void *)src, (void *)dst);
5726 int unmapped_buf_allowed = 1;
5729 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5730 vm_offset_t b_offset, int xfersize)
5734 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5738 while (xfersize > 0) {
5739 a_pg_offset = a_offset & PAGE_MASK;
5740 pages[0] = ma[a_offset >> PAGE_SHIFT];
5741 b_pg_offset = b_offset & PAGE_MASK;
5742 pages[1] = mb[b_offset >> PAGE_SHIFT];
5743 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5744 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5745 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5746 a_cp = (char *)vaddr[0] + a_pg_offset;
5747 b_cp = (char *)vaddr[1] + b_pg_offset;
5748 bcopy(a_cp, b_cp, cnt);
5749 if (__predict_false(mapped))
5750 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5758 * Returns true if the pmap's pv is one of the first
5759 * 16 pvs linked to from this page. This count may
5760 * be changed upwards or downwards in the future; it
5761 * is only necessary that true be returned for a small
5762 * subset of pmaps for proper page aging.
5765 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5767 struct md_page *pvh;
5768 struct rwlock *lock;
5773 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5774 ("pmap_page_exists_quick: page %p is not managed", m));
5776 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5778 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5779 if (PV_PMAP(pv) == pmap) {
5787 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5788 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5789 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5790 if (PV_PMAP(pv) == pmap) {
5804 * pmap_page_wired_mappings:
5806 * Return the number of managed mappings to the given physical page
5810 pmap_page_wired_mappings(vm_page_t m)
5812 struct rwlock *lock;
5813 struct md_page *pvh;
5817 int count, md_gen, pvh_gen;
5819 if ((m->oflags & VPO_UNMANAGED) != 0)
5821 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5825 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5827 if (!PMAP_TRYLOCK(pmap)) {
5828 md_gen = m->md.pv_gen;
5832 if (md_gen != m->md.pv_gen) {
5837 pte = pmap_pte(pmap, pv->pv_va);
5838 if ((*pte & PG_W) != 0)
5842 if ((m->flags & PG_FICTITIOUS) == 0) {
5843 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5844 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5846 if (!PMAP_TRYLOCK(pmap)) {
5847 md_gen = m->md.pv_gen;
5848 pvh_gen = pvh->pv_gen;
5852 if (md_gen != m->md.pv_gen ||
5853 pvh_gen != pvh->pv_gen) {
5858 pte = pmap_pde(pmap, pv->pv_va);
5859 if ((*pte & PG_W) != 0)
5869 * Returns TRUE if the given page is mapped individually or as part of
5870 * a 2mpage. Otherwise, returns FALSE.
5873 pmap_page_is_mapped(vm_page_t m)
5875 struct rwlock *lock;
5878 if ((m->oflags & VPO_UNMANAGED) != 0)
5880 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5882 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5883 ((m->flags & PG_FICTITIOUS) == 0 &&
5884 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5890 * Destroy all managed, non-wired mappings in the given user-space
5891 * pmap. This pmap cannot be active on any processor besides the
5894 * This function cannot be applied to the kernel pmap. Moreover, it
5895 * is not intended for general use. It is only to be used during
5896 * process termination. Consequently, it can be implemented in ways
5897 * that make it faster than pmap_remove(). First, it can more quickly
5898 * destroy mappings by iterating over the pmap's collection of PV
5899 * entries, rather than searching the page table. Second, it doesn't
5900 * have to test and clear the page table entries atomically, because
5901 * no processor is currently accessing the user address space. In
5902 * particular, a page table entry's dirty bit won't change state once
5903 * this function starts.
5905 * Although this function destroys all of the pmap's managed,
5906 * non-wired mappings, it can delay and batch the invalidation of TLB
5907 * entries without calling pmap_delayed_invl_started() and
5908 * pmap_delayed_invl_finished(). Because the pmap is not active on
5909 * any other processor, none of these TLB entries will ever be used
5910 * before their eventual invalidation. Consequently, there is no need
5911 * for either pmap_remove_all() or pmap_remove_write() to wait for
5912 * that eventual TLB invalidation.
5915 pmap_remove_pages(pmap_t pmap)
5918 pt_entry_t *pte, tpte;
5919 pt_entry_t PG_M, PG_RW, PG_V;
5920 struct spglist free;
5921 vm_page_t m, mpte, mt;
5923 struct md_page *pvh;
5924 struct pv_chunk *pc, *npc;
5925 struct rwlock *lock;
5927 uint64_t inuse, bitmask;
5928 int allfree, field, freed, idx;
5929 boolean_t superpage;
5933 * Assert that the given pmap is only active on the current
5934 * CPU. Unfortunately, we cannot block another CPU from
5935 * activating the pmap while this function is executing.
5937 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5940 cpuset_t other_cpus;
5942 other_cpus = all_cpus;
5944 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5945 CPU_AND(&other_cpus, &pmap->pm_active);
5947 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5952 PG_M = pmap_modified_bit(pmap);
5953 PG_V = pmap_valid_bit(pmap);
5954 PG_RW = pmap_rw_bit(pmap);
5958 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5961 for (field = 0; field < _NPCM; field++) {
5962 inuse = ~pc->pc_map[field] & pc_freemask[field];
5963 while (inuse != 0) {
5965 bitmask = 1UL << bit;
5966 idx = field * 64 + bit;
5967 pv = &pc->pc_pventry[idx];
5970 pte = pmap_pdpe(pmap, pv->pv_va);
5972 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5974 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5977 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5979 pte = &pte[pmap_pte_index(pv->pv_va)];
5983 * Keep track whether 'tpte' is a
5984 * superpage explicitly instead of
5985 * relying on PG_PS being set.
5987 * This is because PG_PS is numerically
5988 * identical to PG_PTE_PAT and thus a
5989 * regular page could be mistaken for
5995 if ((tpte & PG_V) == 0) {
5996 panic("bad pte va %lx pte %lx",
6001 * We cannot remove wired pages from a process' mapping at this time
6009 pa = tpte & PG_PS_FRAME;
6011 pa = tpte & PG_FRAME;
6013 m = PHYS_TO_VM_PAGE(pa);
6014 KASSERT(m->phys_addr == pa,
6015 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
6016 m, (uintmax_t)m->phys_addr,
6019 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
6020 m < &vm_page_array[vm_page_array_size],
6021 ("pmap_remove_pages: bad tpte %#jx",
6027 * Update the vm_page_t clean/reference bits.
6029 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6031 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6037 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
6040 pc->pc_map[field] |= bitmask;
6042 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
6043 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
6044 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6046 if (TAILQ_EMPTY(&pvh->pv_list)) {
6047 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6048 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
6049 TAILQ_EMPTY(&mt->md.pv_list))
6050 vm_page_aflag_clear(mt, PGA_WRITEABLE);
6052 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
6054 pmap_resident_count_dec(pmap, 1);
6055 KASSERT(mpte->wire_count == NPTEPG,
6056 ("pmap_remove_pages: pte page wire count error"));
6057 mpte->wire_count = 0;
6058 pmap_add_delayed_free_list(mpte, &free, FALSE);
6061 pmap_resident_count_dec(pmap, 1);
6062 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6064 if ((m->aflags & PGA_WRITEABLE) != 0 &&
6065 TAILQ_EMPTY(&m->md.pv_list) &&
6066 (m->flags & PG_FICTITIOUS) == 0) {
6067 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6068 if (TAILQ_EMPTY(&pvh->pv_list))
6069 vm_page_aflag_clear(m, PGA_WRITEABLE);
6072 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
6076 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
6077 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
6078 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
6080 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
6086 pmap_invalidate_all(pmap);
6088 vm_page_free_pages_toq(&free, true);
6092 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
6094 struct rwlock *lock;
6096 struct md_page *pvh;
6097 pt_entry_t *pte, mask;
6098 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6100 int md_gen, pvh_gen;
6104 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6107 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6109 if (!PMAP_TRYLOCK(pmap)) {
6110 md_gen = m->md.pv_gen;
6114 if (md_gen != m->md.pv_gen) {
6119 pte = pmap_pte(pmap, pv->pv_va);
6122 PG_M = pmap_modified_bit(pmap);
6123 PG_RW = pmap_rw_bit(pmap);
6124 mask |= PG_RW | PG_M;
6127 PG_A = pmap_accessed_bit(pmap);
6128 PG_V = pmap_valid_bit(pmap);
6129 mask |= PG_V | PG_A;
6131 rv = (*pte & mask) == mask;
6136 if ((m->flags & PG_FICTITIOUS) == 0) {
6137 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6138 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
6140 if (!PMAP_TRYLOCK(pmap)) {
6141 md_gen = m->md.pv_gen;
6142 pvh_gen = pvh->pv_gen;
6146 if (md_gen != m->md.pv_gen ||
6147 pvh_gen != pvh->pv_gen) {
6152 pte = pmap_pde(pmap, pv->pv_va);
6155 PG_M = pmap_modified_bit(pmap);
6156 PG_RW = pmap_rw_bit(pmap);
6157 mask |= PG_RW | PG_M;
6160 PG_A = pmap_accessed_bit(pmap);
6161 PG_V = pmap_valid_bit(pmap);
6162 mask |= PG_V | PG_A;
6164 rv = (*pte & mask) == mask;
6178 * Return whether or not the specified physical page was modified
6179 * in any physical maps.
6182 pmap_is_modified(vm_page_t m)
6185 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6186 ("pmap_is_modified: page %p is not managed", m));
6189 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6190 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
6191 * is clear, no PTEs can have PG_M set.
6193 VM_OBJECT_ASSERT_WLOCKED(m->object);
6194 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6196 return (pmap_page_test_mappings(m, FALSE, TRUE));
6200 * pmap_is_prefaultable:
6202 * Return whether or not the specified virtual address is eligible
6206 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
6209 pt_entry_t *pte, PG_V;
6212 PG_V = pmap_valid_bit(pmap);
6215 pde = pmap_pde(pmap, addr);
6216 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
6217 pte = pmap_pde_to_pte(pde, addr);
6218 rv = (*pte & PG_V) == 0;
6225 * pmap_is_referenced:
6227 * Return whether or not the specified physical page was referenced
6228 * in any physical maps.
6231 pmap_is_referenced(vm_page_t m)
6234 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6235 ("pmap_is_referenced: page %p is not managed", m));
6236 return (pmap_page_test_mappings(m, TRUE, FALSE));
6240 * Clear the write and modified bits in each of the given page's mappings.
6243 pmap_remove_write(vm_page_t m)
6245 struct md_page *pvh;
6247 struct rwlock *lock;
6248 pv_entry_t next_pv, pv;
6250 pt_entry_t oldpte, *pte, PG_M, PG_RW;
6252 int pvh_gen, md_gen;
6254 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6255 ("pmap_remove_write: page %p is not managed", m));
6258 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6259 * set by another thread while the object is locked. Thus,
6260 * if PGA_WRITEABLE is clear, no page table entries need updating.
6262 VM_OBJECT_ASSERT_WLOCKED(m->object);
6263 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6265 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6266 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6267 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6270 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6272 if (!PMAP_TRYLOCK(pmap)) {
6273 pvh_gen = pvh->pv_gen;
6277 if (pvh_gen != pvh->pv_gen) {
6283 PG_RW = pmap_rw_bit(pmap);
6285 pde = pmap_pde(pmap, va);
6286 if ((*pde & PG_RW) != 0)
6287 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6288 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6289 ("inconsistent pv lock %p %p for page %p",
6290 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6293 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6295 if (!PMAP_TRYLOCK(pmap)) {
6296 pvh_gen = pvh->pv_gen;
6297 md_gen = m->md.pv_gen;
6301 if (pvh_gen != pvh->pv_gen ||
6302 md_gen != m->md.pv_gen) {
6308 PG_M = pmap_modified_bit(pmap);
6309 PG_RW = pmap_rw_bit(pmap);
6310 pde = pmap_pde(pmap, pv->pv_va);
6311 KASSERT((*pde & PG_PS) == 0,
6312 ("pmap_remove_write: found a 2mpage in page %p's pv list",
6314 pte = pmap_pde_to_pte(pde, pv->pv_va);
6317 if (oldpte & PG_RW) {
6318 if (!atomic_cmpset_long(pte, oldpte, oldpte &
6321 if ((oldpte & PG_M) != 0)
6323 pmap_invalidate_page(pmap, pv->pv_va);
6328 vm_page_aflag_clear(m, PGA_WRITEABLE);
6329 pmap_delayed_invl_wait(m);
6332 static __inline boolean_t
6333 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
6336 if (!pmap_emulate_ad_bits(pmap))
6339 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
6342 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
6343 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
6344 * if the EPT_PG_WRITE bit is set.
6346 if ((pte & EPT_PG_WRITE) != 0)
6350 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
6352 if ((pte & EPT_PG_EXECUTE) == 0 ||
6353 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
6360 * pmap_ts_referenced:
6362 * Return a count of reference bits for a page, clearing those bits.
6363 * It is not necessary for every reference bit to be cleared, but it
6364 * is necessary that 0 only be returned when there are truly no
6365 * reference bits set.
6367 * As an optimization, update the page's dirty field if a modified bit is
6368 * found while counting reference bits. This opportunistic update can be
6369 * performed at low cost and can eliminate the need for some future calls
6370 * to pmap_is_modified(). However, since this function stops after
6371 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
6372 * dirty pages. Those dirty pages will only be detected by a future call
6373 * to pmap_is_modified().
6375 * A DI block is not needed within this function, because
6376 * invalidations are performed before the PV list lock is
6380 pmap_ts_referenced(vm_page_t m)
6382 struct md_page *pvh;
6385 struct rwlock *lock;
6386 pd_entry_t oldpde, *pde;
6387 pt_entry_t *pte, PG_A, PG_M, PG_RW;
6390 int cleared, md_gen, not_cleared, pvh_gen;
6391 struct spglist free;
6394 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6395 ("pmap_ts_referenced: page %p is not managed", m));
6398 pa = VM_PAGE_TO_PHYS(m);
6399 lock = PHYS_TO_PV_LIST_LOCK(pa);
6400 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
6404 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6405 goto small_mappings;
6411 if (!PMAP_TRYLOCK(pmap)) {
6412 pvh_gen = pvh->pv_gen;
6416 if (pvh_gen != pvh->pv_gen) {
6421 PG_A = pmap_accessed_bit(pmap);
6422 PG_M = pmap_modified_bit(pmap);
6423 PG_RW = pmap_rw_bit(pmap);
6425 pde = pmap_pde(pmap, pv->pv_va);
6427 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6429 * Although "oldpde" is mapping a 2MB page, because
6430 * this function is called at a 4KB page granularity,
6431 * we only update the 4KB page under test.
6435 if ((oldpde & PG_A) != 0) {
6437 * Since this reference bit is shared by 512 4KB
6438 * pages, it should not be cleared every time it is
6439 * tested. Apply a simple "hash" function on the
6440 * physical page number, the virtual superpage number,
6441 * and the pmap address to select one 4KB page out of
6442 * the 512 on which testing the reference bit will
6443 * result in clearing that reference bit. This
6444 * function is designed to avoid the selection of the
6445 * same 4KB page for every 2MB page mapping.
6447 * On demotion, a mapping that hasn't been referenced
6448 * is simply destroyed. To avoid the possibility of a
6449 * subsequent page fault on a demoted wired mapping,
6450 * always leave its reference bit set. Moreover,
6451 * since the superpage is wired, the current state of
6452 * its reference bit won't affect page replacement.
6454 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
6455 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
6456 (oldpde & PG_W) == 0) {
6457 if (safe_to_clear_referenced(pmap, oldpde)) {
6458 atomic_clear_long(pde, PG_A);
6459 pmap_invalidate_page(pmap, pv->pv_va);
6461 } else if (pmap_demote_pde_locked(pmap, pde,
6462 pv->pv_va, &lock)) {
6464 * Remove the mapping to a single page
6465 * so that a subsequent access may
6466 * repromote. Since the underlying
6467 * page table page is fully populated,
6468 * this removal never frees a page
6472 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6474 pte = pmap_pde_to_pte(pde, va);
6475 pmap_remove_pte(pmap, pte, va, *pde,
6477 pmap_invalidate_page(pmap, va);
6483 * The superpage mapping was removed
6484 * entirely and therefore 'pv' is no
6492 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6493 ("inconsistent pv lock %p %p for page %p",
6494 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6499 /* Rotate the PV list if it has more than one entry. */
6500 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6501 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6502 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6505 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6507 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6509 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6516 if (!PMAP_TRYLOCK(pmap)) {
6517 pvh_gen = pvh->pv_gen;
6518 md_gen = m->md.pv_gen;
6522 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6527 PG_A = pmap_accessed_bit(pmap);
6528 PG_M = pmap_modified_bit(pmap);
6529 PG_RW = pmap_rw_bit(pmap);
6530 pde = pmap_pde(pmap, pv->pv_va);
6531 KASSERT((*pde & PG_PS) == 0,
6532 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6534 pte = pmap_pde_to_pte(pde, pv->pv_va);
6535 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6537 if ((*pte & PG_A) != 0) {
6538 if (safe_to_clear_referenced(pmap, *pte)) {
6539 atomic_clear_long(pte, PG_A);
6540 pmap_invalidate_page(pmap, pv->pv_va);
6542 } else if ((*pte & PG_W) == 0) {
6544 * Wired pages cannot be paged out so
6545 * doing accessed bit emulation for
6546 * them is wasted effort. We do the
6547 * hard work for unwired pages only.
6549 pmap_remove_pte(pmap, pte, pv->pv_va,
6550 *pde, &free, &lock);
6551 pmap_invalidate_page(pmap, pv->pv_va);
6556 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6557 ("inconsistent pv lock %p %p for page %p",
6558 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6563 /* Rotate the PV list if it has more than one entry. */
6564 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6565 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6566 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6569 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6570 not_cleared < PMAP_TS_REFERENCED_MAX);
6573 vm_page_free_pages_toq(&free, true);
6574 return (cleared + not_cleared);
6578 * Apply the given advice to the specified range of addresses within the
6579 * given pmap. Depending on the advice, clear the referenced and/or
6580 * modified flags in each mapping and set the mapped page's dirty field.
6583 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6585 struct rwlock *lock;
6586 pml4_entry_t *pml4e;
6588 pd_entry_t oldpde, *pde;
6589 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6590 vm_offset_t va, va_next;
6592 boolean_t anychanged;
6594 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6598 * A/D bit emulation requires an alternate code path when clearing
6599 * the modified and accessed bits below. Since this function is
6600 * advisory in nature we skip it entirely for pmaps that require
6601 * A/D bit emulation.
6603 if (pmap_emulate_ad_bits(pmap))
6606 PG_A = pmap_accessed_bit(pmap);
6607 PG_G = pmap_global_bit(pmap);
6608 PG_M = pmap_modified_bit(pmap);
6609 PG_V = pmap_valid_bit(pmap);
6610 PG_RW = pmap_rw_bit(pmap);
6612 pmap_delayed_invl_started();
6614 for (; sva < eva; sva = va_next) {
6615 pml4e = pmap_pml4e(pmap, sva);
6616 if ((*pml4e & PG_V) == 0) {
6617 va_next = (sva + NBPML4) & ~PML4MASK;
6622 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6623 if ((*pdpe & PG_V) == 0) {
6624 va_next = (sva + NBPDP) & ~PDPMASK;
6629 va_next = (sva + NBPDR) & ~PDRMASK;
6632 pde = pmap_pdpe_to_pde(pdpe, sva);
6634 if ((oldpde & PG_V) == 0)
6636 else if ((oldpde & PG_PS) != 0) {
6637 if ((oldpde & PG_MANAGED) == 0)
6640 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6645 * The large page mapping was destroyed.
6651 * Unless the page mappings are wired, remove the
6652 * mapping to a single page so that a subsequent
6653 * access may repromote. Since the underlying page
6654 * table page is fully populated, this removal never
6655 * frees a page table page.
6657 if ((oldpde & PG_W) == 0) {
6658 pte = pmap_pde_to_pte(pde, sva);
6659 KASSERT((*pte & PG_V) != 0,
6660 ("pmap_advise: invalid PTE"));
6661 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6671 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6673 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6675 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6676 if (advice == MADV_DONTNEED) {
6678 * Future calls to pmap_is_modified()
6679 * can be avoided by making the page
6682 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6685 atomic_clear_long(pte, PG_M | PG_A);
6686 } else if ((*pte & PG_A) != 0)
6687 atomic_clear_long(pte, PG_A);
6691 if ((*pte & PG_G) != 0) {
6698 if (va != va_next) {
6699 pmap_invalidate_range(pmap, va, sva);
6704 pmap_invalidate_range(pmap, va, sva);
6707 pmap_invalidate_all(pmap);
6709 pmap_delayed_invl_finished();
6713 * Clear the modify bits on the specified physical page.
6716 pmap_clear_modify(vm_page_t m)
6718 struct md_page *pvh;
6720 pv_entry_t next_pv, pv;
6721 pd_entry_t oldpde, *pde;
6722 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6723 struct rwlock *lock;
6725 int md_gen, pvh_gen;
6727 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6728 ("pmap_clear_modify: page %p is not managed", m));
6729 VM_OBJECT_ASSERT_WLOCKED(m->object);
6730 KASSERT(!vm_page_xbusied(m),
6731 ("pmap_clear_modify: page %p is exclusive busied", m));
6734 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6735 * If the object containing the page is locked and the page is not
6736 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6738 if ((m->aflags & PGA_WRITEABLE) == 0)
6740 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6741 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6742 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6745 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6747 if (!PMAP_TRYLOCK(pmap)) {
6748 pvh_gen = pvh->pv_gen;
6752 if (pvh_gen != pvh->pv_gen) {
6757 PG_M = pmap_modified_bit(pmap);
6758 PG_V = pmap_valid_bit(pmap);
6759 PG_RW = pmap_rw_bit(pmap);
6761 pde = pmap_pde(pmap, va);
6763 if ((oldpde & PG_RW) != 0) {
6764 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6765 if ((oldpde & PG_W) == 0) {
6767 * Write protect the mapping to a
6768 * single page so that a subsequent
6769 * write access may repromote.
6771 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6773 pte = pmap_pde_to_pte(pde, va);
6775 if ((oldpte & PG_V) != 0) {
6776 while (!atomic_cmpset_long(pte,
6778 oldpte & ~(PG_M | PG_RW)))
6781 pmap_invalidate_page(pmap, va);
6788 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6790 if (!PMAP_TRYLOCK(pmap)) {
6791 md_gen = m->md.pv_gen;
6792 pvh_gen = pvh->pv_gen;
6796 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6801 PG_M = pmap_modified_bit(pmap);
6802 PG_RW = pmap_rw_bit(pmap);
6803 pde = pmap_pde(pmap, pv->pv_va);
6804 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6805 " a 2mpage in page %p's pv list", m));
6806 pte = pmap_pde_to_pte(pde, pv->pv_va);
6807 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6808 atomic_clear_long(pte, PG_M);
6809 pmap_invalidate_page(pmap, pv->pv_va);
6817 * Miscellaneous support routines follow
6820 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6821 static __inline void
6822 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6827 * The cache mode bits are all in the low 32-bits of the
6828 * PTE, so we can just spin on updating the low 32-bits.
6831 opte = *(u_int *)pte;
6832 npte = opte & ~mask;
6834 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6837 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6838 static __inline void
6839 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6844 * The cache mode bits are all in the low 32-bits of the
6845 * PDE, so we can just spin on updating the low 32-bits.
6848 opde = *(u_int *)pde;
6849 npde = opde & ~mask;
6851 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6855 * Map a set of physical memory pages into the kernel virtual
6856 * address space. Return a pointer to where it is mapped. This
6857 * routine is intended to be used for mapping device memory,
6861 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6863 struct pmap_preinit_mapping *ppim;
6864 vm_offset_t va, offset;
6868 offset = pa & PAGE_MASK;
6869 size = round_page(offset + size);
6870 pa = trunc_page(pa);
6872 if (!pmap_initialized) {
6874 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6875 ppim = pmap_preinit_mapping + i;
6876 if (ppim->va == 0) {
6880 ppim->va = virtual_avail;
6881 virtual_avail += size;
6887 panic("%s: too many preinit mappings", __func__);
6890 * If we have a preinit mapping, re-use it.
6892 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6893 ppim = pmap_preinit_mapping + i;
6894 if (ppim->pa == pa && ppim->sz == size &&
6896 return ((void *)(ppim->va + offset));
6899 * If the specified range of physical addresses fits within
6900 * the direct map window, use the direct map.
6902 if (pa < dmaplimit && pa + size < dmaplimit) {
6903 va = PHYS_TO_DMAP(pa);
6904 if (!pmap_change_attr(va, size, mode))
6905 return ((void *)(va + offset));
6907 va = kva_alloc(size);
6909 panic("%s: Couldn't allocate KVA", __func__);
6911 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6912 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6913 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6914 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6915 return ((void *)(va + offset));
6919 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6922 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6926 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6929 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6933 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6935 struct pmap_preinit_mapping *ppim;
6939 /* If we gave a direct map region in pmap_mapdev, do nothing */
6940 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6942 offset = va & PAGE_MASK;
6943 size = round_page(offset + size);
6944 va = trunc_page(va);
6945 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6946 ppim = pmap_preinit_mapping + i;
6947 if (ppim->va == va && ppim->sz == size) {
6948 if (pmap_initialized)
6954 if (va + size == virtual_avail)
6959 if (pmap_initialized)
6964 * Tries to demote a 1GB page mapping.
6967 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6969 pdp_entry_t newpdpe, oldpdpe;
6970 pd_entry_t *firstpde, newpde, *pde;
6971 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6975 PG_A = pmap_accessed_bit(pmap);
6976 PG_M = pmap_modified_bit(pmap);
6977 PG_V = pmap_valid_bit(pmap);
6978 PG_RW = pmap_rw_bit(pmap);
6980 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6982 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6983 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6984 if ((pdpg = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6985 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6986 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6987 " in pmap %p", va, pmap);
6990 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
6991 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
6992 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6993 KASSERT((oldpdpe & PG_A) != 0,
6994 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6995 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6996 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
7000 * Initialize the page directory page.
7002 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
7008 * Demote the mapping.
7013 * Invalidate a stale recursive mapping of the page directory page.
7015 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
7017 pmap_pdpe_demotions++;
7018 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
7019 " in pmap %p", va, pmap);
7024 * Sets the memory attribute for the specified page.
7027 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
7030 m->md.pat_mode = ma;
7033 * If "m" is a normal page, update its direct mapping. This update
7034 * can be relied upon to perform any cache operations that are
7035 * required for data coherence.
7037 if ((m->flags & PG_FICTITIOUS) == 0 &&
7038 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
7040 panic("memory attribute change on the direct map failed");
7044 * Changes the specified virtual address range's memory type to that given by
7045 * the parameter "mode". The specified virtual address range must be
7046 * completely contained within either the direct map or the kernel map. If
7047 * the virtual address range is contained within the kernel map, then the
7048 * memory type for each of the corresponding ranges of the direct map is also
7049 * changed. (The corresponding ranges of the direct map are those ranges that
7050 * map the same physical pages as the specified virtual address range.) These
7051 * changes to the direct map are necessary because Intel describes the
7052 * behavior of their processors as "undefined" if two or more mappings to the
7053 * same physical page have different memory types.
7055 * Returns zero if the change completed successfully, and either EINVAL or
7056 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
7057 * of the virtual address range was not mapped, and ENOMEM is returned if
7058 * there was insufficient memory available to complete the change. In the
7059 * latter case, the memory type may have been changed on some part of the
7060 * virtual address range or the direct map.
7063 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
7067 PMAP_LOCK(kernel_pmap);
7068 error = pmap_change_attr_locked(va, size, mode);
7069 PMAP_UNLOCK(kernel_pmap);
7074 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
7076 vm_offset_t base, offset, tmpva;
7077 vm_paddr_t pa_start, pa_end, pa_end1;
7081 int cache_bits_pte, cache_bits_pde, error;
7084 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
7085 base = trunc_page(va);
7086 offset = va & PAGE_MASK;
7087 size = round_page(offset + size);
7090 * Only supported on kernel virtual addresses, including the direct
7091 * map but excluding the recursive map.
7093 if (base < DMAP_MIN_ADDRESS)
7096 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
7097 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
7101 * Pages that aren't mapped aren't supported. Also break down 2MB pages
7102 * into 4KB pages if required.
7104 for (tmpva = base; tmpva < base + size; ) {
7105 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7106 if (pdpe == NULL || *pdpe == 0)
7108 if (*pdpe & PG_PS) {
7110 * If the current 1GB page already has the required
7111 * memory type, then we need not demote this page. Just
7112 * increment tmpva to the next 1GB page frame.
7114 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
7115 tmpva = trunc_1gpage(tmpva) + NBPDP;
7120 * If the current offset aligns with a 1GB page frame
7121 * and there is at least 1GB left within the range, then
7122 * we need not break down this page into 2MB pages.
7124 if ((tmpva & PDPMASK) == 0 &&
7125 tmpva + PDPMASK < base + size) {
7129 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
7132 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7137 * If the current 2MB page already has the required
7138 * memory type, then we need not demote this page. Just
7139 * increment tmpva to the next 2MB page frame.
7141 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
7142 tmpva = trunc_2mpage(tmpva) + NBPDR;
7147 * If the current offset aligns with a 2MB page frame
7148 * and there is at least 2MB left within the range, then
7149 * we need not break down this page into 4KB pages.
7151 if ((tmpva & PDRMASK) == 0 &&
7152 tmpva + PDRMASK < base + size) {
7156 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
7159 pte = pmap_pde_to_pte(pde, tmpva);
7167 * Ok, all the pages exist, so run through them updating their
7168 * cache mode if required.
7170 pa_start = pa_end = 0;
7171 for (tmpva = base; tmpva < base + size; ) {
7172 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7173 if (*pdpe & PG_PS) {
7174 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
7175 pmap_pde_attr(pdpe, cache_bits_pde,
7179 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7180 (*pdpe & PG_PS_FRAME) < dmaplimit) {
7181 if (pa_start == pa_end) {
7182 /* Start physical address run. */
7183 pa_start = *pdpe & PG_PS_FRAME;
7184 pa_end = pa_start + NBPDP;
7185 } else if (pa_end == (*pdpe & PG_PS_FRAME))
7188 /* Run ended, update direct map. */
7189 error = pmap_change_attr_locked(
7190 PHYS_TO_DMAP(pa_start),
7191 pa_end - pa_start, mode);
7194 /* Start physical address run. */
7195 pa_start = *pdpe & PG_PS_FRAME;
7196 pa_end = pa_start + NBPDP;
7199 tmpva = trunc_1gpage(tmpva) + NBPDP;
7202 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7204 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
7205 pmap_pde_attr(pde, cache_bits_pde,
7209 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7210 (*pde & PG_PS_FRAME) < dmaplimit) {
7211 if (pa_start == pa_end) {
7212 /* Start physical address run. */
7213 pa_start = *pde & PG_PS_FRAME;
7214 pa_end = pa_start + NBPDR;
7215 } else if (pa_end == (*pde & PG_PS_FRAME))
7218 /* Run ended, update direct map. */
7219 error = pmap_change_attr_locked(
7220 PHYS_TO_DMAP(pa_start),
7221 pa_end - pa_start, mode);
7224 /* Start physical address run. */
7225 pa_start = *pde & PG_PS_FRAME;
7226 pa_end = pa_start + NBPDR;
7229 tmpva = trunc_2mpage(tmpva) + NBPDR;
7231 pte = pmap_pde_to_pte(pde, tmpva);
7232 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
7233 pmap_pte_attr(pte, cache_bits_pte,
7237 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7238 (*pte & PG_FRAME) < dmaplimit) {
7239 if (pa_start == pa_end) {
7240 /* Start physical address run. */
7241 pa_start = *pte & PG_FRAME;
7242 pa_end = pa_start + PAGE_SIZE;
7243 } else if (pa_end == (*pte & PG_FRAME))
7244 pa_end += PAGE_SIZE;
7246 /* Run ended, update direct map. */
7247 error = pmap_change_attr_locked(
7248 PHYS_TO_DMAP(pa_start),
7249 pa_end - pa_start, mode);
7252 /* Start physical address run. */
7253 pa_start = *pte & PG_FRAME;
7254 pa_end = pa_start + PAGE_SIZE;
7260 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
7261 pa_end1 = MIN(pa_end, dmaplimit);
7262 if (pa_start != pa_end1)
7263 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
7264 pa_end1 - pa_start, mode);
7268 * Flush CPU caches if required to make sure any data isn't cached that
7269 * shouldn't be, etc.
7272 pmap_invalidate_range(kernel_pmap, base, tmpva);
7273 pmap_invalidate_cache_range(base, tmpva, FALSE);
7279 * Demotes any mapping within the direct map region that covers more than the
7280 * specified range of physical addresses. This range's size must be a power
7281 * of two and its starting address must be a multiple of its size. Since the
7282 * demotion does not change any attributes of the mapping, a TLB invalidation
7283 * is not mandatory. The caller may, however, request a TLB invalidation.
7286 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
7295 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
7296 KASSERT((base & (len - 1)) == 0,
7297 ("pmap_demote_DMAP: base is not a multiple of len"));
7298 if (len < NBPDP && base < dmaplimit) {
7299 va = PHYS_TO_DMAP(base);
7301 PMAP_LOCK(kernel_pmap);
7302 pdpe = pmap_pdpe(kernel_pmap, va);
7303 if ((*pdpe & X86_PG_V) == 0)
7304 panic("pmap_demote_DMAP: invalid PDPE");
7305 if ((*pdpe & PG_PS) != 0) {
7306 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
7307 panic("pmap_demote_DMAP: PDPE failed");
7311 pde = pmap_pdpe_to_pde(pdpe, va);
7312 if ((*pde & X86_PG_V) == 0)
7313 panic("pmap_demote_DMAP: invalid PDE");
7314 if ((*pde & PG_PS) != 0) {
7315 if (!pmap_demote_pde(kernel_pmap, pde, va))
7316 panic("pmap_demote_DMAP: PDE failed");
7320 if (changed && invalidate)
7321 pmap_invalidate_page(kernel_pmap, va);
7322 PMAP_UNLOCK(kernel_pmap);
7327 * perform the pmap work for mincore
7330 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
7333 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
7337 PG_A = pmap_accessed_bit(pmap);
7338 PG_M = pmap_modified_bit(pmap);
7339 PG_V = pmap_valid_bit(pmap);
7340 PG_RW = pmap_rw_bit(pmap);
7344 pdep = pmap_pde(pmap, addr);
7345 if (pdep != NULL && (*pdep & PG_V)) {
7346 if (*pdep & PG_PS) {
7348 /* Compute the physical address of the 4KB page. */
7349 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
7351 val = MINCORE_SUPER;
7353 pte = *pmap_pde_to_pte(pdep, addr);
7354 pa = pte & PG_FRAME;
7362 if ((pte & PG_V) != 0) {
7363 val |= MINCORE_INCORE;
7364 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7365 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
7366 if ((pte & PG_A) != 0)
7367 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
7369 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
7370 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
7371 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
7372 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
7373 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
7376 PA_UNLOCK_COND(*locked_pa);
7382 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
7384 uint32_t gen, new_gen, pcid_next;
7386 CRITICAL_ASSERT(curthread);
7387 gen = PCPU_GET(pcid_gen);
7388 if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN)
7389 return (pti ? 0 : CR3_PCID_SAVE);
7390 if (pmap->pm_pcids[cpuid].pm_gen == gen)
7391 return (CR3_PCID_SAVE);
7392 pcid_next = PCPU_GET(pcid_next);
7393 KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
7394 (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
7395 ("cpu %d pcid_next %#x", cpuid, pcid_next));
7396 if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
7397 (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
7401 PCPU_SET(pcid_gen, new_gen);
7402 pcid_next = PMAP_PCID_KERN + 1;
7406 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
7407 pmap->pm_pcids[cpuid].pm_gen = new_gen;
7408 PCPU_SET(pcid_next, pcid_next + 1);
7413 pmap_activate_sw(struct thread *td)
7415 pmap_t oldpmap, pmap;
7416 struct invpcid_descr d;
7417 uint64_t cached, cr3, kcr3, kern_pti_cached, rsp0, ucr3;
7420 struct amd64tss *tssp;
7423 oldpmap = PCPU_GET(curpmap);
7424 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7425 if (oldpmap == pmap)
7427 cpuid = PCPU_GET(cpuid);
7429 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7431 CPU_SET(cpuid, &pmap->pm_active);
7434 if (pmap_pcid_enabled) {
7435 cached = pmap_pcid_alloc(pmap, cpuid);
7436 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
7437 pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
7438 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
7439 pmap->pm_pcids[cpuid].pm_pcid));
7440 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
7441 pmap == kernel_pmap,
7442 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
7443 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
7446 * If the INVPCID instruction is not available,
7447 * invltlb_pcid_handler() is used for handle
7448 * invalidate_all IPI, which checks for curpmap ==
7449 * smp_tlb_pmap. Below operations sequence has a
7450 * window where %CR3 is loaded with the new pmap's
7451 * PML4 address, but curpmap value is not yet updated.
7452 * This causes invltlb IPI handler, called between the
7453 * updates, to execute as NOP, which leaves stale TLB
7456 * Note that the most typical use of
7457 * pmap_activate_sw(), from the context switch, is
7458 * immune to this race, because interrupts are
7459 * disabled (while the thread lock is owned), and IPI
7460 * happends after curpmap is updated. Protect other
7461 * callers in a similar way, by disabling interrupts
7462 * around the %cr3 register reload and curpmap
7466 rflags = intr_disable();
7468 kern_pti_cached = pti ? 0 : cached;
7469 if (!kern_pti_cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
7470 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
7473 PCPU_SET(curpmap, pmap);
7475 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid;
7476 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[cpuid].pm_pcid |
7479 if (!cached && pmap->pm_ucr3 != PMAP_NO_CR3) {
7481 * Manually invalidate translations cached
7482 * from the user page table. They are not
7483 * flushed by reload of cr3 with the kernel
7484 * page table pointer above.
7486 if (invpcid_works) {
7487 d.pcid = PMAP_PCID_USER_PT |
7488 pmap->pm_pcids[cpuid].pm_pcid;
7491 invpcid(&d, INVPCID_CTX);
7493 pmap_pti_pcid_invalidate(ucr3, kcr3);
7497 PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
7498 PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
7501 intr_restore(rflags);
7503 PCPU_INC(pm_save_cnt);
7504 } else if (cr3 != pmap->pm_cr3) {
7505 load_cr3(pmap->pm_cr3);
7506 PCPU_SET(curpmap, pmap);
7508 PCPU_SET(kcr3, pmap->pm_cr3);
7509 PCPU_SET(ucr3, pmap->pm_ucr3);
7512 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
7513 rsp0 = ((vm_offset_t)PCPU_PTR(pti_stack) +
7514 PC_PTI_STACK_SZ * sizeof(uint64_t)) & ~0xful;
7515 tssp = PCPU_GET(tssp);
7516 tssp->tss_rsp0 = rsp0;
7519 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
7521 CPU_CLR(cpuid, &oldpmap->pm_active);
7526 pmap_activate(struct thread *td)
7530 pmap_activate_sw(td);
7535 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
7540 * Increase the starting virtual address of the given mapping if a
7541 * different alignment might result in more superpage mappings.
7544 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7545 vm_offset_t *addr, vm_size_t size)
7547 vm_offset_t superpage_offset;
7551 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7552 offset += ptoa(object->pg_color);
7553 superpage_offset = offset & PDRMASK;
7554 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
7555 (*addr & PDRMASK) == superpage_offset)
7557 if ((*addr & PDRMASK) < superpage_offset)
7558 *addr = (*addr & ~PDRMASK) + superpage_offset;
7560 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
7564 static unsigned long num_dirty_emulations;
7565 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
7566 &num_dirty_emulations, 0, NULL);
7568 static unsigned long num_accessed_emulations;
7569 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
7570 &num_accessed_emulations, 0, NULL);
7572 static unsigned long num_superpage_accessed_emulations;
7573 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7574 &num_superpage_accessed_emulations, 0, NULL);
7576 static unsigned long ad_emulation_superpage_promotions;
7577 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7578 &ad_emulation_superpage_promotions, 0, NULL);
7579 #endif /* INVARIANTS */
7582 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7585 struct rwlock *lock;
7586 #if VM_NRESERVLEVEL > 0
7590 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7592 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7593 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7595 if (!pmap_emulate_ad_bits(pmap))
7598 PG_A = pmap_accessed_bit(pmap);
7599 PG_M = pmap_modified_bit(pmap);
7600 PG_V = pmap_valid_bit(pmap);
7601 PG_RW = pmap_rw_bit(pmap);
7607 pde = pmap_pde(pmap, va);
7608 if (pde == NULL || (*pde & PG_V) == 0)
7611 if ((*pde & PG_PS) != 0) {
7612 if (ftype == VM_PROT_READ) {
7614 atomic_add_long(&num_superpage_accessed_emulations, 1);
7622 pte = pmap_pde_to_pte(pde, va);
7623 if ((*pte & PG_V) == 0)
7626 if (ftype == VM_PROT_WRITE) {
7627 if ((*pte & PG_RW) == 0)
7630 * Set the modified and accessed bits simultaneously.
7632 * Intel EPT PTEs that do software emulation of A/D bits map
7633 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7634 * An EPT misconfiguration is triggered if the PTE is writable
7635 * but not readable (WR=10). This is avoided by setting PG_A
7636 * and PG_M simultaneously.
7638 *pte |= PG_M | PG_A;
7643 #if VM_NRESERVLEVEL > 0
7644 /* try to promote the mapping */
7645 if (va < VM_MAXUSER_ADDRESS)
7646 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7650 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7652 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7653 pmap_ps_enabled(pmap) &&
7654 (m->flags & PG_FICTITIOUS) == 0 &&
7655 vm_reserv_level_iffullpop(m) == 0) {
7656 pmap_promote_pde(pmap, pde, va, &lock);
7658 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7664 if (ftype == VM_PROT_WRITE)
7665 atomic_add_long(&num_dirty_emulations, 1);
7667 atomic_add_long(&num_accessed_emulations, 1);
7669 rv = 0; /* success */
7678 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7683 pt_entry_t *pte, PG_V;
7687 PG_V = pmap_valid_bit(pmap);
7690 pml4 = pmap_pml4e(pmap, va);
7692 if ((*pml4 & PG_V) == 0)
7695 pdp = pmap_pml4e_to_pdpe(pml4, va);
7697 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7700 pde = pmap_pdpe_to_pde(pdp, va);
7702 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7705 pte = pmap_pde_to_pte(pde, va);
7714 * Get the kernel virtual address of a set of physical pages. If there are
7715 * physical addresses not covered by the DMAP perform a transient mapping
7716 * that will be removed when calling pmap_unmap_io_transient.
7718 * \param page The pages the caller wishes to obtain the virtual
7719 * address on the kernel memory map.
7720 * \param vaddr On return contains the kernel virtual memory address
7721 * of the pages passed in the page parameter.
7722 * \param count Number of pages passed in.
7723 * \param can_fault TRUE if the thread using the mapped pages can take
7724 * page faults, FALSE otherwise.
7726 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7727 * finished or FALSE otherwise.
7731 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7732 boolean_t can_fault)
7735 boolean_t needs_mapping;
7737 int cache_bits, error __unused, i;
7740 * Allocate any KVA space that we need, this is done in a separate
7741 * loop to prevent calling vmem_alloc while pinned.
7743 needs_mapping = FALSE;
7744 for (i = 0; i < count; i++) {
7745 paddr = VM_PAGE_TO_PHYS(page[i]);
7746 if (__predict_false(paddr >= dmaplimit)) {
7747 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7748 M_BESTFIT | M_WAITOK, &vaddr[i]);
7749 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7750 needs_mapping = TRUE;
7752 vaddr[i] = PHYS_TO_DMAP(paddr);
7756 /* Exit early if everything is covered by the DMAP */
7761 * NB: The sequence of updating a page table followed by accesses
7762 * to the corresponding pages used in the !DMAP case is subject to
7763 * the situation described in the "AMD64 Architecture Programmer's
7764 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7765 * Coherency Considerations". Therefore, issuing the INVLPG right
7766 * after modifying the PTE bits is crucial.
7770 for (i = 0; i < count; i++) {
7771 paddr = VM_PAGE_TO_PHYS(page[i]);
7772 if (paddr >= dmaplimit) {
7775 * Slow path, since we can get page faults
7776 * while mappings are active don't pin the
7777 * thread to the CPU and instead add a global
7778 * mapping visible to all CPUs.
7780 pmap_qenter(vaddr[i], &page[i], 1);
7782 pte = vtopte(vaddr[i]);
7783 cache_bits = pmap_cache_bits(kernel_pmap,
7784 page[i]->md.pat_mode, 0);
7785 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7792 return (needs_mapping);
7796 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7797 boolean_t can_fault)
7804 for (i = 0; i < count; i++) {
7805 paddr = VM_PAGE_TO_PHYS(page[i]);
7806 if (paddr >= dmaplimit) {
7808 pmap_qremove(vaddr[i], 1);
7809 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7815 pmap_quick_enter_page(vm_page_t m)
7819 paddr = VM_PAGE_TO_PHYS(m);
7820 if (paddr < dmaplimit)
7821 return (PHYS_TO_DMAP(paddr));
7822 mtx_lock_spin(&qframe_mtx);
7823 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7824 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7825 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7830 pmap_quick_remove_page(vm_offset_t addr)
7835 pte_store(vtopte(qframe), 0);
7837 mtx_unlock_spin(&qframe_mtx);
7841 pmap_pti_alloc_page(void)
7845 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7846 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_NOBUSY |
7847 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
7852 pmap_pti_free_page(vm_page_t m)
7855 KASSERT(m->wire_count > 0, ("page %p not wired", m));
7856 if (!vm_page_unwire_noq(m))
7858 vm_page_free_zero(m);
7872 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
7873 VM_OBJECT_WLOCK(pti_obj);
7874 pml4_pg = pmap_pti_alloc_page();
7875 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
7876 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
7877 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
7878 pdpe = pmap_pti_pdpe(va);
7879 pmap_pti_wire_pte(pdpe);
7881 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
7882 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
7883 pmap_pti_add_kva_locked((vm_offset_t)gdt, (vm_offset_t)gdt +
7884 sizeof(struct user_segment_descriptor) * NGDT * MAXCPU, false);
7885 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
7886 sizeof(struct gate_descriptor) * NIDT, false);
7887 pmap_pti_add_kva_locked((vm_offset_t)common_tss,
7888 (vm_offset_t)common_tss + sizeof(struct amd64tss) * MAXCPU, false);
7890 /* Doublefault stack IST 1 */
7891 va = common_tss[i].tss_ist1;
7892 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7893 /* NMI stack IST 2 */
7894 va = common_tss[i].tss_ist2 + sizeof(struct nmi_pcpu);
7895 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7896 /* MC# stack IST 3 */
7897 va = common_tss[i].tss_ist3 + sizeof(struct nmi_pcpu);
7898 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7899 /* DB# stack IST 4 */
7900 va = common_tss[i].tss_ist4 + sizeof(struct nmi_pcpu);
7901 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7903 pmap_pti_add_kva_locked((vm_offset_t)kernphys + KERNBASE,
7904 (vm_offset_t)etext, true);
7905 pti_finalized = true;
7906 VM_OBJECT_WUNLOCK(pti_obj);
7908 SYSINIT(pmap_pti, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_pti_init, NULL);
7910 static pdp_entry_t *
7911 pmap_pti_pdpe(vm_offset_t va)
7913 pml4_entry_t *pml4e;
7916 vm_pindex_t pml4_idx;
7919 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7921 pml4_idx = pmap_pml4e_index(va);
7922 pml4e = &pti_pml4[pml4_idx];
7926 panic("pml4 alloc after finalization\n");
7927 m = pmap_pti_alloc_page();
7929 pmap_pti_free_page(m);
7930 mphys = *pml4e & ~PAGE_MASK;
7932 mphys = VM_PAGE_TO_PHYS(m);
7933 *pml4e = mphys | X86_PG_RW | X86_PG_V;
7936 mphys = *pml4e & ~PAGE_MASK;
7938 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
7943 pmap_pti_wire_pte(void *pte)
7947 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7948 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7953 pmap_pti_unwire_pde(void *pde, bool only_ref)
7957 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7958 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
7959 MPASS(m->wire_count > 0);
7960 MPASS(only_ref || m->wire_count > 1);
7961 pmap_pti_free_page(m);
7965 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
7970 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7971 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7972 MPASS(m->wire_count > 0);
7973 if (pmap_pti_free_page(m)) {
7974 pde = pmap_pti_pde(va);
7975 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
7977 pmap_pti_unwire_pde(pde, false);
7982 pmap_pti_pde(vm_offset_t va)
7990 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7992 pdpe = pmap_pti_pdpe(va);
7994 m = pmap_pti_alloc_page();
7996 pmap_pti_free_page(m);
7997 MPASS((*pdpe & X86_PG_PS) == 0);
7998 mphys = *pdpe & ~PAGE_MASK;
8000 mphys = VM_PAGE_TO_PHYS(m);
8001 *pdpe = mphys | X86_PG_RW | X86_PG_V;
8004 MPASS((*pdpe & X86_PG_PS) == 0);
8005 mphys = *pdpe & ~PAGE_MASK;
8008 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
8009 pd_idx = pmap_pde_index(va);
8015 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
8022 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8024 pde = pmap_pti_pde(va);
8025 if (unwire_pde != NULL) {
8027 pmap_pti_wire_pte(pde);
8030 m = pmap_pti_alloc_page();
8032 pmap_pti_free_page(m);
8033 MPASS((*pde & X86_PG_PS) == 0);
8034 mphys = *pde & ~(PAGE_MASK | pg_nx);
8036 mphys = VM_PAGE_TO_PHYS(m);
8037 *pde = mphys | X86_PG_RW | X86_PG_V;
8038 if (unwire_pde != NULL)
8039 *unwire_pde = false;
8042 MPASS((*pde & X86_PG_PS) == 0);
8043 mphys = *pde & ~(PAGE_MASK | pg_nx);
8046 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
8047 pte += pmap_pte_index(va);
8053 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
8057 pt_entry_t *pte, ptev;
8060 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8062 sva = trunc_page(sva);
8063 MPASS(sva > VM_MAXUSER_ADDRESS);
8064 eva = round_page(eva);
8066 for (; sva < eva; sva += PAGE_SIZE) {
8067 pte = pmap_pti_pte(sva, &unwire_pde);
8068 pa = pmap_kextract(sva);
8069 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A | X86_PG_G |
8070 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
8071 VM_MEMATTR_DEFAULT, FALSE);
8073 pte_store(pte, ptev);
8074 pmap_pti_wire_pte(pte);
8076 KASSERT(!pti_finalized,
8077 ("pti overlap after fin %#lx %#lx %#lx",
8079 KASSERT(*pte == ptev,
8080 ("pti non-identical pte after fin %#lx %#lx %#lx",
8084 pde = pmap_pti_pde(sva);
8085 pmap_pti_unwire_pde(pde, true);
8091 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
8096 VM_OBJECT_WLOCK(pti_obj);
8097 pmap_pti_add_kva_locked(sva, eva, exec);
8098 VM_OBJECT_WUNLOCK(pti_obj);
8102 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
8109 sva = rounddown2(sva, PAGE_SIZE);
8110 MPASS(sva > VM_MAXUSER_ADDRESS);
8111 eva = roundup2(eva, PAGE_SIZE);
8113 VM_OBJECT_WLOCK(pti_obj);
8114 for (va = sva; va < eva; va += PAGE_SIZE) {
8115 pte = pmap_pti_pte(va, NULL);
8116 KASSERT((*pte & X86_PG_V) != 0,
8117 ("invalid pte va %#lx pte %#lx pt %#lx", va,
8118 (u_long)pte, *pte));
8120 pmap_pti_unwire_pte(pte, va);
8122 pmap_invalidate_range(kernel_pmap, sva, eva);
8123 VM_OBJECT_WUNLOCK(pti_obj);
8126 #include "opt_ddb.h"
8128 #include <sys/kdb.h>
8129 #include <ddb/ddb.h>
8131 DB_SHOW_COMMAND(pte, pmap_print_pte)
8137 pt_entry_t *pte, PG_V;
8141 db_printf("show pte addr\n");
8144 va = (vm_offset_t)addr;
8146 if (kdb_thread != NULL)
8147 pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
8149 pmap = PCPU_GET(curpmap);
8151 PG_V = pmap_valid_bit(pmap);
8152 pml4 = pmap_pml4e(pmap, va);
8153 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
8154 if ((*pml4 & PG_V) == 0) {
8158 pdp = pmap_pml4e_to_pdpe(pml4, va);
8159 db_printf(" pdpe %#016lx", *pdp);
8160 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
8164 pde = pmap_pdpe_to_pde(pdp, va);
8165 db_printf(" pde %#016lx", *pde);
8166 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
8170 pte = pmap_pde_to_pte(pde, va);
8171 db_printf(" pte %#016lx\n", *pte);
8174 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
8179 a = (vm_paddr_t)addr;
8180 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
8182 db_printf("show phys2dmap addr\n");