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.
14 * Copyright (c) 2014-2018 The FreeBSD Foundation
15 * All rights reserved.
17 * This code is derived from software contributed to Berkeley by
18 * the Systems Programming Group of the University of Utah Computer
19 * Science Department and William Jolitz of UUNET Technologies Inc.
21 * Portions of this software were developed by
22 * Konstantin Belousov <kib@FreeBSD.org> under sponsorship from
23 * the FreeBSD Foundation.
25 * Redistribution and use in source and binary forms, with or without
26 * modification, are permitted provided that the following conditions
28 * 1. Redistributions of source code must retain the above copyright
29 * notice, this list of conditions and the following disclaimer.
30 * 2. Redistributions in binary form must reproduce the above copyright
31 * notice, this list of conditions and the following disclaimer in the
32 * documentation and/or other materials provided with the distribution.
33 * 3. All advertising materials mentioning features or use of this software
34 * must display the following acknowledgement:
35 * This product includes software developed by the University of
36 * California, Berkeley and its contributors.
37 * 4. Neither the name of the University nor the names of its contributors
38 * may be used to endorse or promote products derived from this software
39 * without specific prior written permission.
41 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53 * from: @(#)pmap.c 7.7 (Berkeley) 5/12/91
56 * Copyright (c) 2003 Networks Associates Technology, Inc.
57 * All rights reserved.
59 * This software was developed for the FreeBSD Project by Jake Burkholder,
60 * Safeport Network Services, and Network Associates Laboratories, the
61 * Security Research Division of Network Associates, Inc. under
62 * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
63 * CHATS research program.
65 * Redistribution and use in source and binary forms, with or without
66 * modification, are permitted provided that the following conditions
68 * 1. Redistributions of source code must retain the above copyright
69 * notice, this list of conditions and the following disclaimer.
70 * 2. Redistributions in binary form must reproduce the above copyright
71 * notice, this list of conditions and the following disclaimer in the
72 * documentation and/or other materials provided with the distribution.
74 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
75 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
76 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
77 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
78 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
79 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
80 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
81 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
82 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
83 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
87 #define AMD64_NPT_AWARE
89 #include <sys/cdefs.h>
90 __FBSDID("$FreeBSD$");
93 * Manages physical address maps.
95 * Since the information managed by this module is
96 * also stored by the logical address mapping module,
97 * this module may throw away valid virtual-to-physical
98 * mappings at almost any time. However, invalidations
99 * of virtual-to-physical mappings must be done as
102 * In order to cope with hardware architectures which
103 * make virtual-to-physical map invalidates expensive,
104 * this module may delay invalidate or reduced protection
105 * operations until such time as they are actually
106 * necessary. This module is given full information as
107 * to which processors are currently using which maps,
108 * and to when physical maps must be made correct.
111 #include "opt_pmap.h"
114 #include <sys/param.h>
115 #include <sys/bitstring.h>
117 #include <sys/systm.h>
118 #include <sys/kernel.h>
120 #include <sys/lock.h>
121 #include <sys/malloc.h>
122 #include <sys/mman.h>
123 #include <sys/mutex.h>
124 #include <sys/proc.h>
125 #include <sys/rwlock.h>
127 #include <sys/turnstile.h>
128 #include <sys/vmem.h>
129 #include <sys/vmmeter.h>
130 #include <sys/sched.h>
131 #include <sys/sysctl.h>
135 #include <vm/vm_param.h>
136 #include <vm/vm_kern.h>
137 #include <vm/vm_page.h>
138 #include <vm/vm_map.h>
139 #include <vm/vm_object.h>
140 #include <vm/vm_extern.h>
141 #include <vm/vm_pageout.h>
142 #include <vm/vm_pager.h>
143 #include <vm/vm_phys.h>
144 #include <vm/vm_radix.h>
145 #include <vm/vm_reserv.h>
148 #include <machine/intr_machdep.h>
149 #include <x86/apicvar.h>
150 #include <machine/cpu.h>
151 #include <machine/cputypes.h>
152 #include <machine/md_var.h>
153 #include <machine/pcb.h>
154 #include <machine/specialreg.h>
156 #include <machine/smp.h>
158 #include <machine/tss.h>
160 static __inline boolean_t
161 pmap_type_guest(pmap_t pmap)
164 return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
167 static __inline boolean_t
168 pmap_emulate_ad_bits(pmap_t pmap)
171 return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
174 static __inline pt_entry_t
175 pmap_valid_bit(pmap_t pmap)
179 switch (pmap->pm_type) {
185 if (pmap_emulate_ad_bits(pmap))
186 mask = EPT_PG_EMUL_V;
191 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
197 static __inline pt_entry_t
198 pmap_rw_bit(pmap_t pmap)
202 switch (pmap->pm_type) {
208 if (pmap_emulate_ad_bits(pmap))
209 mask = EPT_PG_EMUL_RW;
214 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
220 static pt_entry_t pg_g;
222 static __inline pt_entry_t
223 pmap_global_bit(pmap_t pmap)
227 switch (pmap->pm_type) {
236 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
242 static __inline pt_entry_t
243 pmap_accessed_bit(pmap_t pmap)
247 switch (pmap->pm_type) {
253 if (pmap_emulate_ad_bits(pmap))
259 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
265 static __inline pt_entry_t
266 pmap_modified_bit(pmap_t pmap)
270 switch (pmap->pm_type) {
276 if (pmap_emulate_ad_bits(pmap))
282 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
288 #if !defined(DIAGNOSTIC)
289 #ifdef __GNUC_GNU_INLINE__
290 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
292 #define PMAP_INLINE extern inline
299 #define PV_STAT(x) do { x ; } while (0)
301 #define PV_STAT(x) do { } while (0)
304 #define pa_index(pa) ((pa) >> PDRSHIFT)
305 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
307 #define NPV_LIST_LOCKS MAXCPU
309 #define PHYS_TO_PV_LIST_LOCK(pa) \
310 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
312 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
313 struct rwlock **_lockp = (lockp); \
314 struct rwlock *_new_lock; \
316 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
317 if (_new_lock != *_lockp) { \
318 if (*_lockp != NULL) \
319 rw_wunlock(*_lockp); \
320 *_lockp = _new_lock; \
325 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
326 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
328 #define RELEASE_PV_LIST_LOCK(lockp) do { \
329 struct rwlock **_lockp = (lockp); \
331 if (*_lockp != NULL) { \
332 rw_wunlock(*_lockp); \
337 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
338 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
340 struct pmap kernel_pmap_store;
342 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
343 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
346 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
347 "Number of kernel page table pages allocated on bootup");
350 vm_paddr_t dmaplimit;
351 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
354 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
356 static int pat_works = 1;
357 SYSCTL_INT(_vm_pmap, OID_AUTO, pat_works, CTLFLAG_RD, &pat_works, 1,
358 "Is page attribute table fully functional?");
360 static int pg_ps_enabled = 1;
361 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
362 &pg_ps_enabled, 0, "Are large page mappings enabled?");
364 #define PAT_INDEX_SIZE 8
365 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
367 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
368 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
369 u_int64_t KPDPphys; /* phys addr of kernel level 3 */
370 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
372 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
373 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
374 static int ndmpdpphys; /* number of DMPDPphys pages */
377 * pmap_mapdev support pre initialization (i.e. console)
379 #define PMAP_PREINIT_MAPPING_COUNT 8
380 static struct pmap_preinit_mapping {
385 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
386 static int pmap_initialized;
389 * Data for the pv entry allocation mechanism.
390 * Updates to pv_invl_gen are protected by the pv_list_locks[]
391 * elements, but reads are not.
393 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
394 static struct mtx __exclusive_cache_line pv_chunks_mutex;
395 static struct rwlock __exclusive_cache_line pv_list_locks[NPV_LIST_LOCKS];
396 static u_long pv_invl_gen[NPV_LIST_LOCKS];
397 static struct md_page *pv_table;
398 static struct md_page pv_dummy;
401 * All those kernel PT submaps that BSD is so fond of
403 pt_entry_t *CMAP1 = NULL;
405 static vm_offset_t qframe = 0;
406 static struct mtx qframe_mtx;
408 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
410 int pmap_pcid_enabled = 1;
411 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
412 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
413 int invpcid_works = 0;
414 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
415 "Is the invpcid instruction available ?");
418 SYSCTL_INT(_vm_pmap, OID_AUTO, pti, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
420 "Page Table Isolation enabled");
421 static vm_object_t pti_obj;
422 static pml4_entry_t *pti_pml4;
423 static vm_pindex_t pti_pg_idx;
424 static bool pti_finalized;
427 pmap_pcid_save_cnt_proc(SYSCTL_HANDLER_ARGS)
434 res += cpuid_to_pcpu[i]->pc_pm_save_cnt;
436 return (sysctl_handle_64(oidp, &res, 0, req));
438 SYSCTL_PROC(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLTYPE_U64 | CTLFLAG_RW |
439 CTLFLAG_MPSAFE, NULL, 0, pmap_pcid_save_cnt_proc, "QU",
440 "Count of saved TLB context on switch");
442 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
443 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
444 static struct mtx invl_gen_mtx;
445 static u_long pmap_invl_gen = 0;
446 /* Fake lock object to satisfy turnstiles interface. */
447 static struct lock_object invl_gen_ts = {
455 return (curthread->td_md.md_invl_gen.gen == 0);
458 #define PMAP_ASSERT_NOT_IN_DI() \
459 KASSERT(pmap_not_in_di(), ("DI already started"))
462 * Start a new Delayed Invalidation (DI) block of code, executed by
463 * the current thread. Within a DI block, the current thread may
464 * destroy both the page table and PV list entries for a mapping and
465 * then release the corresponding PV list lock before ensuring that
466 * the mapping is flushed from the TLBs of any processors with the
470 pmap_delayed_invl_started(void)
472 struct pmap_invl_gen *invl_gen;
475 invl_gen = &curthread->td_md.md_invl_gen;
476 PMAP_ASSERT_NOT_IN_DI();
477 mtx_lock(&invl_gen_mtx);
478 if (LIST_EMPTY(&pmap_invl_gen_tracker))
479 currgen = pmap_invl_gen;
481 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
482 invl_gen->gen = currgen + 1;
483 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
484 mtx_unlock(&invl_gen_mtx);
488 * Finish the DI block, previously started by the current thread. All
489 * required TLB flushes for the pages marked by
490 * pmap_delayed_invl_page() must be finished before this function is
493 * This function works by bumping the global DI generation number to
494 * the generation number of the current thread's DI, unless there is a
495 * pending DI that started earlier. In the latter case, bumping the
496 * global DI generation number would incorrectly signal that the
497 * earlier DI had finished. Instead, this function bumps the earlier
498 * DI's generation number to match the generation number of the
499 * current thread's DI.
502 pmap_delayed_invl_finished(void)
504 struct pmap_invl_gen *invl_gen, *next;
505 struct turnstile *ts;
507 invl_gen = &curthread->td_md.md_invl_gen;
508 KASSERT(invl_gen->gen != 0, ("missed invl_started"));
509 mtx_lock(&invl_gen_mtx);
510 next = LIST_NEXT(invl_gen, link);
512 turnstile_chain_lock(&invl_gen_ts);
513 ts = turnstile_lookup(&invl_gen_ts);
514 pmap_invl_gen = invl_gen->gen;
516 turnstile_broadcast(ts, TS_SHARED_QUEUE);
517 turnstile_unpend(ts, TS_SHARED_LOCK);
519 turnstile_chain_unlock(&invl_gen_ts);
521 next->gen = invl_gen->gen;
523 LIST_REMOVE(invl_gen, link);
524 mtx_unlock(&invl_gen_mtx);
529 static long invl_wait;
530 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
531 "Number of times DI invalidation blocked pmap_remove_all/write");
535 pmap_delayed_invl_genp(vm_page_t m)
538 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
542 * Ensure that all currently executing DI blocks, that need to flush
543 * TLB for the given page m, actually flushed the TLB at the time the
544 * function returned. If the page m has an empty PV list and we call
545 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
546 * valid mapping for the page m in either its page table or TLB.
548 * This function works by blocking until the global DI generation
549 * number catches up with the generation number associated with the
550 * given page m and its PV list. Since this function's callers
551 * typically own an object lock and sometimes own a page lock, it
552 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
556 pmap_delayed_invl_wait(vm_page_t m)
558 struct turnstile *ts;
561 bool accounted = false;
564 m_gen = pmap_delayed_invl_genp(m);
565 while (*m_gen > pmap_invl_gen) {
568 atomic_add_long(&invl_wait, 1);
572 ts = turnstile_trywait(&invl_gen_ts);
573 if (*m_gen > pmap_invl_gen)
574 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
576 turnstile_cancel(ts);
581 * Mark the page m's PV list as participating in the current thread's
582 * DI block. Any threads concurrently using m's PV list to remove or
583 * restrict all mappings to m will wait for the current thread's DI
584 * block to complete before proceeding.
586 * The function works by setting the DI generation number for m's PV
587 * list to at least the DI generation number of the current thread.
588 * This forces a caller of pmap_delayed_invl_wait() to block until
589 * current thread calls pmap_delayed_invl_finished().
592 pmap_delayed_invl_page(vm_page_t m)
596 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
597 gen = curthread->td_md.md_invl_gen.gen;
600 m_gen = pmap_delayed_invl_genp(m);
608 static caddr_t crashdumpmap;
611 * Internal flags for pmap_enter()'s helper functions.
613 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
614 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
616 static void free_pv_chunk(struct pv_chunk *pc);
617 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
618 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
619 static int popcnt_pc_map_pq(uint64_t *map);
620 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
621 static void reserve_pv_entries(pmap_t pmap, int needed,
622 struct rwlock **lockp);
623 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
624 struct rwlock **lockp);
625 static bool pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
626 u_int flags, struct rwlock **lockp);
627 #if VM_NRESERVLEVEL > 0
628 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
629 struct rwlock **lockp);
631 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
632 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
635 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode);
636 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
637 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
638 vm_offset_t va, struct rwlock **lockp);
639 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
641 static bool pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
642 vm_prot_t prot, struct rwlock **lockp);
643 static int pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
644 u_int flags, vm_page_t m, struct rwlock **lockp);
645 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
646 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
647 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
648 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
649 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
651 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
652 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask);
653 #if VM_NRESERVLEVEL > 0
654 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
655 struct rwlock **lockp);
657 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
659 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
660 static void pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva,
662 static pdp_entry_t *pmap_pti_pdpe(vm_offset_t va);
663 static pd_entry_t *pmap_pti_pde(vm_offset_t va);
664 static void pmap_pti_wire_pte(void *pte);
665 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
666 struct spglist *free, struct rwlock **lockp);
667 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
668 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
669 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
670 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
671 struct spglist *free);
672 static bool pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
673 pd_entry_t *pde, struct spglist *free,
674 struct rwlock **lockp);
675 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
676 vm_page_t m, struct rwlock **lockp);
677 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
679 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
681 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
682 struct rwlock **lockp);
683 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
684 struct rwlock **lockp);
685 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
686 struct rwlock **lockp);
688 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
689 struct spglist *free);
690 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
691 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
694 * Move the kernel virtual free pointer to the next
695 * 2MB. This is used to help improve performance
696 * by using a large (2MB) page for much of the kernel
697 * (.text, .data, .bss)
700 pmap_kmem_choose(vm_offset_t addr)
702 vm_offset_t newaddr = addr;
704 newaddr = roundup2(addr, NBPDR);
708 /********************/
709 /* Inline functions */
710 /********************/
712 /* Return a non-clipped PD index for a given VA */
713 static __inline vm_pindex_t
714 pmap_pde_pindex(vm_offset_t va)
716 return (va >> PDRSHIFT);
720 /* Return a pointer to the PML4 slot that corresponds to a VA */
721 static __inline pml4_entry_t *
722 pmap_pml4e(pmap_t pmap, vm_offset_t va)
725 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
728 /* Return a pointer to the PDP slot that corresponds to a VA */
729 static __inline pdp_entry_t *
730 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
734 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
735 return (&pdpe[pmap_pdpe_index(va)]);
738 /* Return a pointer to the PDP slot that corresponds to a VA */
739 static __inline pdp_entry_t *
740 pmap_pdpe(pmap_t pmap, vm_offset_t va)
745 PG_V = pmap_valid_bit(pmap);
746 pml4e = pmap_pml4e(pmap, va);
747 if ((*pml4e & PG_V) == 0)
749 return (pmap_pml4e_to_pdpe(pml4e, va));
752 /* Return a pointer to the PD slot that corresponds to a VA */
753 static __inline pd_entry_t *
754 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
758 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
759 return (&pde[pmap_pde_index(va)]);
762 /* Return a pointer to the PD slot that corresponds to a VA */
763 static __inline pd_entry_t *
764 pmap_pde(pmap_t pmap, vm_offset_t va)
769 PG_V = pmap_valid_bit(pmap);
770 pdpe = pmap_pdpe(pmap, va);
771 if (pdpe == NULL || (*pdpe & PG_V) == 0)
773 return (pmap_pdpe_to_pde(pdpe, va));
776 /* Return a pointer to the PT slot that corresponds to a VA */
777 static __inline pt_entry_t *
778 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
782 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
783 return (&pte[pmap_pte_index(va)]);
786 /* Return a pointer to the PT slot that corresponds to a VA */
787 static __inline pt_entry_t *
788 pmap_pte(pmap_t pmap, vm_offset_t va)
793 PG_V = pmap_valid_bit(pmap);
794 pde = pmap_pde(pmap, va);
795 if (pde == NULL || (*pde & PG_V) == 0)
797 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
798 return ((pt_entry_t *)pde);
799 return (pmap_pde_to_pte(pde, va));
803 pmap_resident_count_inc(pmap_t pmap, int count)
806 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
807 pmap->pm_stats.resident_count += count;
811 pmap_resident_count_dec(pmap_t pmap, int count)
814 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
815 KASSERT(pmap->pm_stats.resident_count >= count,
816 ("pmap %p resident count underflow %ld %d", pmap,
817 pmap->pm_stats.resident_count, count));
818 pmap->pm_stats.resident_count -= count;
821 PMAP_INLINE pt_entry_t *
822 vtopte(vm_offset_t va)
824 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
826 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
828 return (PTmap + ((va >> PAGE_SHIFT) & mask));
831 static __inline pd_entry_t *
832 vtopde(vm_offset_t va)
834 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
836 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
838 return (PDmap + ((va >> PDRSHIFT) & mask));
842 allocpages(vm_paddr_t *firstaddr, int n)
847 bzero((void *)ret, n * PAGE_SIZE);
848 *firstaddr += n * PAGE_SIZE;
852 CTASSERT(powerof2(NDMPML4E));
854 /* number of kernel PDP slots */
855 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
858 nkpt_init(vm_paddr_t addr)
865 pt_pages = howmany(addr, 1 << PDRSHIFT);
866 pt_pages += NKPDPE(pt_pages);
869 * Add some slop beyond the bare minimum required for bootstrapping
872 * This is quite important when allocating KVA for kernel modules.
873 * The modules are required to be linked in the negative 2GB of
874 * the address space. If we run out of KVA in this region then
875 * pmap_growkernel() will need to allocate page table pages to map
876 * the entire 512GB of KVA space which is an unnecessary tax on
879 * Secondly, device memory mapped as part of setting up the low-
880 * level console(s) is taken from KVA, starting at virtual_avail.
881 * This is because cninit() is called after pmap_bootstrap() but
882 * before vm_init() and pmap_init(). 20MB for a frame buffer is
885 pt_pages += 32; /* 64MB additional slop. */
891 create_pagetables(vm_paddr_t *firstaddr)
893 int i, j, ndm1g, nkpdpe;
899 /* Allocate page table pages for the direct map */
900 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
901 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
903 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
904 if (ndmpdpphys > NDMPML4E) {
906 * Each NDMPML4E allows 512 GB, so limit to that,
907 * and then readjust ndmpdp and ndmpdpphys.
909 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
910 Maxmem = atop(NDMPML4E * NBPML4);
911 ndmpdpphys = NDMPML4E;
912 ndmpdp = NDMPML4E * NPDEPG;
914 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
916 if ((amd_feature & AMDID_PAGE1GB) != 0)
917 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
919 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
920 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
923 KPML4phys = allocpages(firstaddr, 1);
924 KPDPphys = allocpages(firstaddr, NKPML4E);
927 * Allocate the initial number of kernel page table pages required to
928 * bootstrap. We defer this until after all memory-size dependent
929 * allocations are done (e.g. direct map), so that we don't have to
930 * build in too much slop in our estimate.
932 * Note that when NKPML4E > 1, we have an empty page underneath
933 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
934 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
936 nkpt_init(*firstaddr);
937 nkpdpe = NKPDPE(nkpt);
939 KPTphys = allocpages(firstaddr, nkpt);
940 KPDphys = allocpages(firstaddr, nkpdpe);
942 /* Fill in the underlying page table pages */
943 /* Nominally read-only (but really R/W) from zero to physfree */
944 /* XXX not fully used, underneath 2M pages */
945 pt_p = (pt_entry_t *)KPTphys;
946 for (i = 0; ptoa(i) < *firstaddr; i++)
947 pt_p[i] = ptoa(i) | X86_PG_RW | X86_PG_V | pg_g;
949 /* Now map the page tables at their location within PTmap */
950 pd_p = (pd_entry_t *)KPDphys;
951 for (i = 0; i < nkpt; i++)
952 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
954 /* Map from zero to end of allocations under 2M pages */
955 /* This replaces some of the KPTphys entries above */
956 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
957 pd_p[i] = (i << PDRSHIFT) | X86_PG_RW | X86_PG_V | PG_PS |
960 /* And connect up the PD to the PDP (leaving room for L4 pages) */
961 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
962 for (i = 0; i < nkpdpe; i++)
963 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
967 * Now, set up the direct map region using 2MB and/or 1GB pages. If
968 * the end of physical memory is not aligned to a 1GB page boundary,
969 * then the residual physical memory is mapped with 2MB pages. Later,
970 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
971 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
972 * that are partially used.
974 pd_p = (pd_entry_t *)DMPDphys;
975 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
976 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
977 /* Preset PG_M and PG_A because demotion expects it. */
978 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
979 X86_PG_M | X86_PG_A | pg_nx;
981 pdp_p = (pdp_entry_t *)DMPDPphys;
982 for (i = 0; i < ndm1g; i++) {
983 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
984 /* Preset PG_M and PG_A because demotion expects it. */
985 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
986 X86_PG_M | X86_PG_A | pg_nx;
988 for (j = 0; i < ndmpdp; i++, j++) {
989 pdp_p[i] = DMPDphys + ptoa(j);
990 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_U;
993 /* And recursively map PML4 to itself in order to get PTmap */
994 p4_p = (pml4_entry_t *)KPML4phys;
995 p4_p[PML4PML4I] = KPML4phys;
996 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | PG_U;
998 /* Connect the Direct Map slot(s) up to the PML4. */
999 for (i = 0; i < ndmpdpphys; i++) {
1000 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
1001 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | PG_U;
1004 /* Connect the KVA slots up to the PML4 */
1005 for (i = 0; i < NKPML4E; i++) {
1006 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
1007 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V | PG_U;
1012 * Bootstrap the system enough to run with virtual memory.
1014 * On amd64 this is called after mapping has already been enabled
1015 * and just syncs the pmap module with what has already been done.
1016 * [We can't call it easily with mapping off since the kernel is not
1017 * mapped with PA == VA, hence we would have to relocate every address
1018 * from the linked base (virtual) address "KERNBASE" to the actual
1019 * (physical) address starting relative to 0]
1022 pmap_bootstrap(vm_paddr_t *firstaddr)
1032 * Create an initial set of page tables to run the kernel in.
1034 create_pagetables(firstaddr);
1037 * Add a physical memory segment (vm_phys_seg) corresponding to the
1038 * preallocated kernel page table pages so that vm_page structures
1039 * representing these pages will be created. The vm_page structures
1040 * are required for promotion of the corresponding kernel virtual
1041 * addresses to superpage mappings.
1043 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1045 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
1046 virtual_avail = pmap_kmem_choose(virtual_avail);
1048 virtual_end = VM_MAX_KERNEL_ADDRESS;
1051 /* XXX do %cr0 as well */
1052 load_cr4(rcr4() | CR4_PGE);
1053 load_cr3(KPML4phys);
1054 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1055 load_cr4(rcr4() | CR4_SMEP);
1058 * Initialize the kernel pmap (which is statically allocated).
1060 PMAP_LOCK_INIT(kernel_pmap);
1061 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1062 kernel_pmap->pm_cr3 = KPML4phys;
1063 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1064 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1065 kernel_pmap->pm_flags = pmap_flags;
1068 * Initialize the TLB invalidations generation number lock.
1070 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1073 * Reserve some special page table entries/VA space for temporary
1076 #define SYSMAP(c, p, v, n) \
1077 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1083 * Crashdump maps. The first page is reused as CMAP1 for the
1086 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1087 CADDR1 = crashdumpmap;
1092 * Initialize the PAT MSR.
1093 * pmap_init_pat() clears and sets CR4_PGE, which, as a
1094 * side-effect, invalidates stale PG_G TLB entries that might
1095 * have been created in our pre-boot environment.
1099 /* Initialize TLB Context Id. */
1101 pmap_pcid_enabled = 0;
1102 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1103 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1104 /* Check for INVPCID support */
1105 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1107 for (i = 0; i < MAXCPU; i++) {
1108 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1109 kernel_pmap->pm_pcids[i].pm_gen = 1;
1111 PCPU_SET(pcid_next, PMAP_PCID_KERN + 1);
1112 PCPU_SET(pcid_gen, 1);
1114 * pcpu area for APs is zeroed during AP startup.
1115 * pc_pcid_next and pc_pcid_gen are initialized by AP
1116 * during pcpu setup.
1118 load_cr4(rcr4() | CR4_PCIDE);
1120 pmap_pcid_enabled = 0;
1125 * Setup the PAT MSR.
1130 int pat_table[PAT_INDEX_SIZE];
1135 /* Bail if this CPU doesn't implement PAT. */
1136 if ((cpu_feature & CPUID_PAT) == 0)
1139 /* Set default PAT index table. */
1140 for (i = 0; i < PAT_INDEX_SIZE; i++)
1142 pat_table[PAT_WRITE_BACK] = 0;
1143 pat_table[PAT_WRITE_THROUGH] = 1;
1144 pat_table[PAT_UNCACHEABLE] = 3;
1145 pat_table[PAT_WRITE_COMBINING] = 3;
1146 pat_table[PAT_WRITE_PROTECTED] = 3;
1147 pat_table[PAT_UNCACHED] = 3;
1149 /* Initialize default PAT entries. */
1150 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1151 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1152 PAT_VALUE(2, PAT_UNCACHED) |
1153 PAT_VALUE(3, PAT_UNCACHEABLE) |
1154 PAT_VALUE(4, PAT_WRITE_BACK) |
1155 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1156 PAT_VALUE(6, PAT_UNCACHED) |
1157 PAT_VALUE(7, PAT_UNCACHEABLE);
1161 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1162 * Program 5 and 6 as WP and WC.
1163 * Leave 4 and 7 as WB and UC.
1165 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1166 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1167 PAT_VALUE(6, PAT_WRITE_COMBINING);
1168 pat_table[PAT_UNCACHED] = 2;
1169 pat_table[PAT_WRITE_PROTECTED] = 5;
1170 pat_table[PAT_WRITE_COMBINING] = 6;
1173 * Just replace PAT Index 2 with WC instead of UC-.
1175 pat_msr &= ~PAT_MASK(2);
1176 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1177 pat_table[PAT_WRITE_COMBINING] = 2;
1182 load_cr4(cr4 & ~CR4_PGE);
1184 /* Disable caches (CD = 1, NW = 0). */
1186 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1188 /* Flushes caches and TLBs. */
1192 /* Update PAT and index table. */
1193 wrmsr(MSR_PAT, pat_msr);
1194 for (i = 0; i < PAT_INDEX_SIZE; i++)
1195 pat_index[i] = pat_table[i];
1197 /* Flush caches and TLBs again. */
1201 /* Restore caches and PGE. */
1207 * Initialize a vm_page's machine-dependent fields.
1210 pmap_page_init(vm_page_t m)
1213 TAILQ_INIT(&m->md.pv_list);
1214 m->md.pat_mode = PAT_WRITE_BACK;
1218 * Initialize the pmap module.
1219 * Called by vm_init, to initialize any structures that the pmap
1220 * system needs to map virtual memory.
1225 struct pmap_preinit_mapping *ppim;
1228 int error, i, pv_npg;
1231 * Initialize the vm page array entries for the kernel pmap's
1234 for (i = 0; i < nkpt; i++) {
1235 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1236 KASSERT(mpte >= vm_page_array &&
1237 mpte < &vm_page_array[vm_page_array_size],
1238 ("pmap_init: page table page is out of range"));
1239 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1240 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1244 * If the kernel is running on a virtual machine, then it must assume
1245 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1246 * be prepared for the hypervisor changing the vendor and family that
1247 * are reported by CPUID. Consequently, the workaround for AMD Family
1248 * 10h Erratum 383 is enabled if the processor's feature set does not
1249 * include at least one feature that is only supported by older Intel
1250 * or newer AMD processors.
1252 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1253 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1254 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1256 workaround_erratum383 = 1;
1259 * Are large page mappings enabled?
1261 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1262 if (pg_ps_enabled) {
1263 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1264 ("pmap_init: can't assign to pagesizes[1]"));
1265 pagesizes[1] = NBPDR;
1269 * Initialize the pv chunk list mutex.
1271 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1274 * Initialize the pool of pv list locks.
1276 for (i = 0; i < NPV_LIST_LOCKS; i++)
1277 rw_init(&pv_list_locks[i], "pmap pv list");
1280 * Calculate the size of the pv head table for superpages.
1282 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1285 * Allocate memory for the pv head table for superpages.
1287 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1289 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1291 for (i = 0; i < pv_npg; i++)
1292 TAILQ_INIT(&pv_table[i].pv_list);
1293 TAILQ_INIT(&pv_dummy.pv_list);
1295 pmap_initialized = 1;
1296 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1297 ppim = pmap_preinit_mapping + i;
1300 /* Make the direct map consistent */
1301 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1302 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1303 ppim->sz, ppim->mode);
1307 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1308 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1311 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1312 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1313 (vmem_addr_t *)&qframe);
1315 panic("qframe allocation failed");
1318 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1319 "2MB page mapping counters");
1321 static u_long pmap_pde_demotions;
1322 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1323 &pmap_pde_demotions, 0, "2MB page demotions");
1325 static u_long pmap_pde_mappings;
1326 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1327 &pmap_pde_mappings, 0, "2MB page mappings");
1329 static u_long pmap_pde_p_failures;
1330 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1331 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1333 static u_long pmap_pde_promotions;
1334 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1335 &pmap_pde_promotions, 0, "2MB page promotions");
1337 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1338 "1GB page mapping counters");
1340 static u_long pmap_pdpe_demotions;
1341 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1342 &pmap_pdpe_demotions, 0, "1GB page demotions");
1344 /***************************************************
1345 * Low level helper routines.....
1346 ***************************************************/
1349 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1351 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1353 switch (pmap->pm_type) {
1356 /* Verify that both PAT bits are not set at the same time */
1357 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1358 ("Invalid PAT bits in entry %#lx", entry));
1360 /* Swap the PAT bits if one of them is set */
1361 if ((entry & x86_pat_bits) != 0)
1362 entry ^= x86_pat_bits;
1366 * Nothing to do - the memory attributes are represented
1367 * the same way for regular pages and superpages.
1371 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1378 * Determine the appropriate bits to set in a PTE or PDE for a specified
1382 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1384 int cache_bits, pat_flag, pat_idx;
1386 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1387 panic("Unknown caching mode %d\n", mode);
1389 switch (pmap->pm_type) {
1392 /* The PAT bit is different for PTE's and PDE's. */
1393 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1395 /* Map the caching mode to a PAT index. */
1396 pat_idx = pat_index[mode];
1398 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1401 cache_bits |= pat_flag;
1403 cache_bits |= PG_NC_PCD;
1405 cache_bits |= PG_NC_PWT;
1409 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1413 panic("unsupported pmap type %d", pmap->pm_type);
1416 return (cache_bits);
1420 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1424 switch (pmap->pm_type) {
1427 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1430 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1433 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1440 pmap_ps_enabled(pmap_t pmap)
1443 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1447 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1450 switch (pmap->pm_type) {
1457 * This is a little bogus since the generation number is
1458 * supposed to be bumped up when a region of the address
1459 * space is invalidated in the page tables.
1461 * In this case the old PDE entry is valid but yet we want
1462 * to make sure that any mappings using the old entry are
1463 * invalidated in the TLB.
1465 * The reason this works as expected is because we rendezvous
1466 * "all" host cpus and force any vcpu context to exit as a
1469 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1472 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1474 pde_store(pde, newpde);
1478 * After changing the page size for the specified virtual address in the page
1479 * table, flush the corresponding entries from the processor's TLB. Only the
1480 * calling processor's TLB is affected.
1482 * The calling thread must be pinned to a processor.
1485 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1489 if (pmap_type_guest(pmap))
1492 KASSERT(pmap->pm_type == PT_X86,
1493 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1495 PG_G = pmap_global_bit(pmap);
1497 if ((newpde & PG_PS) == 0)
1498 /* Demotion: flush a specific 2MB page mapping. */
1500 else if ((newpde & PG_G) == 0)
1502 * Promotion: flush every 4KB page mapping from the TLB
1503 * because there are too many to flush individually.
1508 * Promotion: flush every 4KB page mapping from the TLB,
1509 * including any global (PG_G) mappings.
1517 * For SMP, these functions have to use the IPI mechanism for coherence.
1519 * N.B.: Before calling any of the following TLB invalidation functions,
1520 * the calling processor must ensure that all stores updating a non-
1521 * kernel page table are globally performed. Otherwise, another
1522 * processor could cache an old, pre-update entry without being
1523 * invalidated. This can happen one of two ways: (1) The pmap becomes
1524 * active on another processor after its pm_active field is checked by
1525 * one of the following functions but before a store updating the page
1526 * table is globally performed. (2) The pmap becomes active on another
1527 * processor before its pm_active field is checked but due to
1528 * speculative loads one of the following functions stills reads the
1529 * pmap as inactive on the other processor.
1531 * The kernel page table is exempt because its pm_active field is
1532 * immutable. The kernel page table is always active on every
1537 * Interrupt the cpus that are executing in the guest context.
1538 * This will force the vcpu to exit and the cached EPT mappings
1539 * will be invalidated by the host before the next vmresume.
1541 static __inline void
1542 pmap_invalidate_ept(pmap_t pmap)
1547 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1548 ("pmap_invalidate_ept: absurd pm_active"));
1551 * The TLB mappings associated with a vcpu context are not
1552 * flushed each time a different vcpu is chosen to execute.
1554 * This is in contrast with a process's vtop mappings that
1555 * are flushed from the TLB on each context switch.
1557 * Therefore we need to do more than just a TLB shootdown on
1558 * the active cpus in 'pmap->pm_active'. To do this we keep
1559 * track of the number of invalidations performed on this pmap.
1561 * Each vcpu keeps a cache of this counter and compares it
1562 * just before a vmresume. If the counter is out-of-date an
1563 * invept will be done to flush stale mappings from the TLB.
1565 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1568 * Force the vcpu to exit and trap back into the hypervisor.
1570 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1571 ipi_selected(pmap->pm_active, ipinum);
1576 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1581 if (pmap_type_guest(pmap)) {
1582 pmap_invalidate_ept(pmap);
1586 KASSERT(pmap->pm_type == PT_X86,
1587 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1590 if (pmap == kernel_pmap) {
1594 cpuid = PCPU_GET(cpuid);
1595 if (pmap == PCPU_GET(curpmap))
1597 else if (pmap_pcid_enabled)
1598 pmap->pm_pcids[cpuid].pm_gen = 0;
1599 if (pmap_pcid_enabled) {
1602 pmap->pm_pcids[i].pm_gen = 0;
1605 mask = &pmap->pm_active;
1607 smp_masked_invlpg(*mask, va);
1611 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1612 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1615 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1621 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1622 pmap_invalidate_all(pmap);
1626 if (pmap_type_guest(pmap)) {
1627 pmap_invalidate_ept(pmap);
1631 KASSERT(pmap->pm_type == PT_X86,
1632 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1635 cpuid = PCPU_GET(cpuid);
1636 if (pmap == kernel_pmap) {
1637 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1641 if (pmap == PCPU_GET(curpmap)) {
1642 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1644 } else if (pmap_pcid_enabled) {
1645 pmap->pm_pcids[cpuid].pm_gen = 0;
1647 if (pmap_pcid_enabled) {
1650 pmap->pm_pcids[i].pm_gen = 0;
1653 mask = &pmap->pm_active;
1655 smp_masked_invlpg_range(*mask, sva, eva);
1660 pmap_invalidate_all(pmap_t pmap)
1663 struct invpcid_descr d;
1666 if (pmap_type_guest(pmap)) {
1667 pmap_invalidate_ept(pmap);
1671 KASSERT(pmap->pm_type == PT_X86,
1672 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1675 if (pmap == kernel_pmap) {
1676 if (pmap_pcid_enabled && invpcid_works) {
1677 bzero(&d, sizeof(d));
1678 invpcid(&d, INVPCID_CTXGLOB);
1684 cpuid = PCPU_GET(cpuid);
1685 if (pmap == PCPU_GET(curpmap)) {
1686 if (pmap_pcid_enabled) {
1687 if (invpcid_works) {
1688 d.pcid = pmap->pm_pcids[cpuid].pm_pcid;
1691 invpcid(&d, INVPCID_CTX);
1693 load_cr3(pmap->pm_cr3 | pmap->pm_pcids
1694 [PCPU_GET(cpuid)].pm_pcid);
1699 } else if (pmap_pcid_enabled) {
1700 pmap->pm_pcids[cpuid].pm_gen = 0;
1702 if (pmap_pcid_enabled) {
1705 pmap->pm_pcids[i].pm_gen = 0;
1708 mask = &pmap->pm_active;
1710 smp_masked_invltlb(*mask, pmap);
1715 pmap_invalidate_cache(void)
1725 cpuset_t invalidate; /* processors that invalidate their TLB */
1730 u_int store; /* processor that updates the PDE */
1734 pmap_update_pde_action(void *arg)
1736 struct pde_action *act = arg;
1738 if (act->store == PCPU_GET(cpuid))
1739 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1743 pmap_update_pde_teardown(void *arg)
1745 struct pde_action *act = arg;
1747 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1748 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1752 * Change the page size for the specified virtual address in a way that
1753 * prevents any possibility of the TLB ever having two entries that map the
1754 * same virtual address using different page sizes. This is the recommended
1755 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1756 * machine check exception for a TLB state that is improperly diagnosed as a
1760 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1762 struct pde_action act;
1763 cpuset_t active, other_cpus;
1767 cpuid = PCPU_GET(cpuid);
1768 other_cpus = all_cpus;
1769 CPU_CLR(cpuid, &other_cpus);
1770 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1773 active = pmap->pm_active;
1775 if (CPU_OVERLAP(&active, &other_cpus)) {
1777 act.invalidate = active;
1781 act.newpde = newpde;
1782 CPU_SET(cpuid, &active);
1783 smp_rendezvous_cpus(active,
1784 smp_no_rendezvous_barrier, pmap_update_pde_action,
1785 pmap_update_pde_teardown, &act);
1787 pmap_update_pde_store(pmap, pde, newpde);
1788 if (CPU_ISSET(cpuid, &active))
1789 pmap_update_pde_invalidate(pmap, va, newpde);
1795 * Normal, non-SMP, invalidation functions.
1798 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1801 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1805 KASSERT(pmap->pm_type == PT_X86,
1806 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1808 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1810 else if (pmap_pcid_enabled)
1811 pmap->pm_pcids[0].pm_gen = 0;
1815 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1819 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1823 KASSERT(pmap->pm_type == PT_X86,
1824 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1826 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1827 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1829 } else if (pmap_pcid_enabled) {
1830 pmap->pm_pcids[0].pm_gen = 0;
1835 pmap_invalidate_all(pmap_t pmap)
1837 struct invpcid_descr d;
1839 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1843 KASSERT(pmap->pm_type == PT_X86,
1844 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
1846 if (pmap == kernel_pmap) {
1847 if (pmap_pcid_enabled && invpcid_works) {
1848 bzero(&d, sizeof(d));
1849 invpcid(&d, INVPCID_CTXGLOB);
1853 } else if (pmap == PCPU_GET(curpmap)) {
1854 if (pmap_pcid_enabled) {
1855 if (invpcid_works) {
1856 d.pcid = pmap->pm_pcids[0].pm_pcid;
1859 invpcid(&d, INVPCID_CTX);
1861 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[0].
1867 } else if (pmap_pcid_enabled) {
1868 pmap->pm_pcids[0].pm_gen = 0;
1873 pmap_invalidate_cache(void)
1880 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1883 pmap_update_pde_store(pmap, pde, newpde);
1884 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1885 pmap_update_pde_invalidate(pmap, va, newpde);
1887 pmap->pm_pcids[0].pm_gen = 0;
1892 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
1896 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
1897 * by a promotion that did not invalidate the 512 4KB page mappings
1898 * that might exist in the TLB. Consequently, at this point, the TLB
1899 * may hold both 4KB and 2MB page mappings for the address range [va,
1900 * va + NBPDR). Therefore, the entire range must be invalidated here.
1901 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
1902 * 4KB page mappings for the address range [va, va + NBPDR), and so a
1903 * single INVLPG suffices to invalidate the 2MB page mapping from the
1906 if ((pde & PG_PROMOTED) != 0)
1907 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
1909 pmap_invalidate_page(pmap, va);
1912 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
1915 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
1919 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
1921 KASSERT((sva & PAGE_MASK) == 0,
1922 ("pmap_invalidate_cache_range: sva not page-aligned"));
1923 KASSERT((eva & PAGE_MASK) == 0,
1924 ("pmap_invalidate_cache_range: eva not page-aligned"));
1927 if ((cpu_feature & CPUID_SS) != 0 && !force)
1928 ; /* If "Self Snoop" is supported and allowed, do nothing. */
1929 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
1930 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1932 * XXX: Some CPUs fault, hang, or trash the local APIC
1933 * registers if we use CLFLUSH on the local APIC
1934 * range. The local APIC is always uncached, so we
1935 * don't need to flush for that range anyway.
1937 if (pmap_kextract(sva) == lapic_paddr)
1941 * Otherwise, do per-cache line flush. Use the sfence
1942 * instruction to insure that previous stores are
1943 * included in the write-back. The processor
1944 * propagates flush to other processors in the cache
1948 for (; sva < eva; sva += cpu_clflush_line_size)
1951 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
1952 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1953 if (pmap_kextract(sva) == lapic_paddr)
1956 * Writes are ordered by CLFLUSH on Intel CPUs.
1958 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1960 for (; sva < eva; sva += cpu_clflush_line_size)
1962 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1967 * No targeted cache flush methods are supported by CPU,
1968 * or the supplied range is bigger than 2MB.
1969 * Globally invalidate cache.
1971 pmap_invalidate_cache();
1976 * Remove the specified set of pages from the data and instruction caches.
1978 * In contrast to pmap_invalidate_cache_range(), this function does not
1979 * rely on the CPU's self-snoop feature, because it is intended for use
1980 * when moving pages into a different cache domain.
1983 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1985 vm_offset_t daddr, eva;
1989 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
1990 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1991 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
1992 pmap_invalidate_cache();
1996 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
1998 for (i = 0; i < count; i++) {
1999 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
2000 eva = daddr + PAGE_SIZE;
2001 for (; daddr < eva; daddr += cpu_clflush_line_size) {
2010 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2016 * Routine: pmap_extract
2018 * Extract the physical page address associated
2019 * with the given map/virtual_address pair.
2022 pmap_extract(pmap_t pmap, vm_offset_t va)
2026 pt_entry_t *pte, PG_V;
2030 PG_V = pmap_valid_bit(pmap);
2032 pdpe = pmap_pdpe(pmap, va);
2033 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2034 if ((*pdpe & PG_PS) != 0)
2035 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
2037 pde = pmap_pdpe_to_pde(pdpe, va);
2038 if ((*pde & PG_V) != 0) {
2039 if ((*pde & PG_PS) != 0) {
2040 pa = (*pde & PG_PS_FRAME) |
2043 pte = pmap_pde_to_pte(pde, va);
2044 pa = (*pte & PG_FRAME) |
2055 * Routine: pmap_extract_and_hold
2057 * Atomically extract and hold the physical page
2058 * with the given pmap and virtual address pair
2059 * if that mapping permits the given protection.
2062 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
2064 pd_entry_t pde, *pdep;
2065 pt_entry_t pte, PG_RW, PG_V;
2071 PG_RW = pmap_rw_bit(pmap);
2072 PG_V = pmap_valid_bit(pmap);
2075 pdep = pmap_pde(pmap, va);
2076 if (pdep != NULL && (pde = *pdep)) {
2078 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2079 if (vm_page_pa_tryrelock(pmap, (pde &
2080 PG_PS_FRAME) | (va & PDRMASK), &pa))
2082 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
2087 pte = *pmap_pde_to_pte(pdep, va);
2089 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2090 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2093 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
2104 pmap_kextract(vm_offset_t va)
2109 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2110 pa = DMAP_TO_PHYS(va);
2114 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2117 * Beware of a concurrent promotion that changes the
2118 * PDE at this point! For example, vtopte() must not
2119 * be used to access the PTE because it would use the
2120 * new PDE. It is, however, safe to use the old PDE
2121 * because the page table page is preserved by the
2124 pa = *pmap_pde_to_pte(&pde, va);
2125 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2131 /***************************************************
2132 * Low level mapping routines.....
2133 ***************************************************/
2136 * Add a wired page to the kva.
2137 * Note: not SMP coherent.
2140 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2145 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g);
2148 static __inline void
2149 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2155 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2156 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | cache_bits);
2160 * Remove a page from the kernel pagetables.
2161 * Note: not SMP coherent.
2164 pmap_kremove(vm_offset_t va)
2173 * Used to map a range of physical addresses into kernel
2174 * virtual address space.
2176 * The value passed in '*virt' is a suggested virtual address for
2177 * the mapping. Architectures which can support a direct-mapped
2178 * physical to virtual region can return the appropriate address
2179 * within that region, leaving '*virt' unchanged. Other
2180 * architectures should map the pages starting at '*virt' and
2181 * update '*virt' with the first usable address after the mapped
2185 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2187 return PHYS_TO_DMAP(start);
2192 * Add a list of wired pages to the kva
2193 * this routine is only used for temporary
2194 * kernel mappings that do not need to have
2195 * page modification or references recorded.
2196 * Note that old mappings are simply written
2197 * over. The page *must* be wired.
2198 * Note: SMP coherent. Uses a ranged shootdown IPI.
2201 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2203 pt_entry_t *endpte, oldpte, pa, *pte;
2209 endpte = pte + count;
2210 while (pte < endpte) {
2212 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2213 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2214 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2216 pte_store(pte, pa | pg_g | X86_PG_RW | X86_PG_V);
2220 if (__predict_false((oldpte & X86_PG_V) != 0))
2221 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2226 * This routine tears out page mappings from the
2227 * kernel -- it is meant only for temporary mappings.
2228 * Note: SMP coherent. Uses a ranged shootdown IPI.
2231 pmap_qremove(vm_offset_t sva, int count)
2236 while (count-- > 0) {
2237 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2241 pmap_invalidate_range(kernel_pmap, sva, va);
2244 /***************************************************
2245 * Page table page management routines.....
2246 ***************************************************/
2247 static __inline void
2248 pmap_free_zero_pages(struct spglist *free)
2253 for (count = 0; (m = SLIST_FIRST(free)) != NULL; count++) {
2254 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2255 /* Preserve the page's PG_ZERO setting. */
2256 vm_page_free_toq(m);
2258 atomic_subtract_int(&vm_cnt.v_wire_count, count);
2262 * Schedule the specified unused page table page to be freed. Specifically,
2263 * add the page to the specified list of pages that will be released to the
2264 * physical memory manager after the TLB has been updated.
2266 static __inline void
2267 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2268 boolean_t set_PG_ZERO)
2272 m->flags |= PG_ZERO;
2274 m->flags &= ~PG_ZERO;
2275 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2279 * Inserts the specified page table page into the specified pmap's collection
2280 * of idle page table pages. Each of a pmap's page table pages is responsible
2281 * for mapping a distinct range of virtual addresses. The pmap's collection is
2282 * ordered by this virtual address range.
2285 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2288 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2289 return (vm_radix_insert(&pmap->pm_root, mpte));
2293 * Removes the page table page mapping the specified virtual address from the
2294 * specified pmap's collection of idle page table pages, and returns it.
2295 * Otherwise, returns NULL if there is no page table page corresponding to the
2296 * specified virtual address.
2298 static __inline vm_page_t
2299 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
2302 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2303 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
2307 * Decrements a page table page's wire count, which is used to record the
2308 * number of valid page table entries within the page. If the wire count
2309 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2310 * page table page was unmapped and FALSE otherwise.
2312 static inline boolean_t
2313 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2317 if (m->wire_count == 0) {
2318 _pmap_unwire_ptp(pmap, va, m, free);
2325 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2328 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2330 * unmap the page table page
2332 if (m->pindex >= (NUPDE + NUPDPE)) {
2335 pml4 = pmap_pml4e(pmap, va);
2337 if (pmap->pm_pml4u != NULL && va <= VM_MAXUSER_ADDRESS) {
2338 pml4 = &pmap->pm_pml4u[pmap_pml4e_index(va)];
2341 } else if (m->pindex >= NUPDE) {
2344 pdp = pmap_pdpe(pmap, va);
2349 pd = pmap_pde(pmap, va);
2352 pmap_resident_count_dec(pmap, 1);
2353 if (m->pindex < NUPDE) {
2354 /* We just released a PT, unhold the matching PD */
2357 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2358 pmap_unwire_ptp(pmap, va, pdpg, free);
2360 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2361 /* We just released a PD, unhold the matching PDP */
2364 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2365 pmap_unwire_ptp(pmap, va, pdppg, free);
2369 * Put page on a list so that it is released after
2370 * *ALL* TLB shootdown is done
2372 pmap_add_delayed_free_list(m, free, TRUE);
2376 * After removing a page table entry, this routine is used to
2377 * conditionally free the page, and manage the hold/wire counts.
2380 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2381 struct spglist *free)
2385 if (va >= VM_MAXUSER_ADDRESS)
2387 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2388 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2389 return (pmap_unwire_ptp(pmap, va, mpte, free));
2393 pmap_pinit0(pmap_t pmap)
2397 PMAP_LOCK_INIT(pmap);
2398 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2399 pmap->pm_pml4u = NULL;
2400 pmap->pm_cr3 = KPML4phys;
2401 pmap->pm_ucr3 = ~0UL;
2402 pmap->pm_root.rt_root = 0;
2403 CPU_ZERO(&pmap->pm_active);
2404 TAILQ_INIT(&pmap->pm_pvchunk);
2405 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2406 pmap->pm_flags = pmap_flags;
2408 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2409 pmap->pm_pcids[i].pm_gen = 0;
2411 __pcpu[i].pc_kcr3 = ~0ul;
2413 PCPU_SET(curpmap, kernel_pmap);
2414 pmap_activate(curthread);
2415 CPU_FILL(&kernel_pmap->pm_active);
2419 pmap_pinit_pml4(vm_page_t pml4pg)
2421 pml4_entry_t *pm_pml4;
2424 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2426 /* Wire in kernel global address entries. */
2427 for (i = 0; i < NKPML4E; i++) {
2428 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2431 for (i = 0; i < ndmpdpphys; i++) {
2432 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2436 /* install self-referential address mapping entry(s) */
2437 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2438 X86_PG_A | X86_PG_M;
2442 pmap_pinit_pml4_pti(vm_page_t pml4pg)
2444 pml4_entry_t *pm_pml4;
2447 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2448 for (i = 0; i < NPML4EPG; i++)
2449 pm_pml4[i] = pti_pml4[i];
2453 * Initialize a preallocated and zeroed pmap structure,
2454 * such as one in a vmspace structure.
2457 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2459 vm_page_t pml4pg, pml4pgu;
2460 vm_paddr_t pml4phys;
2464 * allocate the page directory page
2466 pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
2467 VM_ALLOC_WIRED | VM_ALLOC_ZERO | VM_ALLOC_WAITOK);
2469 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2470 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2472 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2473 pmap->pm_pcids[i].pm_gen = 0;
2475 pmap->pm_cr3 = ~0l; /* initialize to an invalid value */
2476 pmap->pm_pml4u = NULL;
2478 pmap->pm_type = pm_type;
2479 if ((pml4pg->flags & PG_ZERO) == 0)
2480 pagezero(pmap->pm_pml4);
2483 * Do not install the host kernel mappings in the nested page
2484 * tables. These mappings are meaningless in the guest physical
2486 * Install minimal kernel mappings in PTI case.
2488 if (pm_type == PT_X86) {
2489 pmap->pm_cr3 = pml4phys;
2490 pmap_pinit_pml4(pml4pg);
2492 pml4pgu = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2493 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2494 pmap->pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(
2495 VM_PAGE_TO_PHYS(pml4pgu));
2496 pmap_pinit_pml4_pti(pml4pgu);
2497 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pml4pgu);
2501 pmap->pm_root.rt_root = 0;
2502 CPU_ZERO(&pmap->pm_active);
2503 TAILQ_INIT(&pmap->pm_pvchunk);
2504 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2505 pmap->pm_flags = flags;
2506 pmap->pm_eptgen = 0;
2512 pmap_pinit(pmap_t pmap)
2515 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2519 * This routine is called if the desired page table page does not exist.
2521 * If page table page allocation fails, this routine may sleep before
2522 * returning NULL. It sleeps only if a lock pointer was given.
2524 * Note: If a page allocation fails at page table level two or three,
2525 * one or two pages may be held during the wait, only to be released
2526 * afterwards. This conservative approach is easily argued to avoid
2530 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2532 vm_page_t m, pdppg, pdpg;
2533 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2535 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2537 PG_A = pmap_accessed_bit(pmap);
2538 PG_M = pmap_modified_bit(pmap);
2539 PG_V = pmap_valid_bit(pmap);
2540 PG_RW = pmap_rw_bit(pmap);
2543 * Allocate a page table page.
2545 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2546 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2547 if (lockp != NULL) {
2548 RELEASE_PV_LIST_LOCK(lockp);
2550 PMAP_ASSERT_NOT_IN_DI();
2556 * Indicate the need to retry. While waiting, the page table
2557 * page may have been allocated.
2561 if ((m->flags & PG_ZERO) == 0)
2565 * Map the pagetable page into the process address space, if
2566 * it isn't already there.
2569 if (ptepindex >= (NUPDE + NUPDPE)) {
2570 pml4_entry_t *pml4, *pml4u;
2571 vm_pindex_t pml4index;
2573 /* Wire up a new PDPE page */
2574 pml4index = ptepindex - (NUPDE + NUPDPE);
2575 pml4 = &pmap->pm_pml4[pml4index];
2576 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2577 if (pmap->pm_pml4u != NULL && pml4index < NUPML4E) {
2579 * PTI: Make all user-space mappings in the
2580 * kernel-mode page table no-execute so that
2581 * we detect any programming errors that leave
2582 * the kernel-mode page table active on return
2587 pml4u = &pmap->pm_pml4u[pml4index];
2588 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
2592 } else if (ptepindex >= NUPDE) {
2593 vm_pindex_t pml4index;
2594 vm_pindex_t pdpindex;
2598 /* Wire up a new PDE page */
2599 pdpindex = ptepindex - NUPDE;
2600 pml4index = pdpindex >> NPML4EPGSHIFT;
2602 pml4 = &pmap->pm_pml4[pml4index];
2603 if ((*pml4 & PG_V) == 0) {
2604 /* Have to allocate a new pdp, recurse */
2605 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2608 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2609 vm_page_free_zero(m);
2613 /* Add reference to pdp page */
2614 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2615 pdppg->wire_count++;
2617 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2619 /* Now find the pdp page */
2620 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2621 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2624 vm_pindex_t pml4index;
2625 vm_pindex_t pdpindex;
2630 /* Wire up a new PTE page */
2631 pdpindex = ptepindex >> NPDPEPGSHIFT;
2632 pml4index = pdpindex >> NPML4EPGSHIFT;
2634 /* First, find the pdp and check that its valid. */
2635 pml4 = &pmap->pm_pml4[pml4index];
2636 if ((*pml4 & PG_V) == 0) {
2637 /* Have to allocate a new pd, recurse */
2638 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2641 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2642 vm_page_free_zero(m);
2645 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2646 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2648 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2649 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2650 if ((*pdp & PG_V) == 0) {
2651 /* Have to allocate a new pd, recurse */
2652 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2655 atomic_subtract_int(&vm_cnt.v_wire_count,
2657 vm_page_free_zero(m);
2661 /* Add reference to the pd page */
2662 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2666 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2668 /* Now we know where the page directory page is */
2669 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2670 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2673 pmap_resident_count_inc(pmap, 1);
2679 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2681 vm_pindex_t pdpindex, ptepindex;
2682 pdp_entry_t *pdpe, PG_V;
2685 PG_V = pmap_valid_bit(pmap);
2688 pdpe = pmap_pdpe(pmap, va);
2689 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2690 /* Add a reference to the pd page. */
2691 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2694 /* Allocate a pd page. */
2695 ptepindex = pmap_pde_pindex(va);
2696 pdpindex = ptepindex >> NPDPEPGSHIFT;
2697 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2698 if (pdpg == NULL && lockp != NULL)
2705 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2707 vm_pindex_t ptepindex;
2708 pd_entry_t *pd, PG_V;
2711 PG_V = pmap_valid_bit(pmap);
2714 * Calculate pagetable page index
2716 ptepindex = pmap_pde_pindex(va);
2719 * Get the page directory entry
2721 pd = pmap_pde(pmap, va);
2724 * This supports switching from a 2MB page to a
2727 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2728 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2730 * Invalidation of the 2MB page mapping may have caused
2731 * the deallocation of the underlying PD page.
2738 * If the page table page is mapped, we just increment the
2739 * hold count, and activate it.
2741 if (pd != NULL && (*pd & PG_V) != 0) {
2742 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2746 * Here if the pte page isn't mapped, or if it has been
2749 m = _pmap_allocpte(pmap, ptepindex, lockp);
2750 if (m == NULL && lockp != NULL)
2757 /***************************************************
2758 * Pmap allocation/deallocation routines.
2759 ***************************************************/
2762 * Release any resources held by the given physical map.
2763 * Called when a pmap initialized by pmap_pinit is being released.
2764 * Should only be called if the map contains no valid mappings.
2767 pmap_release(pmap_t pmap)
2772 KASSERT(pmap->pm_stats.resident_count == 0,
2773 ("pmap_release: pmap resident count %ld != 0",
2774 pmap->pm_stats.resident_count));
2775 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2776 ("pmap_release: pmap has reserved page table page(s)"));
2777 KASSERT(CPU_EMPTY(&pmap->pm_active),
2778 ("releasing active pmap %p", pmap));
2780 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2782 for (i = 0; i < NKPML4E; i++) /* KVA */
2783 pmap->pm_pml4[KPML4BASE + i] = 0;
2784 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
2785 pmap->pm_pml4[DMPML4I + i] = 0;
2786 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
2789 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2790 vm_page_free_zero(m);
2792 if (pmap->pm_pml4u != NULL) {
2793 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4u));
2795 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2801 kvm_size(SYSCTL_HANDLER_ARGS)
2803 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2805 return sysctl_handle_long(oidp, &ksize, 0, req);
2807 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2808 0, 0, kvm_size, "LU", "Size of KVM");
2811 kvm_free(SYSCTL_HANDLER_ARGS)
2813 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2815 return sysctl_handle_long(oidp, &kfree, 0, req);
2817 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2818 0, 0, kvm_free, "LU", "Amount of KVM free");
2821 * grow the number of kernel page table entries, if needed
2824 pmap_growkernel(vm_offset_t addr)
2828 pd_entry_t *pde, newpdir;
2831 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2834 * Return if "addr" is within the range of kernel page table pages
2835 * that were preallocated during pmap bootstrap. Moreover, leave
2836 * "kernel_vm_end" and the kernel page table as they were.
2838 * The correctness of this action is based on the following
2839 * argument: vm_map_insert() allocates contiguous ranges of the
2840 * kernel virtual address space. It calls this function if a range
2841 * ends after "kernel_vm_end". If the kernel is mapped between
2842 * "kernel_vm_end" and "addr", then the range cannot begin at
2843 * "kernel_vm_end". In fact, its beginning address cannot be less
2844 * than the kernel. Thus, there is no immediate need to allocate
2845 * any new kernel page table pages between "kernel_vm_end" and
2848 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
2851 addr = roundup2(addr, NBPDR);
2852 if (addr - 1 >= kernel_map->max_offset)
2853 addr = kernel_map->max_offset;
2854 while (kernel_vm_end < addr) {
2855 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
2856 if ((*pdpe & X86_PG_V) == 0) {
2857 /* We need a new PDP entry */
2858 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
2859 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
2860 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2862 panic("pmap_growkernel: no memory to grow kernel");
2863 if ((nkpg->flags & PG_ZERO) == 0)
2864 pmap_zero_page(nkpg);
2865 paddr = VM_PAGE_TO_PHYS(nkpg);
2866 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
2867 X86_PG_A | X86_PG_M);
2868 continue; /* try again */
2870 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
2871 if ((*pde & X86_PG_V) != 0) {
2872 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2873 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2874 kernel_vm_end = kernel_map->max_offset;
2880 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
2881 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
2884 panic("pmap_growkernel: no memory to grow kernel");
2885 if ((nkpg->flags & PG_ZERO) == 0)
2886 pmap_zero_page(nkpg);
2887 paddr = VM_PAGE_TO_PHYS(nkpg);
2888 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
2889 pde_store(pde, newpdir);
2891 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2892 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2893 kernel_vm_end = kernel_map->max_offset;
2900 /***************************************************
2901 * page management routines.
2902 ***************************************************/
2904 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
2905 CTASSERT(_NPCM == 3);
2906 CTASSERT(_NPCPV == 168);
2908 static __inline struct pv_chunk *
2909 pv_to_chunk(pv_entry_t pv)
2912 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
2915 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
2917 #define PC_FREE0 0xfffffffffffffffful
2918 #define PC_FREE1 0xfffffffffffffffful
2919 #define PC_FREE2 0x000000fffffffffful
2921 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
2924 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2926 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2927 "Current number of pv entry chunks");
2928 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2929 "Current number of pv entry chunks allocated");
2930 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2931 "Current number of pv entry chunks frees");
2932 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
2933 "Number of times tried to get a chunk page but failed.");
2935 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
2936 static int pv_entry_spare;
2938 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2939 "Current number of pv entry frees");
2940 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
2941 "Current number of pv entry allocs");
2942 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2943 "Current number of pv entries");
2944 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2945 "Current number of spare pv entries");
2949 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
2954 pmap_invalidate_all(pmap);
2955 if (pmap != locked_pmap)
2958 pmap_delayed_invl_finished();
2962 * We are in a serious low memory condition. Resort to
2963 * drastic measures to free some pages so we can allocate
2964 * another pv entry chunk.
2966 * Returns NULL if PV entries were reclaimed from the specified pmap.
2968 * We do not, however, unmap 2mpages because subsequent accesses will
2969 * allocate per-page pv entries until repromotion occurs, thereby
2970 * exacerbating the shortage of free pv entries.
2973 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
2975 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
2976 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
2977 struct md_page *pvh;
2979 pmap_t next_pmap, pmap;
2980 pt_entry_t *pte, tpte;
2981 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
2985 struct spglist free;
2987 int bit, field, freed;
2989 static int active_reclaims = 0;
2991 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2992 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
2995 PG_G = PG_A = PG_M = PG_RW = 0;
2997 bzero(&pc_marker_b, sizeof(pc_marker_b));
2998 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
2999 pc_marker = (struct pv_chunk *)&pc_marker_b;
3000 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
3003 * A delayed invalidation block should already be active if
3004 * pmap_advise() or pmap_remove() called this function by way
3005 * of pmap_demote_pde_locked().
3007 start_di = pmap_not_in_di();
3009 mtx_lock(&pv_chunks_mutex);
3011 TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
3012 TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
3013 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
3014 SLIST_EMPTY(&free)) {
3015 next_pmap = pc->pc_pmap;
3016 if (next_pmap == NULL) {
3018 * The next chunk is a marker. However, it is
3019 * not our marker, so active_reclaims must be
3020 * > 1. Consequently, the next_chunk code
3021 * will not rotate the pv_chunks list.
3025 mtx_unlock(&pv_chunks_mutex);
3028 * A pv_chunk can only be removed from the pc_lru list
3029 * when both pc_chunks_mutex is owned and the
3030 * corresponding pmap is locked.
3032 if (pmap != next_pmap) {
3033 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
3036 /* Avoid deadlock and lock recursion. */
3037 if (pmap > locked_pmap) {
3038 RELEASE_PV_LIST_LOCK(lockp);
3041 pmap_delayed_invl_started();
3042 mtx_lock(&pv_chunks_mutex);
3044 } else if (pmap != locked_pmap) {
3045 if (PMAP_TRYLOCK(pmap)) {
3047 pmap_delayed_invl_started();
3048 mtx_lock(&pv_chunks_mutex);
3051 pmap = NULL; /* pmap is not locked */
3052 mtx_lock(&pv_chunks_mutex);
3053 pc = TAILQ_NEXT(pc_marker, pc_lru);
3055 pc->pc_pmap != next_pmap)
3059 } else if (start_di)
3060 pmap_delayed_invl_started();
3061 PG_G = pmap_global_bit(pmap);
3062 PG_A = pmap_accessed_bit(pmap);
3063 PG_M = pmap_modified_bit(pmap);
3064 PG_RW = pmap_rw_bit(pmap);
3068 * Destroy every non-wired, 4 KB page mapping in the chunk.
3071 for (field = 0; field < _NPCM; field++) {
3072 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
3073 inuse != 0; inuse &= ~(1UL << bit)) {
3075 pv = &pc->pc_pventry[field * 64 + bit];
3077 pde = pmap_pde(pmap, va);
3078 if ((*pde & PG_PS) != 0)
3080 pte = pmap_pde_to_pte(pde, va);
3081 if ((*pte & PG_W) != 0)
3083 tpte = pte_load_clear(pte);
3084 if ((tpte & PG_G) != 0)
3085 pmap_invalidate_page(pmap, va);
3086 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3087 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3089 if ((tpte & PG_A) != 0)
3090 vm_page_aflag_set(m, PGA_REFERENCED);
3091 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3092 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3094 if (TAILQ_EMPTY(&m->md.pv_list) &&
3095 (m->flags & PG_FICTITIOUS) == 0) {
3096 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3097 if (TAILQ_EMPTY(&pvh->pv_list)) {
3098 vm_page_aflag_clear(m,
3102 pmap_delayed_invl_page(m);
3103 pc->pc_map[field] |= 1UL << bit;
3104 pmap_unuse_pt(pmap, va, *pde, &free);
3109 mtx_lock(&pv_chunks_mutex);
3112 /* Every freed mapping is for a 4 KB page. */
3113 pmap_resident_count_dec(pmap, freed);
3114 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
3115 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
3116 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
3117 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3118 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
3119 pc->pc_map[2] == PC_FREE2) {
3120 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3121 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3122 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3123 /* Entire chunk is free; return it. */
3124 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3125 dump_drop_page(m_pc->phys_addr);
3126 mtx_lock(&pv_chunks_mutex);
3127 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3130 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3131 mtx_lock(&pv_chunks_mutex);
3132 /* One freed pv entry in locked_pmap is sufficient. */
3133 if (pmap == locked_pmap)
3136 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3137 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
3138 if (active_reclaims == 1 && pmap != NULL) {
3140 * Rotate the pv chunks list so that we do not
3141 * scan the same pv chunks that could not be
3142 * freed (because they contained a wired
3143 * and/or superpage mapping) on every
3144 * invocation of reclaim_pv_chunk().
3146 while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
3147 MPASS(pc->pc_pmap != NULL);
3148 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3149 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3153 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3154 TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
3156 mtx_unlock(&pv_chunks_mutex);
3157 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
3158 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
3159 m_pc = SLIST_FIRST(&free);
3160 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3161 /* Recycle a freed page table page. */
3162 m_pc->wire_count = 1;
3164 pmap_free_zero_pages(&free);
3169 * free the pv_entry back to the free list
3172 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3174 struct pv_chunk *pc;
3175 int idx, field, bit;
3177 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3178 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3179 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3180 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3181 pc = pv_to_chunk(pv);
3182 idx = pv - &pc->pc_pventry[0];
3185 pc->pc_map[field] |= 1ul << bit;
3186 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3187 pc->pc_map[2] != PC_FREE2) {
3188 /* 98% of the time, pc is already at the head of the list. */
3189 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3190 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3191 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3195 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3200 free_pv_chunk(struct pv_chunk *pc)
3204 mtx_lock(&pv_chunks_mutex);
3205 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3206 mtx_unlock(&pv_chunks_mutex);
3207 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3208 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3209 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3210 /* entire chunk is free, return it */
3211 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3212 dump_drop_page(m->phys_addr);
3213 vm_page_unwire(m, PQ_NONE);
3218 * Returns a new PV entry, allocating a new PV chunk from the system when
3219 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3220 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3223 * The given PV list lock may be released.
3226 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3230 struct pv_chunk *pc;
3233 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3234 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3236 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3238 for (field = 0; field < _NPCM; field++) {
3239 if (pc->pc_map[field]) {
3240 bit = bsfq(pc->pc_map[field]);
3244 if (field < _NPCM) {
3245 pv = &pc->pc_pventry[field * 64 + bit];
3246 pc->pc_map[field] &= ~(1ul << bit);
3247 /* If this was the last item, move it to tail */
3248 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3249 pc->pc_map[2] == 0) {
3250 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3251 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3254 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3255 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3259 /* No free items, allocate another chunk */
3260 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3263 if (lockp == NULL) {
3264 PV_STAT(pc_chunk_tryfail++);
3267 m = reclaim_pv_chunk(pmap, lockp);
3271 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3272 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3273 dump_add_page(m->phys_addr);
3274 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3276 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3277 pc->pc_map[1] = PC_FREE1;
3278 pc->pc_map[2] = PC_FREE2;
3279 mtx_lock(&pv_chunks_mutex);
3280 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3281 mtx_unlock(&pv_chunks_mutex);
3282 pv = &pc->pc_pventry[0];
3283 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3284 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3285 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3290 * Returns the number of one bits within the given PV chunk map.
3292 * The erratas for Intel processors state that "POPCNT Instruction May
3293 * Take Longer to Execute Than Expected". It is believed that the
3294 * issue is the spurious dependency on the destination register.
3295 * Provide a hint to the register rename logic that the destination
3296 * value is overwritten, by clearing it, as suggested in the
3297 * optimization manual. It should be cheap for unaffected processors
3300 * Reference numbers for erratas are
3301 * 4th Gen Core: HSD146
3302 * 5th Gen Core: BDM85
3303 * 6th Gen Core: SKL029
3306 popcnt_pc_map_pq(uint64_t *map)
3310 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3311 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3312 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3313 : "=&r" (result), "=&r" (tmp)
3314 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3319 * Ensure that the number of spare PV entries in the specified pmap meets or
3320 * exceeds the given count, "needed".
3322 * The given PV list lock may be released.
3325 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3327 struct pch new_tail;
3328 struct pv_chunk *pc;
3332 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3333 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3336 * Newly allocated PV chunks must be stored in a private list until
3337 * the required number of PV chunks have been allocated. Otherwise,
3338 * reclaim_pv_chunk() could recycle one of these chunks. In
3339 * contrast, these chunks must be added to the pmap upon allocation.
3341 TAILQ_INIT(&new_tail);
3344 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3346 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3347 bit_count((bitstr_t *)pc->pc_map, 0,
3348 sizeof(pc->pc_map) * NBBY, &free);
3351 free = popcnt_pc_map_pq(pc->pc_map);
3355 if (avail >= needed)
3358 for (; avail < needed; avail += _NPCPV) {
3359 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3362 m = reclaim_pv_chunk(pmap, lockp);
3366 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3367 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3368 dump_add_page(m->phys_addr);
3369 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3371 pc->pc_map[0] = PC_FREE0;
3372 pc->pc_map[1] = PC_FREE1;
3373 pc->pc_map[2] = PC_FREE2;
3374 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3375 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3376 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3378 if (!TAILQ_EMPTY(&new_tail)) {
3379 mtx_lock(&pv_chunks_mutex);
3380 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3381 mtx_unlock(&pv_chunks_mutex);
3386 * First find and then remove the pv entry for the specified pmap and virtual
3387 * address from the specified pv list. Returns the pv entry if found and NULL
3388 * otherwise. This operation can be performed on pv lists for either 4KB or
3389 * 2MB page mappings.
3391 static __inline pv_entry_t
3392 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3396 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3397 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3398 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3407 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3408 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3409 * entries for each of the 4KB page mappings.
3412 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3413 struct rwlock **lockp)
3415 struct md_page *pvh;
3416 struct pv_chunk *pc;
3418 vm_offset_t va_last;
3422 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3423 KASSERT((pa & PDRMASK) == 0,
3424 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3425 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3428 * Transfer the 2mpage's pv entry for this mapping to the first
3429 * page's pv list. Once this transfer begins, the pv list lock
3430 * must not be released until the last pv entry is reinstantiated.
3432 pvh = pa_to_pvh(pa);
3433 va = trunc_2mpage(va);
3434 pv = pmap_pvh_remove(pvh, pmap, va);
3435 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3436 m = PHYS_TO_VM_PAGE(pa);
3437 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3439 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3440 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3441 va_last = va + NBPDR - PAGE_SIZE;
3443 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3444 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3445 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3446 for (field = 0; field < _NPCM; field++) {
3447 while (pc->pc_map[field]) {
3448 bit = bsfq(pc->pc_map[field]);
3449 pc->pc_map[field] &= ~(1ul << bit);
3450 pv = &pc->pc_pventry[field * 64 + bit];
3454 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3455 ("pmap_pv_demote_pde: page %p is not managed", m));
3456 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3462 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3463 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3466 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3467 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3468 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3470 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3471 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3474 #if VM_NRESERVLEVEL > 0
3476 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3477 * replace the many pv entries for the 4KB page mappings by a single pv entry
3478 * for the 2MB page mapping.
3481 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3482 struct rwlock **lockp)
3484 struct md_page *pvh;
3486 vm_offset_t va_last;
3489 KASSERT((pa & PDRMASK) == 0,
3490 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3491 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3494 * Transfer the first page's pv entry for this mapping to the 2mpage's
3495 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3496 * a transfer avoids the possibility that get_pv_entry() calls
3497 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3498 * mappings that is being promoted.
3500 m = PHYS_TO_VM_PAGE(pa);
3501 va = trunc_2mpage(va);
3502 pv = pmap_pvh_remove(&m->md, pmap, va);
3503 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3504 pvh = pa_to_pvh(pa);
3505 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3507 /* Free the remaining NPTEPG - 1 pv entries. */
3508 va_last = va + NBPDR - PAGE_SIZE;
3512 pmap_pvh_free(&m->md, pmap, va);
3513 } while (va < va_last);
3515 #endif /* VM_NRESERVLEVEL > 0 */
3518 * First find and then destroy the pv entry for the specified pmap and virtual
3519 * address. This operation can be performed on pv lists for either 4KB or 2MB
3523 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3527 pv = pmap_pvh_remove(pvh, pmap, va);
3528 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3529 free_pv_entry(pmap, pv);
3533 * Conditionally create the PV entry for a 4KB page mapping if the required
3534 * memory can be allocated without resorting to reclamation.
3537 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3538 struct rwlock **lockp)
3542 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3543 /* Pass NULL instead of the lock pointer to disable reclamation. */
3544 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3546 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3547 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3555 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3556 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3557 * false if the PV entry cannot be allocated without resorting to reclamation.
3560 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
3561 struct rwlock **lockp)
3563 struct md_page *pvh;
3567 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3568 /* Pass NULL instead of the lock pointer to disable reclamation. */
3569 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3570 NULL : lockp)) == NULL)
3573 pa = pde & PG_PS_FRAME;
3574 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3575 pvh = pa_to_pvh(pa);
3576 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3582 * Fills a page table page with mappings to consecutive physical pages.
3585 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3589 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3591 newpte += PAGE_SIZE;
3596 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3597 * mapping is invalidated.
3600 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3602 struct rwlock *lock;
3606 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3613 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3614 struct rwlock **lockp)
3616 pd_entry_t newpde, oldpde;
3617 pt_entry_t *firstpte, newpte;
3618 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3621 struct spglist free;
3625 PG_G = pmap_global_bit(pmap);
3626 PG_A = pmap_accessed_bit(pmap);
3627 PG_M = pmap_modified_bit(pmap);
3628 PG_RW = pmap_rw_bit(pmap);
3629 PG_V = pmap_valid_bit(pmap);
3630 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3632 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3634 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3635 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3636 if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
3638 KASSERT((oldpde & PG_W) == 0,
3639 ("pmap_demote_pde: page table page for a wired mapping"
3643 * Invalidate the 2MB page mapping and return "failure" if the
3644 * mapping was never accessed or the allocation of the new
3645 * page table page fails. If the 2MB page mapping belongs to
3646 * the direct map region of the kernel's address space, then
3647 * the page allocation request specifies the highest possible
3648 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3649 * normal. Page table pages are preallocated for every other
3650 * part of the kernel address space, so the direct map region
3651 * is the only part of the kernel address space that must be
3654 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3655 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3656 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3657 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3659 sva = trunc_2mpage(va);
3660 pmap_remove_pde(pmap, pde, sva, &free, lockp);
3661 if ((oldpde & PG_G) == 0)
3662 pmap_invalidate_pde_page(pmap, sva, oldpde);
3663 pmap_free_zero_pages(&free);
3664 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3665 " in pmap %p", va, pmap);
3668 if (va < VM_MAXUSER_ADDRESS)
3669 pmap_resident_count_inc(pmap, 1);
3671 mptepa = VM_PAGE_TO_PHYS(mpte);
3672 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3673 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3674 KASSERT((oldpde & PG_A) != 0,
3675 ("pmap_demote_pde: oldpde is missing PG_A"));
3676 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3677 ("pmap_demote_pde: oldpde is missing PG_M"));
3678 newpte = oldpde & ~PG_PS;
3679 newpte = pmap_swap_pat(pmap, newpte);
3682 * If the page table page is new, initialize it.
3684 if (mpte->wire_count == 1) {
3685 mpte->wire_count = NPTEPG;
3686 pmap_fill_ptp(firstpte, newpte);
3688 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3689 ("pmap_demote_pde: firstpte and newpte map different physical"
3693 * If the mapping has changed attributes, update the page table
3696 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3697 pmap_fill_ptp(firstpte, newpte);
3700 * The spare PV entries must be reserved prior to demoting the
3701 * mapping, that is, prior to changing the PDE. Otherwise, the state
3702 * of the PDE and the PV lists will be inconsistent, which can result
3703 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3704 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3705 * PV entry for the 2MB page mapping that is being demoted.
3707 if ((oldpde & PG_MANAGED) != 0)
3708 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3711 * Demote the mapping. This pmap is locked. The old PDE has
3712 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3713 * set. Thus, there is no danger of a race with another
3714 * processor changing the setting of PG_A and/or PG_M between
3715 * the read above and the store below.
3717 if (workaround_erratum383)
3718 pmap_update_pde(pmap, va, pde, newpde);
3720 pde_store(pde, newpde);
3723 * Invalidate a stale recursive mapping of the page table page.
3725 if (va >= VM_MAXUSER_ADDRESS)
3726 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3729 * Demote the PV entry.
3731 if ((oldpde & PG_MANAGED) != 0)
3732 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3734 atomic_add_long(&pmap_pde_demotions, 1);
3735 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3736 " in pmap %p", va, pmap);
3741 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3744 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3750 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3751 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3752 mpte = pmap_remove_pt_page(pmap, va);
3754 panic("pmap_remove_kernel_pde: Missing pt page.");
3756 mptepa = VM_PAGE_TO_PHYS(mpte);
3757 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3760 * Initialize the page table page.
3762 pagezero((void *)PHYS_TO_DMAP(mptepa));
3765 * Demote the mapping.
3767 if (workaround_erratum383)
3768 pmap_update_pde(pmap, va, pde, newpde);
3770 pde_store(pde, newpde);
3773 * Invalidate a stale recursive mapping of the page table page.
3775 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3779 * pmap_remove_pde: do the things to unmap a superpage in a process
3782 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
3783 struct spglist *free, struct rwlock **lockp)
3785 struct md_page *pvh;
3787 vm_offset_t eva, va;
3789 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3791 PG_G = pmap_global_bit(pmap);
3792 PG_A = pmap_accessed_bit(pmap);
3793 PG_M = pmap_modified_bit(pmap);
3794 PG_RW = pmap_rw_bit(pmap);
3796 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3797 KASSERT((sva & PDRMASK) == 0,
3798 ("pmap_remove_pde: sva is not 2mpage aligned"));
3799 oldpde = pte_load_clear(pdq);
3801 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
3802 if ((oldpde & PG_G) != 0)
3803 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
3804 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
3805 if (oldpde & PG_MANAGED) {
3806 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
3807 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
3808 pmap_pvh_free(pvh, pmap, sva);
3810 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3811 va < eva; va += PAGE_SIZE, m++) {
3812 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3815 vm_page_aflag_set(m, PGA_REFERENCED);
3816 if (TAILQ_EMPTY(&m->md.pv_list) &&
3817 TAILQ_EMPTY(&pvh->pv_list))
3818 vm_page_aflag_clear(m, PGA_WRITEABLE);
3819 pmap_delayed_invl_page(m);
3822 if (pmap == kernel_pmap) {
3823 pmap_remove_kernel_pde(pmap, pdq, sva);
3825 mpte = pmap_remove_pt_page(pmap, sva);
3827 pmap_resident_count_dec(pmap, 1);
3828 KASSERT(mpte->wire_count == NPTEPG,
3829 ("pmap_remove_pde: pte page wire count error"));
3830 mpte->wire_count = 0;
3831 pmap_add_delayed_free_list(mpte, free, FALSE);
3834 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
3838 * pmap_remove_pte: do the things to unmap a page in a process
3841 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
3842 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
3844 struct md_page *pvh;
3845 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
3848 PG_A = pmap_accessed_bit(pmap);
3849 PG_M = pmap_modified_bit(pmap);
3850 PG_RW = pmap_rw_bit(pmap);
3852 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3853 oldpte = pte_load_clear(ptq);
3855 pmap->pm_stats.wired_count -= 1;
3856 pmap_resident_count_dec(pmap, 1);
3857 if (oldpte & PG_MANAGED) {
3858 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
3859 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3862 vm_page_aflag_set(m, PGA_REFERENCED);
3863 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3864 pmap_pvh_free(&m->md, pmap, va);
3865 if (TAILQ_EMPTY(&m->md.pv_list) &&
3866 (m->flags & PG_FICTITIOUS) == 0) {
3867 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3868 if (TAILQ_EMPTY(&pvh->pv_list))
3869 vm_page_aflag_clear(m, PGA_WRITEABLE);
3871 pmap_delayed_invl_page(m);
3873 return (pmap_unuse_pt(pmap, va, ptepde, free));
3877 * Remove a single page from a process address space
3880 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
3881 struct spglist *free)
3883 struct rwlock *lock;
3884 pt_entry_t *pte, PG_V;
3886 PG_V = pmap_valid_bit(pmap);
3887 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3888 if ((*pde & PG_V) == 0)
3890 pte = pmap_pde_to_pte(pde, va);
3891 if ((*pte & PG_V) == 0)
3894 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
3897 pmap_invalidate_page(pmap, va);
3901 * Removes the specified range of addresses from the page table page.
3904 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
3905 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
3907 pt_entry_t PG_G, *pte;
3911 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3912 PG_G = pmap_global_bit(pmap);
3915 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
3919 pmap_invalidate_range(pmap, va, sva);
3924 if ((*pte & PG_G) == 0)
3928 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
3934 pmap_invalidate_range(pmap, va, sva);
3939 * Remove the given range of addresses from the specified map.
3941 * It is assumed that the start and end are properly
3942 * rounded to the page size.
3945 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3947 struct rwlock *lock;
3948 vm_offset_t va_next;
3949 pml4_entry_t *pml4e;
3951 pd_entry_t ptpaddr, *pde;
3952 pt_entry_t PG_G, PG_V;
3953 struct spglist free;
3956 PG_G = pmap_global_bit(pmap);
3957 PG_V = pmap_valid_bit(pmap);
3960 * Perform an unsynchronized read. This is, however, safe.
3962 if (pmap->pm_stats.resident_count == 0)
3968 pmap_delayed_invl_started();
3972 * special handling of removing one page. a very
3973 * common operation and easy to short circuit some
3976 if (sva + PAGE_SIZE == eva) {
3977 pde = pmap_pde(pmap, sva);
3978 if (pde && (*pde & PG_PS) == 0) {
3979 pmap_remove_page(pmap, sva, pde, &free);
3985 for (; sva < eva; sva = va_next) {
3987 if (pmap->pm_stats.resident_count == 0)
3990 pml4e = pmap_pml4e(pmap, sva);
3991 if ((*pml4e & PG_V) == 0) {
3992 va_next = (sva + NBPML4) & ~PML4MASK;
3998 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
3999 if ((*pdpe & PG_V) == 0) {
4000 va_next = (sva + NBPDP) & ~PDPMASK;
4007 * Calculate index for next page table.
4009 va_next = (sva + NBPDR) & ~PDRMASK;
4013 pde = pmap_pdpe_to_pde(pdpe, sva);
4017 * Weed out invalid mappings.
4023 * Check for large page.
4025 if ((ptpaddr & PG_PS) != 0) {
4027 * Are we removing the entire large page? If not,
4028 * demote the mapping and fall through.
4030 if (sva + NBPDR == va_next && eva >= va_next) {
4032 * The TLB entry for a PG_G mapping is
4033 * invalidated by pmap_remove_pde().
4035 if ((ptpaddr & PG_G) == 0)
4037 pmap_remove_pde(pmap, pde, sva, &free, &lock);
4039 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
4041 /* The large page mapping was destroyed. */
4048 * Limit our scan to either the end of the va represented
4049 * by the current page table page, or to the end of the
4050 * range being removed.
4055 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
4062 pmap_invalidate_all(pmap);
4064 pmap_delayed_invl_finished();
4065 pmap_free_zero_pages(&free);
4069 * Routine: pmap_remove_all
4071 * Removes this physical page from
4072 * all physical maps in which it resides.
4073 * Reflects back modify bits to the pager.
4076 * Original versions of this routine were very
4077 * inefficient because they iteratively called
4078 * pmap_remove (slow...)
4082 pmap_remove_all(vm_page_t m)
4084 struct md_page *pvh;
4087 struct rwlock *lock;
4088 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
4091 struct spglist free;
4092 int pvh_gen, md_gen;
4094 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4095 ("pmap_remove_all: page %p is not managed", m));
4097 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4098 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
4099 pa_to_pvh(VM_PAGE_TO_PHYS(m));
4102 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
4104 if (!PMAP_TRYLOCK(pmap)) {
4105 pvh_gen = pvh->pv_gen;
4109 if (pvh_gen != pvh->pv_gen) {
4116 pde = pmap_pde(pmap, va);
4117 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
4120 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4122 if (!PMAP_TRYLOCK(pmap)) {
4123 pvh_gen = pvh->pv_gen;
4124 md_gen = m->md.pv_gen;
4128 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
4134 PG_A = pmap_accessed_bit(pmap);
4135 PG_M = pmap_modified_bit(pmap);
4136 PG_RW = pmap_rw_bit(pmap);
4137 pmap_resident_count_dec(pmap, 1);
4138 pde = pmap_pde(pmap, pv->pv_va);
4139 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
4140 " a 2mpage in page %p's pv list", m));
4141 pte = pmap_pde_to_pte(pde, pv->pv_va);
4142 tpte = pte_load_clear(pte);
4144 pmap->pm_stats.wired_count--;
4146 vm_page_aflag_set(m, PGA_REFERENCED);
4149 * Update the vm_page_t clean and reference bits.
4151 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4153 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
4154 pmap_invalidate_page(pmap, pv->pv_va);
4155 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4157 free_pv_entry(pmap, pv);
4160 vm_page_aflag_clear(m, PGA_WRITEABLE);
4162 pmap_delayed_invl_wait(m);
4163 pmap_free_zero_pages(&free);
4167 * pmap_protect_pde: do the things to protect a 2mpage in a process
4170 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
4172 pd_entry_t newpde, oldpde;
4173 vm_offset_t eva, va;
4175 boolean_t anychanged;
4176 pt_entry_t PG_G, PG_M, PG_RW;
4178 PG_G = pmap_global_bit(pmap);
4179 PG_M = pmap_modified_bit(pmap);
4180 PG_RW = pmap_rw_bit(pmap);
4182 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4183 KASSERT((sva & PDRMASK) == 0,
4184 ("pmap_protect_pde: sva is not 2mpage aligned"));
4187 oldpde = newpde = *pde;
4188 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4189 (PG_MANAGED | PG_M | PG_RW)) {
4191 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4192 va < eva; va += PAGE_SIZE, m++)
4195 if ((prot & VM_PROT_WRITE) == 0)
4196 newpde &= ~(PG_RW | PG_M);
4197 if ((prot & VM_PROT_EXECUTE) == 0)
4199 if (newpde != oldpde) {
4201 * As an optimization to future operations on this PDE, clear
4202 * PG_PROMOTED. The impending invalidation will remove any
4203 * lingering 4KB page mappings from the TLB.
4205 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
4207 if ((oldpde & PG_G) != 0)
4208 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4212 return (anychanged);
4216 * Set the physical protection on the
4217 * specified range of this map as requested.
4220 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4222 vm_offset_t va_next;
4223 pml4_entry_t *pml4e;
4225 pd_entry_t ptpaddr, *pde;
4226 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4227 boolean_t anychanged;
4229 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4230 if (prot == VM_PROT_NONE) {
4231 pmap_remove(pmap, sva, eva);
4235 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4236 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4239 PG_G = pmap_global_bit(pmap);
4240 PG_M = pmap_modified_bit(pmap);
4241 PG_V = pmap_valid_bit(pmap);
4242 PG_RW = pmap_rw_bit(pmap);
4246 * Although this function delays and batches the invalidation
4247 * of stale TLB entries, it does not need to call
4248 * pmap_delayed_invl_started() and
4249 * pmap_delayed_invl_finished(), because it does not
4250 * ordinarily destroy mappings. Stale TLB entries from
4251 * protection-only changes need only be invalidated before the
4252 * pmap lock is released, because protection-only changes do
4253 * not destroy PV entries. Even operations that iterate over
4254 * a physical page's PV list of mappings, like
4255 * pmap_remove_write(), acquire the pmap lock for each
4256 * mapping. Consequently, for protection-only changes, the
4257 * pmap lock suffices to synchronize both page table and TLB
4260 * This function only destroys a mapping if pmap_demote_pde()
4261 * fails. In that case, stale TLB entries are immediately
4266 for (; sva < eva; sva = va_next) {
4268 pml4e = pmap_pml4e(pmap, sva);
4269 if ((*pml4e & PG_V) == 0) {
4270 va_next = (sva + NBPML4) & ~PML4MASK;
4276 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4277 if ((*pdpe & PG_V) == 0) {
4278 va_next = (sva + NBPDP) & ~PDPMASK;
4284 va_next = (sva + NBPDR) & ~PDRMASK;
4288 pde = pmap_pdpe_to_pde(pdpe, sva);
4292 * Weed out invalid mappings.
4298 * Check for large page.
4300 if ((ptpaddr & PG_PS) != 0) {
4302 * Are we protecting the entire large page? If not,
4303 * demote the mapping and fall through.
4305 if (sva + NBPDR == va_next && eva >= va_next) {
4307 * The TLB entry for a PG_G mapping is
4308 * invalidated by pmap_protect_pde().
4310 if (pmap_protect_pde(pmap, pde, sva, prot))
4313 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4315 * The large page mapping was destroyed.
4324 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4326 pt_entry_t obits, pbits;
4330 obits = pbits = *pte;
4331 if ((pbits & PG_V) == 0)
4334 if ((prot & VM_PROT_WRITE) == 0) {
4335 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4336 (PG_MANAGED | PG_M | PG_RW)) {
4337 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4340 pbits &= ~(PG_RW | PG_M);
4342 if ((prot & VM_PROT_EXECUTE) == 0)
4345 if (pbits != obits) {
4346 if (!atomic_cmpset_long(pte, obits, pbits))
4349 pmap_invalidate_page(pmap, sva);
4356 pmap_invalidate_all(pmap);
4360 #if VM_NRESERVLEVEL > 0
4362 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4363 * single page table page (PTP) to a single 2MB page mapping. For promotion
4364 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4365 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4366 * identical characteristics.
4369 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4370 struct rwlock **lockp)
4373 pt_entry_t *firstpte, oldpte, pa, *pte;
4374 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4378 PG_A = pmap_accessed_bit(pmap);
4379 PG_G = pmap_global_bit(pmap);
4380 PG_M = pmap_modified_bit(pmap);
4381 PG_V = pmap_valid_bit(pmap);
4382 PG_RW = pmap_rw_bit(pmap);
4383 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4385 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4388 * Examine the first PTE in the specified PTP. Abort if this PTE is
4389 * either invalid, unused, or does not map the first 4KB physical page
4390 * within a 2MB page.
4392 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4395 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4396 atomic_add_long(&pmap_pde_p_failures, 1);
4397 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4398 " in pmap %p", va, pmap);
4401 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4403 * When PG_M is already clear, PG_RW can be cleared without
4404 * a TLB invalidation.
4406 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4412 * Examine each of the other PTEs in the specified PTP. Abort if this
4413 * PTE maps an unexpected 4KB physical page or does not have identical
4414 * characteristics to the first PTE.
4416 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4417 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4420 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4421 atomic_add_long(&pmap_pde_p_failures, 1);
4422 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4423 " in pmap %p", va, pmap);
4426 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4428 * When PG_M is already clear, PG_RW can be cleared
4429 * without a TLB invalidation.
4431 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4434 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4435 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4436 (va & ~PDRMASK), pmap);
4438 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4439 atomic_add_long(&pmap_pde_p_failures, 1);
4440 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4441 " in pmap %p", va, pmap);
4448 * Save the page table page in its current state until the PDE
4449 * mapping the superpage is demoted by pmap_demote_pde() or
4450 * destroyed by pmap_remove_pde().
4452 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4453 KASSERT(mpte >= vm_page_array &&
4454 mpte < &vm_page_array[vm_page_array_size],
4455 ("pmap_promote_pde: page table page is out of range"));
4456 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4457 ("pmap_promote_pde: page table page's pindex is wrong"));
4458 if (pmap_insert_pt_page(pmap, mpte)) {
4459 atomic_add_long(&pmap_pde_p_failures, 1);
4461 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4467 * Promote the pv entries.
4469 if ((newpde & PG_MANAGED) != 0)
4470 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4473 * Propagate the PAT index to its proper position.
4475 newpde = pmap_swap_pat(pmap, newpde);
4478 * Map the superpage.
4480 if (workaround_erratum383)
4481 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4483 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
4485 atomic_add_long(&pmap_pde_promotions, 1);
4486 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4487 " in pmap %p", va, pmap);
4489 #endif /* VM_NRESERVLEVEL > 0 */
4492 * Insert the given physical page (p) at
4493 * the specified virtual address (v) in the
4494 * target physical map with the protection requested.
4496 * If specified, the page will be wired down, meaning
4497 * that the related pte can not be reclaimed.
4499 * NB: This is the only routine which MAY NOT lazy-evaluate
4500 * or lose information. That is, this routine must actually
4501 * insert this page into the given map NOW.
4503 * When destroying both a page table and PV entry, this function
4504 * performs the TLB invalidation before releasing the PV list
4505 * lock, so we do not need pmap_delayed_invl_page() calls here.
4508 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4509 u_int flags, int8_t psind)
4511 struct rwlock *lock;
4513 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4514 pt_entry_t newpte, origpte;
4521 PG_A = pmap_accessed_bit(pmap);
4522 PG_G = pmap_global_bit(pmap);
4523 PG_M = pmap_modified_bit(pmap);
4524 PG_V = pmap_valid_bit(pmap);
4525 PG_RW = pmap_rw_bit(pmap);
4527 va = trunc_page(va);
4528 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4529 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4530 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4532 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4533 va >= kmi.clean_eva,
4534 ("pmap_enter: managed mapping within the clean submap"));
4535 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4536 VM_OBJECT_ASSERT_LOCKED(m->object);
4537 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
4538 ("pmap_enter: flags %u has reserved bits set", flags));
4539 pa = VM_PAGE_TO_PHYS(m);
4540 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4541 if ((flags & VM_PROT_WRITE) != 0)
4543 if ((prot & VM_PROT_WRITE) != 0)
4545 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4546 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4547 if ((prot & VM_PROT_EXECUTE) == 0)
4549 if ((flags & PMAP_ENTER_WIRED) != 0)
4551 if (va < VM_MAXUSER_ADDRESS)
4553 if (pmap == kernel_pmap)
4555 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
4558 * Set modified bit gratuitously for writeable mappings if
4559 * the page is unmanaged. We do not want to take a fault
4560 * to do the dirty bit accounting for these mappings.
4562 if ((m->oflags & VPO_UNMANAGED) != 0) {
4563 if ((newpte & PG_RW) != 0)
4566 newpte |= PG_MANAGED;
4571 /* Assert the required virtual and physical alignment. */
4572 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
4573 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4574 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
4580 * In the case that a page table page is not
4581 * resident, we are creating it here.
4584 pde = pmap_pde(pmap, va);
4585 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4586 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4587 pte = pmap_pde_to_pte(pde, va);
4588 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4589 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4592 } else if (va < VM_MAXUSER_ADDRESS) {
4594 * Here if the pte page isn't mapped, or if it has been
4597 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4598 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4599 nosleep ? NULL : &lock);
4600 if (mpte == NULL && nosleep) {
4601 rv = KERN_RESOURCE_SHORTAGE;
4606 panic("pmap_enter: invalid page directory va=%#lx", va);
4611 * Is the specified virtual address already mapped?
4613 if ((origpte & PG_V) != 0) {
4615 * Wiring change, just update stats. We don't worry about
4616 * wiring PT pages as they remain resident as long as there
4617 * are valid mappings in them. Hence, if a user page is wired,
4618 * the PT page will be also.
4620 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4621 pmap->pm_stats.wired_count++;
4622 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4623 pmap->pm_stats.wired_count--;
4626 * Remove the extra PT page reference.
4630 KASSERT(mpte->wire_count > 0,
4631 ("pmap_enter: missing reference to page table page,"
4636 * Has the physical page changed?
4638 opa = origpte & PG_FRAME;
4641 * No, might be a protection or wiring change.
4643 if ((origpte & PG_MANAGED) != 0 &&
4644 (newpte & PG_RW) != 0)
4645 vm_page_aflag_set(m, PGA_WRITEABLE);
4646 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4652 * Increment the counters.
4654 if ((newpte & PG_W) != 0)
4655 pmap->pm_stats.wired_count++;
4656 pmap_resident_count_inc(pmap, 1);
4660 * Enter on the PV list if part of our managed memory.
4662 if ((newpte & PG_MANAGED) != 0) {
4663 pv = get_pv_entry(pmap, &lock);
4665 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4666 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4668 if ((newpte & PG_RW) != 0)
4669 vm_page_aflag_set(m, PGA_WRITEABLE);
4675 if ((origpte & PG_V) != 0) {
4677 origpte = pte_load_store(pte, newpte);
4678 opa = origpte & PG_FRAME;
4680 if ((origpte & PG_MANAGED) != 0) {
4681 om = PHYS_TO_VM_PAGE(opa);
4682 if ((origpte & (PG_M | PG_RW)) == (PG_M |
4685 if ((origpte & PG_A) != 0)
4686 vm_page_aflag_set(om, PGA_REFERENCED);
4687 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4688 pmap_pvh_free(&om->md, pmap, va);
4689 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4690 TAILQ_EMPTY(&om->md.pv_list) &&
4691 ((om->flags & PG_FICTITIOUS) != 0 ||
4692 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4693 vm_page_aflag_clear(om, PGA_WRITEABLE);
4695 } else if ((newpte & PG_M) == 0 && (origpte & (PG_M |
4696 PG_RW)) == (PG_M | PG_RW)) {
4697 if ((origpte & PG_MANAGED) != 0)
4701 * Although the PTE may still have PG_RW set, TLB
4702 * invalidation may nonetheless be required because
4703 * the PTE no longer has PG_M set.
4705 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4707 * This PTE change does not require TLB invalidation.
4711 if ((origpte & PG_A) != 0)
4712 pmap_invalidate_page(pmap, va);
4714 pte_store(pte, newpte);
4718 #if VM_NRESERVLEVEL > 0
4720 * If both the page table page and the reservation are fully
4721 * populated, then attempt promotion.
4723 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4724 pmap_ps_enabled(pmap) &&
4725 (m->flags & PG_FICTITIOUS) == 0 &&
4726 vm_reserv_level_iffullpop(m) == 0)
4727 pmap_promote_pde(pmap, pde, va, &lock);
4739 * Tries to create a read- and/or execute-only 2MB page mapping. Returns true
4740 * if successful. Returns false if (1) a page table page cannot be allocated
4741 * without sleeping, (2) a mapping already exists at the specified virtual
4742 * address, or (3) a PV entry cannot be allocated without reclaiming another
4746 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4747 struct rwlock **lockp)
4752 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4753 PG_V = pmap_valid_bit(pmap);
4754 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
4756 if ((m->oflags & VPO_UNMANAGED) == 0)
4757 newpde |= PG_MANAGED;
4758 if ((prot & VM_PROT_EXECUTE) == 0)
4760 if (va < VM_MAXUSER_ADDRESS)
4762 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
4763 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
4768 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
4769 * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
4770 * otherwise. Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
4771 * a mapping already exists at the specified virtual address. Returns
4772 * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
4773 * page allocation failed. Returns KERN_RESOURCE_SHORTAGE if
4774 * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
4776 * The parameter "m" is only used when creating a managed, writeable mapping.
4779 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
4780 vm_page_t m, struct rwlock **lockp)
4782 struct spglist free;
4783 pd_entry_t oldpde, *pde;
4784 pt_entry_t PG_G, PG_RW, PG_V;
4787 PG_G = pmap_global_bit(pmap);
4788 PG_RW = pmap_rw_bit(pmap);
4789 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
4790 ("pmap_enter_pde: newpde is missing PG_M"));
4791 PG_V = pmap_valid_bit(pmap);
4792 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4794 if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
4795 NULL : lockp)) == NULL) {
4796 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4797 " in pmap %p", va, pmap);
4798 return (KERN_RESOURCE_SHORTAGE);
4800 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4801 pde = &pde[pmap_pde_index(va)];
4803 if ((oldpde & PG_V) != 0) {
4804 KASSERT(pdpg->wire_count > 1,
4805 ("pmap_enter_pde: pdpg's wire count is too low"));
4806 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
4808 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4809 " in pmap %p", va, pmap);
4810 return (KERN_FAILURE);
4812 /* Break the existing mapping(s). */
4814 if ((oldpde & PG_PS) != 0) {
4816 * The reference to the PD page that was acquired by
4817 * pmap_allocpde() ensures that it won't be freed.
4818 * However, if the PDE resulted from a promotion, then
4819 * a reserved PT page could be freed.
4821 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
4822 if ((oldpde & PG_G) == 0)
4823 pmap_invalidate_pde_page(pmap, va, oldpde);
4825 pmap_delayed_invl_started();
4826 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
4828 pmap_invalidate_all(pmap);
4829 pmap_delayed_invl_finished();
4831 pmap_free_zero_pages(&free);
4832 if (va >= VM_MAXUSER_ADDRESS) {
4833 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4834 if (pmap_insert_pt_page(pmap, mt)) {
4836 * XXX Currently, this can't happen because
4837 * we do not perform pmap_enter(psind == 1)
4838 * on the kernel pmap.
4840 panic("pmap_enter_pde: trie insert failed");
4843 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
4846 if ((newpde & PG_MANAGED) != 0) {
4848 * Abort this mapping if its PV entry could not be created.
4850 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
4852 if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
4854 * Although "va" is not mapped, paging-
4855 * structure caches could nonetheless have
4856 * entries that refer to the freed page table
4857 * pages. Invalidate those entries.
4859 pmap_invalidate_page(pmap, va);
4860 pmap_free_zero_pages(&free);
4862 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4863 " in pmap %p", va, pmap);
4864 return (KERN_RESOURCE_SHORTAGE);
4866 if ((newpde & PG_RW) != 0) {
4867 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
4868 vm_page_aflag_set(mt, PGA_WRITEABLE);
4873 * Increment counters.
4875 if ((newpde & PG_W) != 0)
4876 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
4877 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
4880 * Map the superpage. (This is not a promoted mapping; there will not
4881 * be any lingering 4KB page mappings in the TLB.)
4883 pde_store(pde, newpde);
4885 atomic_add_long(&pmap_pde_mappings, 1);
4886 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
4887 " in pmap %p", va, pmap);
4888 return (KERN_SUCCESS);
4892 * Maps a sequence of resident pages belonging to the same object.
4893 * The sequence begins with the given page m_start. This page is
4894 * mapped at the given virtual address start. Each subsequent page is
4895 * mapped at a virtual address that is offset from start by the same
4896 * amount as the page is offset from m_start within the object. The
4897 * last page in the sequence is the page with the largest offset from
4898 * m_start that can be mapped at a virtual address less than the given
4899 * virtual address end. Not every virtual page between start and end
4900 * is mapped; only those for which a resident page exists with the
4901 * corresponding offset from m_start are mapped.
4904 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
4905 vm_page_t m_start, vm_prot_t prot)
4907 struct rwlock *lock;
4910 vm_pindex_t diff, psize;
4912 VM_OBJECT_ASSERT_LOCKED(m_start->object);
4914 psize = atop(end - start);
4919 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
4920 va = start + ptoa(diff);
4921 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
4922 m->psind == 1 && pmap_ps_enabled(pmap) &&
4923 pmap_enter_2mpage(pmap, va, m, prot, &lock))
4924 m = &m[NBPDR / PAGE_SIZE - 1];
4926 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
4928 m = TAILQ_NEXT(m, listq);
4936 * this code makes some *MAJOR* assumptions:
4937 * 1. Current pmap & pmap exists.
4940 * 4. No page table pages.
4941 * but is *MUCH* faster than pmap_enter...
4945 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
4947 struct rwlock *lock;
4951 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
4958 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
4959 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
4961 struct spglist free;
4962 pt_entry_t *pte, PG_V;
4965 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
4966 (m->oflags & VPO_UNMANAGED) != 0,
4967 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
4968 PG_V = pmap_valid_bit(pmap);
4969 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4972 * In the case that a page table page is not
4973 * resident, we are creating it here.
4975 if (va < VM_MAXUSER_ADDRESS) {
4976 vm_pindex_t ptepindex;
4980 * Calculate pagetable page index
4982 ptepindex = pmap_pde_pindex(va);
4983 if (mpte && (mpte->pindex == ptepindex)) {
4987 * Get the page directory entry
4989 ptepa = pmap_pde(pmap, va);
4992 * If the page table page is mapped, we just increment
4993 * the hold count, and activate it. Otherwise, we
4994 * attempt to allocate a page table page. If this
4995 * attempt fails, we don't retry. Instead, we give up.
4997 if (ptepa && (*ptepa & PG_V) != 0) {
5000 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
5004 * Pass NULL instead of the PV list lock
5005 * pointer, because we don't intend to sleep.
5007 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
5012 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
5013 pte = &pte[pmap_pte_index(va)];
5027 * Enter on the PV list if part of our managed memory.
5029 if ((m->oflags & VPO_UNMANAGED) == 0 &&
5030 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
5033 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
5035 * Although "va" is not mapped, paging-
5036 * structure caches could nonetheless have
5037 * entries that refer to the freed page table
5038 * pages. Invalidate those entries.
5040 pmap_invalidate_page(pmap, va);
5041 pmap_free_zero_pages(&free);
5049 * Increment counters
5051 pmap_resident_count_inc(pmap, 1);
5053 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
5054 if ((prot & VM_PROT_EXECUTE) == 0)
5058 * Now validate mapping with RO protection
5060 if ((m->oflags & VPO_UNMANAGED) != 0)
5061 pte_store(pte, pa | PG_V | PG_U);
5063 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
5068 * Make a temporary mapping for a physical address. This is only intended
5069 * to be used for panic dumps.
5072 pmap_kenter_temporary(vm_paddr_t pa, int i)
5076 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
5077 pmap_kenter(va, pa);
5079 return ((void *)crashdumpmap);
5083 * This code maps large physical mmap regions into the
5084 * processor address space. Note that some shortcuts
5085 * are taken, but the code works.
5088 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
5089 vm_pindex_t pindex, vm_size_t size)
5092 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5093 vm_paddr_t pa, ptepa;
5097 PG_A = pmap_accessed_bit(pmap);
5098 PG_M = pmap_modified_bit(pmap);
5099 PG_V = pmap_valid_bit(pmap);
5100 PG_RW = pmap_rw_bit(pmap);
5102 VM_OBJECT_ASSERT_WLOCKED(object);
5103 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
5104 ("pmap_object_init_pt: non-device object"));
5105 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
5106 if (!pmap_ps_enabled(pmap))
5108 if (!vm_object_populate(object, pindex, pindex + atop(size)))
5110 p = vm_page_lookup(object, pindex);
5111 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5112 ("pmap_object_init_pt: invalid page %p", p));
5113 pat_mode = p->md.pat_mode;
5116 * Abort the mapping if the first page is not physically
5117 * aligned to a 2MB page boundary.
5119 ptepa = VM_PAGE_TO_PHYS(p);
5120 if (ptepa & (NBPDR - 1))
5124 * Skip the first page. Abort the mapping if the rest of
5125 * the pages are not physically contiguous or have differing
5126 * memory attributes.
5128 p = TAILQ_NEXT(p, listq);
5129 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
5131 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5132 ("pmap_object_init_pt: invalid page %p", p));
5133 if (pa != VM_PAGE_TO_PHYS(p) ||
5134 pat_mode != p->md.pat_mode)
5136 p = TAILQ_NEXT(p, listq);
5140 * Map using 2MB pages. Since "ptepa" is 2M aligned and
5141 * "size" is a multiple of 2M, adding the PAT setting to "pa"
5142 * will not affect the termination of this loop.
5145 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
5146 pa < ptepa + size; pa += NBPDR) {
5147 pdpg = pmap_allocpde(pmap, addr, NULL);
5150 * The creation of mappings below is only an
5151 * optimization. If a page directory page
5152 * cannot be allocated without blocking,
5153 * continue on to the next mapping rather than
5159 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5160 pde = &pde[pmap_pde_index(addr)];
5161 if ((*pde & PG_V) == 0) {
5162 pde_store(pde, pa | PG_PS | PG_M | PG_A |
5163 PG_U | PG_RW | PG_V);
5164 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5165 atomic_add_long(&pmap_pde_mappings, 1);
5167 /* Continue on if the PDE is already valid. */
5169 KASSERT(pdpg->wire_count > 0,
5170 ("pmap_object_init_pt: missing reference "
5171 "to page directory page, va: 0x%lx", addr));
5180 * Clear the wired attribute from the mappings for the specified range of
5181 * addresses in the given pmap. Every valid mapping within that range
5182 * must have the wired attribute set. In contrast, invalid mappings
5183 * cannot have the wired attribute set, so they are ignored.
5185 * The wired attribute of the page table entry is not a hardware
5186 * feature, so there is no need to invalidate any TLB entries.
5187 * Since pmap_demote_pde() for the wired entry must never fail,
5188 * pmap_delayed_invl_started()/finished() calls around the
5189 * function are not needed.
5192 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5194 vm_offset_t va_next;
5195 pml4_entry_t *pml4e;
5198 pt_entry_t *pte, PG_V;
5200 PG_V = pmap_valid_bit(pmap);
5202 for (; sva < eva; sva = va_next) {
5203 pml4e = pmap_pml4e(pmap, sva);
5204 if ((*pml4e & PG_V) == 0) {
5205 va_next = (sva + NBPML4) & ~PML4MASK;
5210 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5211 if ((*pdpe & PG_V) == 0) {
5212 va_next = (sva + NBPDP) & ~PDPMASK;
5217 va_next = (sva + NBPDR) & ~PDRMASK;
5220 pde = pmap_pdpe_to_pde(pdpe, sva);
5221 if ((*pde & PG_V) == 0)
5223 if ((*pde & PG_PS) != 0) {
5224 if ((*pde & PG_W) == 0)
5225 panic("pmap_unwire: pde %#jx is missing PG_W",
5229 * Are we unwiring the entire large page? If not,
5230 * demote the mapping and fall through.
5232 if (sva + NBPDR == va_next && eva >= va_next) {
5233 atomic_clear_long(pde, PG_W);
5234 pmap->pm_stats.wired_count -= NBPDR /
5237 } else if (!pmap_demote_pde(pmap, pde, sva))
5238 panic("pmap_unwire: demotion failed");
5242 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
5244 if ((*pte & PG_V) == 0)
5246 if ((*pte & PG_W) == 0)
5247 panic("pmap_unwire: pte %#jx is missing PG_W",
5251 * PG_W must be cleared atomically. Although the pmap
5252 * lock synchronizes access to PG_W, another processor
5253 * could be setting PG_M and/or PG_A concurrently.
5255 atomic_clear_long(pte, PG_W);
5256 pmap->pm_stats.wired_count--;
5263 * Copy the range specified by src_addr/len
5264 * from the source map to the range dst_addr/len
5265 * in the destination map.
5267 * This routine is only advisory and need not do anything.
5271 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5272 vm_offset_t src_addr)
5274 struct rwlock *lock;
5275 struct spglist free;
5277 vm_offset_t end_addr = src_addr + len;
5278 vm_offset_t va_next;
5279 vm_page_t dst_pdpg, dstmpte, srcmpte;
5280 pt_entry_t PG_A, PG_M, PG_V;
5282 if (dst_addr != src_addr)
5285 if (dst_pmap->pm_type != src_pmap->pm_type)
5289 * EPT page table entries that require emulation of A/D bits are
5290 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5291 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5292 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5293 * implementations flag an EPT misconfiguration for exec-only
5294 * mappings we skip this function entirely for emulated pmaps.
5296 if (pmap_emulate_ad_bits(dst_pmap))
5300 if (dst_pmap < src_pmap) {
5301 PMAP_LOCK(dst_pmap);
5302 PMAP_LOCK(src_pmap);
5304 PMAP_LOCK(src_pmap);
5305 PMAP_LOCK(dst_pmap);
5308 PG_A = pmap_accessed_bit(dst_pmap);
5309 PG_M = pmap_modified_bit(dst_pmap);
5310 PG_V = pmap_valid_bit(dst_pmap);
5312 for (addr = src_addr; addr < end_addr; addr = va_next) {
5313 pt_entry_t *src_pte, *dst_pte;
5314 pml4_entry_t *pml4e;
5316 pd_entry_t srcptepaddr, *pde;
5318 KASSERT(addr < UPT_MIN_ADDRESS,
5319 ("pmap_copy: invalid to pmap_copy page tables"));
5321 pml4e = pmap_pml4e(src_pmap, addr);
5322 if ((*pml4e & PG_V) == 0) {
5323 va_next = (addr + NBPML4) & ~PML4MASK;
5329 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5330 if ((*pdpe & PG_V) == 0) {
5331 va_next = (addr + NBPDP) & ~PDPMASK;
5337 va_next = (addr + NBPDR) & ~PDRMASK;
5341 pde = pmap_pdpe_to_pde(pdpe, addr);
5343 if (srcptepaddr == 0)
5346 if (srcptepaddr & PG_PS) {
5347 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5349 dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
5350 if (dst_pdpg == NULL)
5352 pde = (pd_entry_t *)
5353 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
5354 pde = &pde[pmap_pde_index(addr)];
5355 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5356 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
5357 PMAP_ENTER_NORECLAIM, &lock))) {
5358 *pde = srcptepaddr & ~PG_W;
5359 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5360 atomic_add_long(&pmap_pde_mappings, 1);
5362 dst_pdpg->wire_count--;
5366 srcptepaddr &= PG_FRAME;
5367 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5368 KASSERT(srcmpte->wire_count > 0,
5369 ("pmap_copy: source page table page is unused"));
5371 if (va_next > end_addr)
5374 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5375 src_pte = &src_pte[pmap_pte_index(addr)];
5377 while (addr < va_next) {
5381 * we only virtual copy managed pages
5383 if ((ptetemp & PG_MANAGED) != 0) {
5384 if (dstmpte != NULL &&
5385 dstmpte->pindex == pmap_pde_pindex(addr))
5386 dstmpte->wire_count++;
5387 else if ((dstmpte = pmap_allocpte(dst_pmap,
5388 addr, NULL)) == NULL)
5390 dst_pte = (pt_entry_t *)
5391 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5392 dst_pte = &dst_pte[pmap_pte_index(addr)];
5393 if (*dst_pte == 0 &&
5394 pmap_try_insert_pv_entry(dst_pmap, addr,
5395 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5398 * Clear the wired, modified, and
5399 * accessed (referenced) bits
5402 *dst_pte = ptetemp & ~(PG_W | PG_M |
5404 pmap_resident_count_inc(dst_pmap, 1);
5407 if (pmap_unwire_ptp(dst_pmap, addr,
5410 * Although "addr" is not
5411 * mapped, paging-structure
5412 * caches could nonetheless
5413 * have entries that refer to
5414 * the freed page table pages.
5415 * Invalidate those entries.
5417 pmap_invalidate_page(dst_pmap,
5419 pmap_free_zero_pages(&free);
5423 if (dstmpte->wire_count >= srcmpte->wire_count)
5433 PMAP_UNLOCK(src_pmap);
5434 PMAP_UNLOCK(dst_pmap);
5438 * Zero the specified hardware page.
5441 pmap_zero_page(vm_page_t m)
5443 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5445 pagezero((void *)va);
5449 * Zero an an area within a single hardware page. off and size must not
5450 * cover an area beyond a single hardware page.
5453 pmap_zero_page_area(vm_page_t m, int off, int size)
5455 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5457 if (off == 0 && size == PAGE_SIZE)
5458 pagezero((void *)va);
5460 bzero((char *)va + off, size);
5464 * Copy 1 specified hardware page to another.
5467 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5469 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5470 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5472 pagecopy((void *)src, (void *)dst);
5475 int unmapped_buf_allowed = 1;
5478 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5479 vm_offset_t b_offset, int xfersize)
5483 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5487 while (xfersize > 0) {
5488 a_pg_offset = a_offset & PAGE_MASK;
5489 pages[0] = ma[a_offset >> PAGE_SHIFT];
5490 b_pg_offset = b_offset & PAGE_MASK;
5491 pages[1] = mb[b_offset >> PAGE_SHIFT];
5492 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5493 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5494 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5495 a_cp = (char *)vaddr[0] + a_pg_offset;
5496 b_cp = (char *)vaddr[1] + b_pg_offset;
5497 bcopy(a_cp, b_cp, cnt);
5498 if (__predict_false(mapped))
5499 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5507 * Returns true if the pmap's pv is one of the first
5508 * 16 pvs linked to from this page. This count may
5509 * be changed upwards or downwards in the future; it
5510 * is only necessary that true be returned for a small
5511 * subset of pmaps for proper page aging.
5514 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5516 struct md_page *pvh;
5517 struct rwlock *lock;
5522 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5523 ("pmap_page_exists_quick: page %p is not managed", m));
5525 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5527 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5528 if (PV_PMAP(pv) == pmap) {
5536 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5537 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5538 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5539 if (PV_PMAP(pv) == pmap) {
5553 * pmap_page_wired_mappings:
5555 * Return the number of managed mappings to the given physical page
5559 pmap_page_wired_mappings(vm_page_t m)
5561 struct rwlock *lock;
5562 struct md_page *pvh;
5566 int count, md_gen, pvh_gen;
5568 if ((m->oflags & VPO_UNMANAGED) != 0)
5570 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5574 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5576 if (!PMAP_TRYLOCK(pmap)) {
5577 md_gen = m->md.pv_gen;
5581 if (md_gen != m->md.pv_gen) {
5586 pte = pmap_pte(pmap, pv->pv_va);
5587 if ((*pte & PG_W) != 0)
5591 if ((m->flags & PG_FICTITIOUS) == 0) {
5592 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5593 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5595 if (!PMAP_TRYLOCK(pmap)) {
5596 md_gen = m->md.pv_gen;
5597 pvh_gen = pvh->pv_gen;
5601 if (md_gen != m->md.pv_gen ||
5602 pvh_gen != pvh->pv_gen) {
5607 pte = pmap_pde(pmap, pv->pv_va);
5608 if ((*pte & PG_W) != 0)
5618 * Returns TRUE if the given page is mapped individually or as part of
5619 * a 2mpage. Otherwise, returns FALSE.
5622 pmap_page_is_mapped(vm_page_t m)
5624 struct rwlock *lock;
5627 if ((m->oflags & VPO_UNMANAGED) != 0)
5629 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5631 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5632 ((m->flags & PG_FICTITIOUS) == 0 &&
5633 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5639 * Destroy all managed, non-wired mappings in the given user-space
5640 * pmap. This pmap cannot be active on any processor besides the
5643 * This function cannot be applied to the kernel pmap. Moreover, it
5644 * is not intended for general use. It is only to be used during
5645 * process termination. Consequently, it can be implemented in ways
5646 * that make it faster than pmap_remove(). First, it can more quickly
5647 * destroy mappings by iterating over the pmap's collection of PV
5648 * entries, rather than searching the page table. Second, it doesn't
5649 * have to test and clear the page table entries atomically, because
5650 * no processor is currently accessing the user address space. In
5651 * particular, a page table entry's dirty bit won't change state once
5652 * this function starts.
5654 * Although this function destroys all of the pmap's managed,
5655 * non-wired mappings, it can delay and batch the invalidation of TLB
5656 * entries without calling pmap_delayed_invl_started() and
5657 * pmap_delayed_invl_finished(). Because the pmap is not active on
5658 * any other processor, none of these TLB entries will ever be used
5659 * before their eventual invalidation. Consequently, there is no need
5660 * for either pmap_remove_all() or pmap_remove_write() to wait for
5661 * that eventual TLB invalidation.
5664 pmap_remove_pages(pmap_t pmap)
5667 pt_entry_t *pte, tpte;
5668 pt_entry_t PG_M, PG_RW, PG_V;
5669 struct spglist free;
5670 vm_page_t m, mpte, mt;
5672 struct md_page *pvh;
5673 struct pv_chunk *pc, *npc;
5674 struct rwlock *lock;
5676 uint64_t inuse, bitmask;
5677 int allfree, field, freed, idx;
5678 boolean_t superpage;
5682 * Assert that the given pmap is only active on the current
5683 * CPU. Unfortunately, we cannot block another CPU from
5684 * activating the pmap while this function is executing.
5686 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5689 cpuset_t other_cpus;
5691 other_cpus = all_cpus;
5693 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5694 CPU_AND(&other_cpus, &pmap->pm_active);
5696 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5701 PG_M = pmap_modified_bit(pmap);
5702 PG_V = pmap_valid_bit(pmap);
5703 PG_RW = pmap_rw_bit(pmap);
5707 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5710 for (field = 0; field < _NPCM; field++) {
5711 inuse = ~pc->pc_map[field] & pc_freemask[field];
5712 while (inuse != 0) {
5714 bitmask = 1UL << bit;
5715 idx = field * 64 + bit;
5716 pv = &pc->pc_pventry[idx];
5719 pte = pmap_pdpe(pmap, pv->pv_va);
5721 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5723 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5726 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5728 pte = &pte[pmap_pte_index(pv->pv_va)];
5732 * Keep track whether 'tpte' is a
5733 * superpage explicitly instead of
5734 * relying on PG_PS being set.
5736 * This is because PG_PS is numerically
5737 * identical to PG_PTE_PAT and thus a
5738 * regular page could be mistaken for
5744 if ((tpte & PG_V) == 0) {
5745 panic("bad pte va %lx pte %lx",
5750 * We cannot remove wired pages from a process' mapping at this time
5758 pa = tpte & PG_PS_FRAME;
5760 pa = tpte & PG_FRAME;
5762 m = PHYS_TO_VM_PAGE(pa);
5763 KASSERT(m->phys_addr == pa,
5764 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5765 m, (uintmax_t)m->phys_addr,
5768 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5769 m < &vm_page_array[vm_page_array_size],
5770 ("pmap_remove_pages: bad tpte %#jx",
5776 * Update the vm_page_t clean/reference bits.
5778 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5780 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5786 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5789 pc->pc_map[field] |= bitmask;
5791 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
5792 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
5793 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5795 if (TAILQ_EMPTY(&pvh->pv_list)) {
5796 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5797 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
5798 TAILQ_EMPTY(&mt->md.pv_list))
5799 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5801 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
5803 pmap_resident_count_dec(pmap, 1);
5804 KASSERT(mpte->wire_count == NPTEPG,
5805 ("pmap_remove_pages: pte page wire count error"));
5806 mpte->wire_count = 0;
5807 pmap_add_delayed_free_list(mpte, &free, FALSE);
5810 pmap_resident_count_dec(pmap, 1);
5811 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5813 if ((m->aflags & PGA_WRITEABLE) != 0 &&
5814 TAILQ_EMPTY(&m->md.pv_list) &&
5815 (m->flags & PG_FICTITIOUS) == 0) {
5816 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5817 if (TAILQ_EMPTY(&pvh->pv_list))
5818 vm_page_aflag_clear(m, PGA_WRITEABLE);
5821 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
5825 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5826 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5827 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5829 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5835 pmap_invalidate_all(pmap);
5837 pmap_free_zero_pages(&free);
5841 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
5843 struct rwlock *lock;
5845 struct md_page *pvh;
5846 pt_entry_t *pte, mask;
5847 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5849 int md_gen, pvh_gen;
5853 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5856 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5858 if (!PMAP_TRYLOCK(pmap)) {
5859 md_gen = m->md.pv_gen;
5863 if (md_gen != m->md.pv_gen) {
5868 pte = pmap_pte(pmap, pv->pv_va);
5871 PG_M = pmap_modified_bit(pmap);
5872 PG_RW = pmap_rw_bit(pmap);
5873 mask |= PG_RW | PG_M;
5876 PG_A = pmap_accessed_bit(pmap);
5877 PG_V = pmap_valid_bit(pmap);
5878 mask |= PG_V | PG_A;
5880 rv = (*pte & mask) == mask;
5885 if ((m->flags & PG_FICTITIOUS) == 0) {
5886 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5887 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5889 if (!PMAP_TRYLOCK(pmap)) {
5890 md_gen = m->md.pv_gen;
5891 pvh_gen = pvh->pv_gen;
5895 if (md_gen != m->md.pv_gen ||
5896 pvh_gen != pvh->pv_gen) {
5901 pte = pmap_pde(pmap, pv->pv_va);
5904 PG_M = pmap_modified_bit(pmap);
5905 PG_RW = pmap_rw_bit(pmap);
5906 mask |= PG_RW | PG_M;
5909 PG_A = pmap_accessed_bit(pmap);
5910 PG_V = pmap_valid_bit(pmap);
5911 mask |= PG_V | PG_A;
5913 rv = (*pte & mask) == mask;
5927 * Return whether or not the specified physical page was modified
5928 * in any physical maps.
5931 pmap_is_modified(vm_page_t m)
5934 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5935 ("pmap_is_modified: page %p is not managed", m));
5938 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5939 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
5940 * is clear, no PTEs can have PG_M set.
5942 VM_OBJECT_ASSERT_WLOCKED(m->object);
5943 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
5945 return (pmap_page_test_mappings(m, FALSE, TRUE));
5949 * pmap_is_prefaultable:
5951 * Return whether or not the specified virtual address is eligible
5955 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
5958 pt_entry_t *pte, PG_V;
5961 PG_V = pmap_valid_bit(pmap);
5964 pde = pmap_pde(pmap, addr);
5965 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
5966 pte = pmap_pde_to_pte(pde, addr);
5967 rv = (*pte & PG_V) == 0;
5974 * pmap_is_referenced:
5976 * Return whether or not the specified physical page was referenced
5977 * in any physical maps.
5980 pmap_is_referenced(vm_page_t m)
5983 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5984 ("pmap_is_referenced: page %p is not managed", m));
5985 return (pmap_page_test_mappings(m, TRUE, FALSE));
5989 * Clear the write and modified bits in each of the given page's mappings.
5992 pmap_remove_write(vm_page_t m)
5994 struct md_page *pvh;
5996 struct rwlock *lock;
5997 pv_entry_t next_pv, pv;
5999 pt_entry_t oldpte, *pte, PG_M, PG_RW;
6001 int pvh_gen, md_gen;
6003 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6004 ("pmap_remove_write: page %p is not managed", m));
6007 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6008 * set by another thread while the object is locked. Thus,
6009 * if PGA_WRITEABLE is clear, no page table entries need updating.
6011 VM_OBJECT_ASSERT_WLOCKED(m->object);
6012 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6014 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6015 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6016 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6019 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6021 if (!PMAP_TRYLOCK(pmap)) {
6022 pvh_gen = pvh->pv_gen;
6026 if (pvh_gen != pvh->pv_gen) {
6032 PG_RW = pmap_rw_bit(pmap);
6034 pde = pmap_pde(pmap, va);
6035 if ((*pde & PG_RW) != 0)
6036 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6037 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6038 ("inconsistent pv lock %p %p for page %p",
6039 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6042 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6044 if (!PMAP_TRYLOCK(pmap)) {
6045 pvh_gen = pvh->pv_gen;
6046 md_gen = m->md.pv_gen;
6050 if (pvh_gen != pvh->pv_gen ||
6051 md_gen != m->md.pv_gen) {
6057 PG_M = pmap_modified_bit(pmap);
6058 PG_RW = pmap_rw_bit(pmap);
6059 pde = pmap_pde(pmap, pv->pv_va);
6060 KASSERT((*pde & PG_PS) == 0,
6061 ("pmap_remove_write: found a 2mpage in page %p's pv list",
6063 pte = pmap_pde_to_pte(pde, pv->pv_va);
6066 if (oldpte & PG_RW) {
6067 if (!atomic_cmpset_long(pte, oldpte, oldpte &
6070 if ((oldpte & PG_M) != 0)
6072 pmap_invalidate_page(pmap, pv->pv_va);
6077 vm_page_aflag_clear(m, PGA_WRITEABLE);
6078 pmap_delayed_invl_wait(m);
6081 static __inline boolean_t
6082 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
6085 if (!pmap_emulate_ad_bits(pmap))
6088 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
6091 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
6092 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
6093 * if the EPT_PG_WRITE bit is set.
6095 if ((pte & EPT_PG_WRITE) != 0)
6099 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
6101 if ((pte & EPT_PG_EXECUTE) == 0 ||
6102 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
6109 * pmap_ts_referenced:
6111 * Return a count of reference bits for a page, clearing those bits.
6112 * It is not necessary for every reference bit to be cleared, but it
6113 * is necessary that 0 only be returned when there are truly no
6114 * reference bits set.
6116 * As an optimization, update the page's dirty field if a modified bit is
6117 * found while counting reference bits. This opportunistic update can be
6118 * performed at low cost and can eliminate the need for some future calls
6119 * to pmap_is_modified(). However, since this function stops after
6120 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
6121 * dirty pages. Those dirty pages will only be detected by a future call
6122 * to pmap_is_modified().
6124 * A DI block is not needed within this function, because
6125 * invalidations are performed before the PV list lock is
6129 pmap_ts_referenced(vm_page_t m)
6131 struct md_page *pvh;
6134 struct rwlock *lock;
6135 pd_entry_t oldpde, *pde;
6136 pt_entry_t *pte, PG_A, PG_M, PG_RW;
6139 int cleared, md_gen, not_cleared, pvh_gen;
6140 struct spglist free;
6143 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6144 ("pmap_ts_referenced: page %p is not managed", m));
6147 pa = VM_PAGE_TO_PHYS(m);
6148 lock = PHYS_TO_PV_LIST_LOCK(pa);
6149 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
6153 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6154 goto small_mappings;
6160 if (!PMAP_TRYLOCK(pmap)) {
6161 pvh_gen = pvh->pv_gen;
6165 if (pvh_gen != pvh->pv_gen) {
6170 PG_A = pmap_accessed_bit(pmap);
6171 PG_M = pmap_modified_bit(pmap);
6172 PG_RW = pmap_rw_bit(pmap);
6174 pde = pmap_pde(pmap, pv->pv_va);
6176 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6178 * Although "oldpde" is mapping a 2MB page, because
6179 * this function is called at a 4KB page granularity,
6180 * we only update the 4KB page under test.
6184 if ((oldpde & PG_A) != 0) {
6186 * Since this reference bit is shared by 512 4KB
6187 * pages, it should not be cleared every time it is
6188 * tested. Apply a simple "hash" function on the
6189 * physical page number, the virtual superpage number,
6190 * and the pmap address to select one 4KB page out of
6191 * the 512 on which testing the reference bit will
6192 * result in clearing that reference bit. This
6193 * function is designed to avoid the selection of the
6194 * same 4KB page for every 2MB page mapping.
6196 * On demotion, a mapping that hasn't been referenced
6197 * is simply destroyed. To avoid the possibility of a
6198 * subsequent page fault on a demoted wired mapping,
6199 * always leave its reference bit set. Moreover,
6200 * since the superpage is wired, the current state of
6201 * its reference bit won't affect page replacement.
6203 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
6204 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
6205 (oldpde & PG_W) == 0) {
6206 if (safe_to_clear_referenced(pmap, oldpde)) {
6207 atomic_clear_long(pde, PG_A);
6208 pmap_invalidate_page(pmap, pv->pv_va);
6210 } else if (pmap_demote_pde_locked(pmap, pde,
6211 pv->pv_va, &lock)) {
6213 * Remove the mapping to a single page
6214 * so that a subsequent access may
6215 * repromote. Since the underlying
6216 * page table page is fully populated,
6217 * this removal never frees a page
6221 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6223 pte = pmap_pde_to_pte(pde, va);
6224 pmap_remove_pte(pmap, pte, va, *pde,
6226 pmap_invalidate_page(pmap, va);
6232 * The superpage mapping was removed
6233 * entirely and therefore 'pv' is no
6241 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6242 ("inconsistent pv lock %p %p for page %p",
6243 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6248 /* Rotate the PV list if it has more than one entry. */
6249 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6250 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6251 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6254 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6256 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6258 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6265 if (!PMAP_TRYLOCK(pmap)) {
6266 pvh_gen = pvh->pv_gen;
6267 md_gen = m->md.pv_gen;
6271 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6276 PG_A = pmap_accessed_bit(pmap);
6277 PG_M = pmap_modified_bit(pmap);
6278 PG_RW = pmap_rw_bit(pmap);
6279 pde = pmap_pde(pmap, pv->pv_va);
6280 KASSERT((*pde & PG_PS) == 0,
6281 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6283 pte = pmap_pde_to_pte(pde, pv->pv_va);
6284 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6286 if ((*pte & PG_A) != 0) {
6287 if (safe_to_clear_referenced(pmap, *pte)) {
6288 atomic_clear_long(pte, PG_A);
6289 pmap_invalidate_page(pmap, pv->pv_va);
6291 } else if ((*pte & PG_W) == 0) {
6293 * Wired pages cannot be paged out so
6294 * doing accessed bit emulation for
6295 * them is wasted effort. We do the
6296 * hard work for unwired pages only.
6298 pmap_remove_pte(pmap, pte, pv->pv_va,
6299 *pde, &free, &lock);
6300 pmap_invalidate_page(pmap, pv->pv_va);
6305 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6306 ("inconsistent pv lock %p %p for page %p",
6307 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6312 /* Rotate the PV list if it has more than one entry. */
6313 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6314 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6315 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6318 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6319 not_cleared < PMAP_TS_REFERENCED_MAX);
6322 pmap_free_zero_pages(&free);
6323 return (cleared + not_cleared);
6327 * Apply the given advice to the specified range of addresses within the
6328 * given pmap. Depending on the advice, clear the referenced and/or
6329 * modified flags in each mapping and set the mapped page's dirty field.
6332 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6334 struct rwlock *lock;
6335 pml4_entry_t *pml4e;
6337 pd_entry_t oldpde, *pde;
6338 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6339 vm_offset_t va, va_next;
6341 boolean_t anychanged;
6343 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6347 * A/D bit emulation requires an alternate code path when clearing
6348 * the modified and accessed bits below. Since this function is
6349 * advisory in nature we skip it entirely for pmaps that require
6350 * A/D bit emulation.
6352 if (pmap_emulate_ad_bits(pmap))
6355 PG_A = pmap_accessed_bit(pmap);
6356 PG_G = pmap_global_bit(pmap);
6357 PG_M = pmap_modified_bit(pmap);
6358 PG_V = pmap_valid_bit(pmap);
6359 PG_RW = pmap_rw_bit(pmap);
6361 pmap_delayed_invl_started();
6363 for (; sva < eva; sva = va_next) {
6364 pml4e = pmap_pml4e(pmap, sva);
6365 if ((*pml4e & PG_V) == 0) {
6366 va_next = (sva + NBPML4) & ~PML4MASK;
6371 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6372 if ((*pdpe & PG_V) == 0) {
6373 va_next = (sva + NBPDP) & ~PDPMASK;
6378 va_next = (sva + NBPDR) & ~PDRMASK;
6381 pde = pmap_pdpe_to_pde(pdpe, sva);
6383 if ((oldpde & PG_V) == 0)
6385 else if ((oldpde & PG_PS) != 0) {
6386 if ((oldpde & PG_MANAGED) == 0)
6389 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6394 * The large page mapping was destroyed.
6400 * Unless the page mappings are wired, remove the
6401 * mapping to a single page so that a subsequent
6402 * access may repromote. Since the underlying page
6403 * table page is fully populated, this removal never
6404 * frees a page table page.
6406 if ((oldpde & PG_W) == 0) {
6407 pte = pmap_pde_to_pte(pde, sva);
6408 KASSERT((*pte & PG_V) != 0,
6409 ("pmap_advise: invalid PTE"));
6410 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6420 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6422 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6424 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6425 if (advice == MADV_DONTNEED) {
6427 * Future calls to pmap_is_modified()
6428 * can be avoided by making the page
6431 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6434 atomic_clear_long(pte, PG_M | PG_A);
6435 } else if ((*pte & PG_A) != 0)
6436 atomic_clear_long(pte, PG_A);
6440 if ((*pte & PG_G) != 0) {
6447 if (va != va_next) {
6448 pmap_invalidate_range(pmap, va, sva);
6453 pmap_invalidate_range(pmap, va, sva);
6456 pmap_invalidate_all(pmap);
6458 pmap_delayed_invl_finished();
6462 * Clear the modify bits on the specified physical page.
6465 pmap_clear_modify(vm_page_t m)
6467 struct md_page *pvh;
6469 pv_entry_t next_pv, pv;
6470 pd_entry_t oldpde, *pde;
6471 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6472 struct rwlock *lock;
6474 int md_gen, pvh_gen;
6476 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6477 ("pmap_clear_modify: page %p is not managed", m));
6478 VM_OBJECT_ASSERT_WLOCKED(m->object);
6479 KASSERT(!vm_page_xbusied(m),
6480 ("pmap_clear_modify: page %p is exclusive busied", m));
6483 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6484 * If the object containing the page is locked and the page is not
6485 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6487 if ((m->aflags & PGA_WRITEABLE) == 0)
6489 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6490 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6491 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6494 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6496 if (!PMAP_TRYLOCK(pmap)) {
6497 pvh_gen = pvh->pv_gen;
6501 if (pvh_gen != pvh->pv_gen) {
6506 PG_M = pmap_modified_bit(pmap);
6507 PG_V = pmap_valid_bit(pmap);
6508 PG_RW = pmap_rw_bit(pmap);
6510 pde = pmap_pde(pmap, va);
6512 if ((oldpde & PG_RW) != 0) {
6513 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6514 if ((oldpde & PG_W) == 0) {
6516 * Write protect the mapping to a
6517 * single page so that a subsequent
6518 * write access may repromote.
6520 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6522 pte = pmap_pde_to_pte(pde, va);
6524 if ((oldpte & PG_V) != 0) {
6525 while (!atomic_cmpset_long(pte,
6527 oldpte & ~(PG_M | PG_RW)))
6530 pmap_invalidate_page(pmap, va);
6537 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6539 if (!PMAP_TRYLOCK(pmap)) {
6540 md_gen = m->md.pv_gen;
6541 pvh_gen = pvh->pv_gen;
6545 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6550 PG_M = pmap_modified_bit(pmap);
6551 PG_RW = pmap_rw_bit(pmap);
6552 pde = pmap_pde(pmap, pv->pv_va);
6553 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6554 " a 2mpage in page %p's pv list", m));
6555 pte = pmap_pde_to_pte(pde, pv->pv_va);
6556 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6557 atomic_clear_long(pte, PG_M);
6558 pmap_invalidate_page(pmap, pv->pv_va);
6566 * Miscellaneous support routines follow
6569 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6570 static __inline void
6571 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6576 * The cache mode bits are all in the low 32-bits of the
6577 * PTE, so we can just spin on updating the low 32-bits.
6580 opte = *(u_int *)pte;
6581 npte = opte & ~mask;
6583 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6586 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6587 static __inline void
6588 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6593 * The cache mode bits are all in the low 32-bits of the
6594 * PDE, so we can just spin on updating the low 32-bits.
6597 opde = *(u_int *)pde;
6598 npde = opde & ~mask;
6600 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6604 * Map a set of physical memory pages into the kernel virtual
6605 * address space. Return a pointer to where it is mapped. This
6606 * routine is intended to be used for mapping device memory,
6610 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6612 struct pmap_preinit_mapping *ppim;
6613 vm_offset_t va, offset;
6617 offset = pa & PAGE_MASK;
6618 size = round_page(offset + size);
6619 pa = trunc_page(pa);
6621 if (!pmap_initialized) {
6623 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6624 ppim = pmap_preinit_mapping + i;
6625 if (ppim->va == 0) {
6629 ppim->va = virtual_avail;
6630 virtual_avail += size;
6636 panic("%s: too many preinit mappings", __func__);
6639 * If we have a preinit mapping, re-use it.
6641 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6642 ppim = pmap_preinit_mapping + i;
6643 if (ppim->pa == pa && ppim->sz == size &&
6645 return ((void *)(ppim->va + offset));
6648 * If the specified range of physical addresses fits within
6649 * the direct map window, use the direct map.
6651 if (pa < dmaplimit && pa + size < dmaplimit) {
6652 va = PHYS_TO_DMAP(pa);
6653 if (!pmap_change_attr(va, size, mode))
6654 return ((void *)(va + offset));
6656 va = kva_alloc(size);
6658 panic("%s: Couldn't allocate KVA", __func__);
6660 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6661 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6662 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6663 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6664 return ((void *)(va + offset));
6668 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6671 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6675 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6678 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6682 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6684 struct pmap_preinit_mapping *ppim;
6688 /* If we gave a direct map region in pmap_mapdev, do nothing */
6689 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6691 offset = va & PAGE_MASK;
6692 size = round_page(offset + size);
6693 va = trunc_page(va);
6694 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6695 ppim = pmap_preinit_mapping + i;
6696 if (ppim->va == va && ppim->sz == size) {
6697 if (pmap_initialized)
6703 if (va + size == virtual_avail)
6708 if (pmap_initialized)
6713 * Tries to demote a 1GB page mapping.
6716 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6718 pdp_entry_t newpdpe, oldpdpe;
6719 pd_entry_t *firstpde, newpde, *pde;
6720 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6724 PG_A = pmap_accessed_bit(pmap);
6725 PG_M = pmap_modified_bit(pmap);
6726 PG_V = pmap_valid_bit(pmap);
6727 PG_RW = pmap_rw_bit(pmap);
6729 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6731 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6732 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6733 if ((pdpg = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6734 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6735 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6736 " in pmap %p", va, pmap);
6739 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
6740 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
6741 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6742 KASSERT((oldpdpe & PG_A) != 0,
6743 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6744 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6745 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
6749 * Initialize the page directory page.
6751 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
6757 * Demote the mapping.
6762 * Invalidate a stale recursive mapping of the page directory page.
6764 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
6766 pmap_pdpe_demotions++;
6767 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
6768 " in pmap %p", va, pmap);
6773 * Sets the memory attribute for the specified page.
6776 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6779 m->md.pat_mode = ma;
6782 * If "m" is a normal page, update its direct mapping. This update
6783 * can be relied upon to perform any cache operations that are
6784 * required for data coherence.
6786 if ((m->flags & PG_FICTITIOUS) == 0 &&
6787 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6789 panic("memory attribute change on the direct map failed");
6793 * Changes the specified virtual address range's memory type to that given by
6794 * the parameter "mode". The specified virtual address range must be
6795 * completely contained within either the direct map or the kernel map. If
6796 * the virtual address range is contained within the kernel map, then the
6797 * memory type for each of the corresponding ranges of the direct map is also
6798 * changed. (The corresponding ranges of the direct map are those ranges that
6799 * map the same physical pages as the specified virtual address range.) These
6800 * changes to the direct map are necessary because Intel describes the
6801 * behavior of their processors as "undefined" if two or more mappings to the
6802 * same physical page have different memory types.
6804 * Returns zero if the change completed successfully, and either EINVAL or
6805 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6806 * of the virtual address range was not mapped, and ENOMEM is returned if
6807 * there was insufficient memory available to complete the change. In the
6808 * latter case, the memory type may have been changed on some part of the
6809 * virtual address range or the direct map.
6812 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6816 PMAP_LOCK(kernel_pmap);
6817 error = pmap_change_attr_locked(va, size, mode);
6818 PMAP_UNLOCK(kernel_pmap);
6823 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
6825 vm_offset_t base, offset, tmpva;
6826 vm_paddr_t pa_start, pa_end, pa_end1;
6830 int cache_bits_pte, cache_bits_pde, error;
6833 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6834 base = trunc_page(va);
6835 offset = va & PAGE_MASK;
6836 size = round_page(offset + size);
6839 * Only supported on kernel virtual addresses, including the direct
6840 * map but excluding the recursive map.
6842 if (base < DMAP_MIN_ADDRESS)
6845 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
6846 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
6850 * Pages that aren't mapped aren't supported. Also break down 2MB pages
6851 * into 4KB pages if required.
6853 for (tmpva = base; tmpva < base + size; ) {
6854 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6855 if (pdpe == NULL || *pdpe == 0)
6857 if (*pdpe & PG_PS) {
6859 * If the current 1GB page already has the required
6860 * memory type, then we need not demote this page. Just
6861 * increment tmpva to the next 1GB page frame.
6863 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
6864 tmpva = trunc_1gpage(tmpva) + NBPDP;
6869 * If the current offset aligns with a 1GB page frame
6870 * and there is at least 1GB left within the range, then
6871 * we need not break down this page into 2MB pages.
6873 if ((tmpva & PDPMASK) == 0 &&
6874 tmpva + PDPMASK < base + size) {
6878 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
6881 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6886 * If the current 2MB page already has the required
6887 * memory type, then we need not demote this page. Just
6888 * increment tmpva to the next 2MB page frame.
6890 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
6891 tmpva = trunc_2mpage(tmpva) + NBPDR;
6896 * If the current offset aligns with a 2MB page frame
6897 * and there is at least 2MB left within the range, then
6898 * we need not break down this page into 4KB pages.
6900 if ((tmpva & PDRMASK) == 0 &&
6901 tmpva + PDRMASK < base + size) {
6905 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
6908 pte = pmap_pde_to_pte(pde, tmpva);
6916 * Ok, all the pages exist, so run through them updating their
6917 * cache mode if required.
6919 pa_start = pa_end = 0;
6920 for (tmpva = base; tmpva < base + size; ) {
6921 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6922 if (*pdpe & PG_PS) {
6923 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
6924 pmap_pde_attr(pdpe, cache_bits_pde,
6928 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6929 (*pdpe & PG_PS_FRAME) < dmaplimit) {
6930 if (pa_start == pa_end) {
6931 /* Start physical address run. */
6932 pa_start = *pdpe & PG_PS_FRAME;
6933 pa_end = pa_start + NBPDP;
6934 } else if (pa_end == (*pdpe & PG_PS_FRAME))
6937 /* Run ended, update direct map. */
6938 error = pmap_change_attr_locked(
6939 PHYS_TO_DMAP(pa_start),
6940 pa_end - pa_start, mode);
6943 /* Start physical address run. */
6944 pa_start = *pdpe & PG_PS_FRAME;
6945 pa_end = pa_start + NBPDP;
6948 tmpva = trunc_1gpage(tmpva) + NBPDP;
6951 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6953 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
6954 pmap_pde_attr(pde, cache_bits_pde,
6958 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6959 (*pde & PG_PS_FRAME) < dmaplimit) {
6960 if (pa_start == pa_end) {
6961 /* Start physical address run. */
6962 pa_start = *pde & PG_PS_FRAME;
6963 pa_end = pa_start + NBPDR;
6964 } else if (pa_end == (*pde & PG_PS_FRAME))
6967 /* Run ended, update direct map. */
6968 error = pmap_change_attr_locked(
6969 PHYS_TO_DMAP(pa_start),
6970 pa_end - pa_start, mode);
6973 /* Start physical address run. */
6974 pa_start = *pde & PG_PS_FRAME;
6975 pa_end = pa_start + NBPDR;
6978 tmpva = trunc_2mpage(tmpva) + NBPDR;
6980 pte = pmap_pde_to_pte(pde, tmpva);
6981 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
6982 pmap_pte_attr(pte, cache_bits_pte,
6986 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6987 (*pte & PG_FRAME) < dmaplimit) {
6988 if (pa_start == pa_end) {
6989 /* Start physical address run. */
6990 pa_start = *pte & PG_FRAME;
6991 pa_end = pa_start + PAGE_SIZE;
6992 } else if (pa_end == (*pte & PG_FRAME))
6993 pa_end += PAGE_SIZE;
6995 /* Run ended, update direct map. */
6996 error = pmap_change_attr_locked(
6997 PHYS_TO_DMAP(pa_start),
6998 pa_end - pa_start, mode);
7001 /* Start physical address run. */
7002 pa_start = *pte & PG_FRAME;
7003 pa_end = pa_start + PAGE_SIZE;
7009 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
7010 pa_end1 = MIN(pa_end, dmaplimit);
7011 if (pa_start != pa_end1)
7012 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
7013 pa_end1 - pa_start, mode);
7017 * Flush CPU caches if required to make sure any data isn't cached that
7018 * shouldn't be, etc.
7021 pmap_invalidate_range(kernel_pmap, base, tmpva);
7022 pmap_invalidate_cache_range(base, tmpva, FALSE);
7028 * Demotes any mapping within the direct map region that covers more than the
7029 * specified range of physical addresses. This range's size must be a power
7030 * of two and its starting address must be a multiple of its size. Since the
7031 * demotion does not change any attributes of the mapping, a TLB invalidation
7032 * is not mandatory. The caller may, however, request a TLB invalidation.
7035 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
7044 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
7045 KASSERT((base & (len - 1)) == 0,
7046 ("pmap_demote_DMAP: base is not a multiple of len"));
7047 if (len < NBPDP && base < dmaplimit) {
7048 va = PHYS_TO_DMAP(base);
7050 PMAP_LOCK(kernel_pmap);
7051 pdpe = pmap_pdpe(kernel_pmap, va);
7052 if ((*pdpe & X86_PG_V) == 0)
7053 panic("pmap_demote_DMAP: invalid PDPE");
7054 if ((*pdpe & PG_PS) != 0) {
7055 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
7056 panic("pmap_demote_DMAP: PDPE failed");
7060 pde = pmap_pdpe_to_pde(pdpe, va);
7061 if ((*pde & X86_PG_V) == 0)
7062 panic("pmap_demote_DMAP: invalid PDE");
7063 if ((*pde & PG_PS) != 0) {
7064 if (!pmap_demote_pde(kernel_pmap, pde, va))
7065 panic("pmap_demote_DMAP: PDE failed");
7069 if (changed && invalidate)
7070 pmap_invalidate_page(kernel_pmap, va);
7071 PMAP_UNLOCK(kernel_pmap);
7076 * perform the pmap work for mincore
7079 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
7082 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
7086 PG_A = pmap_accessed_bit(pmap);
7087 PG_M = pmap_modified_bit(pmap);
7088 PG_V = pmap_valid_bit(pmap);
7089 PG_RW = pmap_rw_bit(pmap);
7093 pdep = pmap_pde(pmap, addr);
7094 if (pdep != NULL && (*pdep & PG_V)) {
7095 if (*pdep & PG_PS) {
7097 /* Compute the physical address of the 4KB page. */
7098 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
7100 val = MINCORE_SUPER;
7102 pte = *pmap_pde_to_pte(pdep, addr);
7103 pa = pte & PG_FRAME;
7111 if ((pte & PG_V) != 0) {
7112 val |= MINCORE_INCORE;
7113 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7114 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
7115 if ((pte & PG_A) != 0)
7116 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
7118 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
7119 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
7120 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
7121 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
7122 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
7125 PA_UNLOCK_COND(*locked_pa);
7131 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
7133 uint32_t gen, new_gen, pcid_next;
7135 CRITICAL_ASSERT(curthread);
7136 gen = PCPU_GET(pcid_gen);
7137 if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN ||
7138 pmap->pm_pcids[cpuid].pm_gen == gen)
7139 return (CR3_PCID_SAVE);
7140 pcid_next = PCPU_GET(pcid_next);
7141 KASSERT(pcid_next <= PMAP_PCID_OVERMAX, ("cpu %d pcid_next %#x",
7143 if (pcid_next == PMAP_PCID_OVERMAX) {
7147 PCPU_SET(pcid_gen, new_gen);
7148 pcid_next = PMAP_PCID_KERN + 1;
7152 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
7153 pmap->pm_pcids[cpuid].pm_gen = new_gen;
7154 PCPU_SET(pcid_next, pcid_next + 1);
7159 pmap_activate_sw(struct thread *td)
7161 pmap_t oldpmap, pmap;
7162 uint64_t cached, cr3;
7166 oldpmap = PCPU_GET(curpmap);
7167 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7168 if (oldpmap == pmap)
7170 cpuid = PCPU_GET(cpuid);
7172 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7174 CPU_SET(cpuid, &pmap->pm_active);
7177 if (pmap_pcid_enabled) {
7178 cached = pmap_pcid_alloc(pmap, cpuid);
7179 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
7180 pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
7181 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
7182 pmap->pm_pcids[cpuid].pm_pcid));
7183 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
7184 pmap == kernel_pmap,
7185 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
7186 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
7189 * If the INVPCID instruction is not available,
7190 * invltlb_pcid_handler() is used for handle
7191 * invalidate_all IPI, which checks for curpmap ==
7192 * smp_tlb_pmap. Below operations sequence has a
7193 * window where %CR3 is loaded with the new pmap's
7194 * PML4 address, but curpmap value is not yet updated.
7195 * This causes invltlb IPI handler, called between the
7196 * updates, to execute as NOP, which leaves stale TLB
7199 * Note that the most typical use of
7200 * pmap_activate_sw(), from the context switch, is
7201 * immune to this race, because interrupts are
7202 * disabled (while the thread lock is owned), and IPI
7203 * happends after curpmap is updated. Protect other
7204 * callers in a similar way, by disabling interrupts
7205 * around the %cr3 register reload and curpmap
7209 rflags = intr_disable();
7211 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
7212 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
7215 PCPU_INC(pm_save_cnt);
7217 PCPU_SET(curpmap, pmap);
7219 intr_restore(rflags);
7220 } else if (cr3 != pmap->pm_cr3) {
7221 load_cr3(pmap->pm_cr3);
7222 PCPU_SET(curpmap, pmap);
7224 PCPU_SET(kcr3, pmap->pm_cr3);
7225 PCPU_SET(ucr3, pmap->pm_ucr3);
7229 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
7231 CPU_CLR(cpuid, &oldpmap->pm_active);
7236 pmap_activate(struct thread *td)
7240 pmap_activate_sw(td);
7245 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
7250 * Increase the starting virtual address of the given mapping if a
7251 * different alignment might result in more superpage mappings.
7254 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7255 vm_offset_t *addr, vm_size_t size)
7257 vm_offset_t superpage_offset;
7261 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7262 offset += ptoa(object->pg_color);
7263 superpage_offset = offset & PDRMASK;
7264 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
7265 (*addr & PDRMASK) == superpage_offset)
7267 if ((*addr & PDRMASK) < superpage_offset)
7268 *addr = (*addr & ~PDRMASK) + superpage_offset;
7270 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
7274 static unsigned long num_dirty_emulations;
7275 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
7276 &num_dirty_emulations, 0, NULL);
7278 static unsigned long num_accessed_emulations;
7279 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
7280 &num_accessed_emulations, 0, NULL);
7282 static unsigned long num_superpage_accessed_emulations;
7283 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7284 &num_superpage_accessed_emulations, 0, NULL);
7286 static unsigned long ad_emulation_superpage_promotions;
7287 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7288 &ad_emulation_superpage_promotions, 0, NULL);
7289 #endif /* INVARIANTS */
7292 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7295 struct rwlock *lock;
7296 #if VM_NRESERVLEVEL > 0
7300 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7302 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7303 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7305 if (!pmap_emulate_ad_bits(pmap))
7308 PG_A = pmap_accessed_bit(pmap);
7309 PG_M = pmap_modified_bit(pmap);
7310 PG_V = pmap_valid_bit(pmap);
7311 PG_RW = pmap_rw_bit(pmap);
7317 pde = pmap_pde(pmap, va);
7318 if (pde == NULL || (*pde & PG_V) == 0)
7321 if ((*pde & PG_PS) != 0) {
7322 if (ftype == VM_PROT_READ) {
7324 atomic_add_long(&num_superpage_accessed_emulations, 1);
7332 pte = pmap_pde_to_pte(pde, va);
7333 if ((*pte & PG_V) == 0)
7336 if (ftype == VM_PROT_WRITE) {
7337 if ((*pte & PG_RW) == 0)
7340 * Set the modified and accessed bits simultaneously.
7342 * Intel EPT PTEs that do software emulation of A/D bits map
7343 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7344 * An EPT misconfiguration is triggered if the PTE is writable
7345 * but not readable (WR=10). This is avoided by setting PG_A
7346 * and PG_M simultaneously.
7348 *pte |= PG_M | PG_A;
7353 #if VM_NRESERVLEVEL > 0
7354 /* try to promote the mapping */
7355 if (va < VM_MAXUSER_ADDRESS)
7356 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7360 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7362 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7363 pmap_ps_enabled(pmap) &&
7364 (m->flags & PG_FICTITIOUS) == 0 &&
7365 vm_reserv_level_iffullpop(m) == 0) {
7366 pmap_promote_pde(pmap, pde, va, &lock);
7368 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7374 if (ftype == VM_PROT_WRITE)
7375 atomic_add_long(&num_dirty_emulations, 1);
7377 atomic_add_long(&num_accessed_emulations, 1);
7379 rv = 0; /* success */
7388 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7393 pt_entry_t *pte, PG_V;
7397 PG_V = pmap_valid_bit(pmap);
7400 pml4 = pmap_pml4e(pmap, va);
7402 if ((*pml4 & PG_V) == 0)
7405 pdp = pmap_pml4e_to_pdpe(pml4, va);
7407 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7410 pde = pmap_pdpe_to_pde(pdp, va);
7412 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7415 pte = pmap_pde_to_pte(pde, va);
7424 * Get the kernel virtual address of a set of physical pages. If there are
7425 * physical addresses not covered by the DMAP perform a transient mapping
7426 * that will be removed when calling pmap_unmap_io_transient.
7428 * \param page The pages the caller wishes to obtain the virtual
7429 * address on the kernel memory map.
7430 * \param vaddr On return contains the kernel virtual memory address
7431 * of the pages passed in the page parameter.
7432 * \param count Number of pages passed in.
7433 * \param can_fault TRUE if the thread using the mapped pages can take
7434 * page faults, FALSE otherwise.
7436 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7437 * finished or FALSE otherwise.
7441 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7442 boolean_t can_fault)
7445 boolean_t needs_mapping;
7447 int cache_bits, error, i;
7450 * Allocate any KVA space that we need, this is done in a separate
7451 * loop to prevent calling vmem_alloc while pinned.
7453 needs_mapping = FALSE;
7454 for (i = 0; i < count; i++) {
7455 paddr = VM_PAGE_TO_PHYS(page[i]);
7456 if (__predict_false(paddr >= dmaplimit)) {
7457 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7458 M_BESTFIT | M_WAITOK, &vaddr[i]);
7459 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7460 needs_mapping = TRUE;
7462 vaddr[i] = PHYS_TO_DMAP(paddr);
7466 /* Exit early if everything is covered by the DMAP */
7471 * NB: The sequence of updating a page table followed by accesses
7472 * to the corresponding pages used in the !DMAP case is subject to
7473 * the situation described in the "AMD64 Architecture Programmer's
7474 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7475 * Coherency Considerations". Therefore, issuing the INVLPG right
7476 * after modifying the PTE bits is crucial.
7480 for (i = 0; i < count; i++) {
7481 paddr = VM_PAGE_TO_PHYS(page[i]);
7482 if (paddr >= dmaplimit) {
7485 * Slow path, since we can get page faults
7486 * while mappings are active don't pin the
7487 * thread to the CPU and instead add a global
7488 * mapping visible to all CPUs.
7490 pmap_qenter(vaddr[i], &page[i], 1);
7492 pte = vtopte(vaddr[i]);
7493 cache_bits = pmap_cache_bits(kernel_pmap,
7494 page[i]->md.pat_mode, 0);
7495 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7502 return (needs_mapping);
7506 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7507 boolean_t can_fault)
7514 for (i = 0; i < count; i++) {
7515 paddr = VM_PAGE_TO_PHYS(page[i]);
7516 if (paddr >= dmaplimit) {
7518 pmap_qremove(vaddr[i], 1);
7519 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7525 pmap_quick_enter_page(vm_page_t m)
7529 paddr = VM_PAGE_TO_PHYS(m);
7530 if (paddr < dmaplimit)
7531 return (PHYS_TO_DMAP(paddr));
7532 mtx_lock_spin(&qframe_mtx);
7533 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7534 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7535 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7540 pmap_quick_remove_page(vm_offset_t addr)
7545 pte_store(vtopte(qframe), 0);
7547 mtx_unlock_spin(&qframe_mtx);
7551 pmap_pti_alloc_page(void)
7555 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7556 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_NOBUSY |
7557 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
7562 pmap_pti_free_page(vm_page_t m)
7565 KASSERT(m->wire_count > 0, ("page %p not wired", m));
7567 if (m->wire_count != 0)
7569 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
7570 vm_page_free_zero(m);
7584 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
7585 VM_OBJECT_WLOCK(pti_obj);
7586 pml4_pg = pmap_pti_alloc_page();
7587 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
7588 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
7589 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
7590 pdpe = pmap_pti_pdpe(va);
7591 pmap_pti_wire_pte(pdpe);
7593 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
7594 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
7595 pmap_pti_add_kva_locked((vm_offset_t)gdt, (vm_offset_t)gdt +
7596 sizeof(struct user_segment_descriptor) * NGDT * MAXCPU, false);
7597 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
7598 sizeof(struct gate_descriptor) * NIDT, false);
7599 pmap_pti_add_kva_locked((vm_offset_t)common_tss,
7600 (vm_offset_t)common_tss + sizeof(struct amd64tss) * MAXCPU, false);
7602 /* Doublefault stack IST 1 */
7603 va = common_tss[i].tss_ist1;
7604 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7605 /* NMI stack IST 2 */
7606 va = common_tss[i].tss_ist2 + sizeof(struct nmi_pcpu);
7607 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7608 /* MC# stack IST 3 */
7609 va = common_tss[i].tss_ist3 + sizeof(struct nmi_pcpu);
7610 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7612 pmap_pti_add_kva_locked((vm_offset_t)kernphys + KERNBASE,
7613 (vm_offset_t)etext, true);
7614 pti_finalized = true;
7615 VM_OBJECT_WUNLOCK(pti_obj);
7617 SYSINIT(pmap_pti, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_pti_init, NULL);
7619 static pdp_entry_t *
7620 pmap_pti_pdpe(vm_offset_t va)
7622 pml4_entry_t *pml4e;
7625 vm_pindex_t pml4_idx;
7628 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7630 pml4_idx = pmap_pml4e_index(va);
7631 pml4e = &pti_pml4[pml4_idx];
7635 panic("pml4 alloc after finalization\n");
7636 m = pmap_pti_alloc_page();
7638 pmap_pti_free_page(m);
7639 mphys = *pml4e & ~PAGE_MASK;
7641 mphys = VM_PAGE_TO_PHYS(m);
7642 *pml4e = mphys | X86_PG_RW | X86_PG_V;
7645 mphys = *pml4e & ~PAGE_MASK;
7647 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
7652 pmap_pti_wire_pte(void *pte)
7656 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7657 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7662 pmap_pti_unwire_pde(void *pde, bool only_ref)
7666 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7667 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
7668 MPASS(m->wire_count > 0);
7669 MPASS(only_ref || m->wire_count > 1);
7670 pmap_pti_free_page(m);
7674 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
7679 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7680 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7681 MPASS(m->wire_count > 0);
7682 if (pmap_pti_free_page(m)) {
7683 pde = pmap_pti_pde(va);
7684 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
7686 pmap_pti_unwire_pde(pde, false);
7691 pmap_pti_pde(vm_offset_t va)
7699 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7701 pdpe = pmap_pti_pdpe(va);
7703 m = pmap_pti_alloc_page();
7705 pmap_pti_free_page(m);
7706 MPASS((*pdpe & X86_PG_PS) == 0);
7707 mphys = *pdpe & ~PAGE_MASK;
7709 mphys = VM_PAGE_TO_PHYS(m);
7710 *pdpe = mphys | X86_PG_RW | X86_PG_V;
7713 MPASS((*pdpe & X86_PG_PS) == 0);
7714 mphys = *pdpe & ~PAGE_MASK;
7717 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
7718 pd_idx = pmap_pde_index(va);
7724 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
7731 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7733 pde = pmap_pti_pde(va);
7734 if (unwire_pde != NULL) {
7736 pmap_pti_wire_pte(pde);
7739 m = pmap_pti_alloc_page();
7741 pmap_pti_free_page(m);
7742 MPASS((*pde & X86_PG_PS) == 0);
7743 mphys = *pde & ~(PAGE_MASK | pg_nx);
7745 mphys = VM_PAGE_TO_PHYS(m);
7746 *pde = mphys | X86_PG_RW | X86_PG_V;
7747 if (unwire_pde != NULL)
7748 *unwire_pde = false;
7751 MPASS((*pde & X86_PG_PS) == 0);
7752 mphys = *pde & ~(PAGE_MASK | pg_nx);
7755 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
7756 pte += pmap_pte_index(va);
7762 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
7766 pt_entry_t *pte, ptev;
7769 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7771 sva = trunc_page(sva);
7772 MPASS(sva > VM_MAXUSER_ADDRESS);
7773 eva = round_page(eva);
7775 for (; sva < eva; sva += PAGE_SIZE) {
7776 pte = pmap_pti_pte(sva, &unwire_pde);
7777 pa = pmap_kextract(sva);
7778 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A |
7779 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
7780 VM_MEMATTR_DEFAULT, FALSE);
7782 pte_store(pte, ptev);
7783 pmap_pti_wire_pte(pte);
7785 KASSERT(!pti_finalized,
7786 ("pti overlap after fin %#lx %#lx %#lx",
7788 KASSERT(*pte == ptev,
7789 ("pti non-identical pte after fin %#lx %#lx %#lx",
7793 pde = pmap_pti_pde(sva);
7794 pmap_pti_unwire_pde(pde, true);
7800 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
7805 VM_OBJECT_WLOCK(pti_obj);
7806 pmap_pti_add_kva_locked(sva, eva, exec);
7807 VM_OBJECT_WUNLOCK(pti_obj);
7811 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
7818 sva = rounddown2(sva, PAGE_SIZE);
7819 MPASS(sva > VM_MAXUSER_ADDRESS);
7820 eva = roundup2(eva, PAGE_SIZE);
7822 VM_OBJECT_WLOCK(pti_obj);
7823 for (va = sva; va < eva; va += PAGE_SIZE) {
7824 pte = pmap_pti_pte(va, NULL);
7825 KASSERT((*pte & X86_PG_V) != 0,
7826 ("invalid pte va %#lx pte %#lx pt %#lx", va,
7827 (u_long)pte, *pte));
7829 pmap_pti_unwire_pte(pte, va);
7831 pmap_invalidate_range(kernel_pmap, sva, eva);
7832 VM_OBJECT_WUNLOCK(pti_obj);
7835 #include "opt_ddb.h"
7837 #include <sys/kdb.h>
7838 #include <ddb/ddb.h>
7840 DB_SHOW_COMMAND(pte, pmap_print_pte)
7846 pt_entry_t *pte, PG_V;
7850 db_printf("show pte addr\n");
7853 va = (vm_offset_t)addr;
7855 if (kdb_thread != NULL)
7856 pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
7858 pmap = PCPU_GET(curpmap);
7860 PG_V = pmap_valid_bit(pmap);
7861 pml4 = pmap_pml4e(pmap, va);
7862 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
7863 if ((*pml4 & PG_V) == 0) {
7867 pdp = pmap_pml4e_to_pdpe(pml4, va);
7868 db_printf(" pdpe %#016lx", *pdp);
7869 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
7873 pde = pmap_pdpe_to_pde(pdp, va);
7874 db_printf(" pde %#016lx", *pde);
7875 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
7879 pte = pmap_pde_to_pte(pde, va);
7880 db_printf(" pte %#016lx\n", *pte);
7883 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
7888 a = (vm_paddr_t)addr;
7889 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
7891 db_printf("show phys2dmap addr\n");