2 * SPDX-License-Identifier: BSD-4-Clause
4 * Copyright (c) 1991 Regents of the University of California.
6 * Copyright (c) 1994 John S. Dyson
8 * Copyright (c) 1994 David Greenman
10 * Copyright (c) 2003 Peter Wemm
11 * All rights reserved.
12 * Copyright (c) 2005-2010 Alan L. Cox <alc@cs.rice.edu>
13 * All rights reserved.
15 * This code is derived from software contributed to Berkeley by
16 * the Systems Programming Group of the University of Utah Computer
17 * Science Department and William Jolitz of UUNET Technologies Inc.
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
22 * 1. Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
24 * 2. Redistributions in binary form must reproduce the above copyright
25 * notice, this list of conditions and the following disclaimer in the
26 * documentation and/or other materials provided with the distribution.
27 * 3. All advertising materials mentioning features or use of this software
28 * must display the following acknowledgement:
29 * This product includes software developed by the University of
30 * California, Berkeley and its contributors.
31 * 4. Neither the name of the University nor the names of its contributors
32 * may be used to endorse or promote products derived from this software
33 * without specific prior written permission.
35 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
36 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
39 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
40 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
41 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
42 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
43 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
44 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * from: @(#)pmap.c 7.7 (Berkeley) 5/12/91
50 * Copyright (c) 2003 Networks Associates Technology, Inc.
51 * Copyright (c) 2014-2018 The FreeBSD Foundation
52 * All rights reserved.
54 * This software was developed for the FreeBSD Project by Jake Burkholder,
55 * Safeport Network Services, and Network Associates Laboratories, the
56 * Security Research Division of Network Associates, Inc. under
57 * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
58 * CHATS research program.
60 * Portions of this software were developed by
61 * Konstantin Belousov <kib@FreeBSD.org> under sponsorship from
62 * the FreeBSD Foundation.
64 * Redistribution and use in source and binary forms, with or without
65 * modification, are permitted provided that the following conditions
67 * 1. Redistributions of source code must retain the above copyright
68 * notice, this list of conditions and the following disclaimer.
69 * 2. Redistributions in binary form must reproduce the above copyright
70 * notice, this list of conditions and the following disclaimer in the
71 * documentation and/or other materials provided with the distribution.
73 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
74 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
75 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
76 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
77 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
78 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
79 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
80 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
81 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
82 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
86 #define AMD64_NPT_AWARE
88 #include <sys/cdefs.h>
89 __FBSDID("$FreeBSD$");
92 * Manages physical address maps.
94 * Since the information managed by this module is
95 * also stored by the logical address mapping module,
96 * this module may throw away valid virtual-to-physical
97 * mappings at almost any time. However, invalidations
98 * of virtual-to-physical mappings must be done as
101 * In order to cope with hardware architectures which
102 * make virtual-to-physical map invalidates expensive,
103 * this module may delay invalidate or reduced protection
104 * operations until such time as they are actually
105 * necessary. This module is given full information as
106 * to which processors are currently using which maps,
107 * and to when physical maps must be made correct.
110 #include "opt_pmap.h"
113 #include <sys/param.h>
114 #include <sys/bitstring.h>
116 #include <sys/systm.h>
117 #include <sys/kernel.h>
119 #include <sys/lock.h>
120 #include <sys/malloc.h>
121 #include <sys/mman.h>
122 #include <sys/mutex.h>
123 #include <sys/proc.h>
124 #include <sys/rwlock.h>
126 #include <sys/turnstile.h>
127 #include <sys/vmem.h>
128 #include <sys/vmmeter.h>
129 #include <sys/sched.h>
130 #include <sys/sysctl.h>
134 #include <vm/vm_param.h>
135 #include <vm/vm_kern.h>
136 #include <vm/vm_page.h>
137 #include <vm/vm_map.h>
138 #include <vm/vm_object.h>
139 #include <vm/vm_extern.h>
140 #include <vm/vm_pageout.h>
141 #include <vm/vm_pager.h>
142 #include <vm/vm_phys.h>
143 #include <vm/vm_radix.h>
144 #include <vm/vm_reserv.h>
147 #include <machine/intr_machdep.h>
148 #include <x86/apicvar.h>
149 #include <machine/cpu.h>
150 #include <machine/cputypes.h>
151 #include <machine/md_var.h>
152 #include <machine/pcb.h>
153 #include <machine/specialreg.h>
155 #include <machine/smp.h>
157 #include <machine/tss.h>
159 static __inline boolean_t
160 pmap_type_guest(pmap_t pmap)
163 return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
166 static __inline boolean_t
167 pmap_emulate_ad_bits(pmap_t pmap)
170 return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
173 static __inline pt_entry_t
174 pmap_valid_bit(pmap_t pmap)
178 switch (pmap->pm_type) {
184 if (pmap_emulate_ad_bits(pmap))
185 mask = EPT_PG_EMUL_V;
190 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
196 static __inline pt_entry_t
197 pmap_rw_bit(pmap_t pmap)
201 switch (pmap->pm_type) {
207 if (pmap_emulate_ad_bits(pmap))
208 mask = EPT_PG_EMUL_RW;
213 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
219 static pt_entry_t pg_g;
221 static __inline pt_entry_t
222 pmap_global_bit(pmap_t pmap)
226 switch (pmap->pm_type) {
235 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
241 static __inline pt_entry_t
242 pmap_accessed_bit(pmap_t pmap)
246 switch (pmap->pm_type) {
252 if (pmap_emulate_ad_bits(pmap))
258 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
264 static __inline pt_entry_t
265 pmap_modified_bit(pmap_t pmap)
269 switch (pmap->pm_type) {
275 if (pmap_emulate_ad_bits(pmap))
281 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
287 #if !defined(DIAGNOSTIC)
288 #ifdef __GNUC_GNU_INLINE__
289 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
291 #define PMAP_INLINE extern inline
298 #define PV_STAT(x) do { x ; } while (0)
300 #define PV_STAT(x) do { } while (0)
303 #define pa_index(pa) ((pa) >> PDRSHIFT)
304 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
306 #define NPV_LIST_LOCKS MAXCPU
308 #define PHYS_TO_PV_LIST_LOCK(pa) \
309 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
311 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
312 struct rwlock **_lockp = (lockp); \
313 struct rwlock *_new_lock; \
315 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
316 if (_new_lock != *_lockp) { \
317 if (*_lockp != NULL) \
318 rw_wunlock(*_lockp); \
319 *_lockp = _new_lock; \
324 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
325 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
327 #define RELEASE_PV_LIST_LOCK(lockp) do { \
328 struct rwlock **_lockp = (lockp); \
330 if (*_lockp != NULL) { \
331 rw_wunlock(*_lockp); \
336 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
337 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
339 struct pmap kernel_pmap_store;
341 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
342 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
345 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
346 "Number of kernel page table pages allocated on bootup");
349 vm_paddr_t dmaplimit;
350 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
353 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
355 static int pat_works = 1;
356 SYSCTL_INT(_vm_pmap, OID_AUTO, pat_works, CTLFLAG_RD, &pat_works, 1,
357 "Is page attribute table fully functional?");
359 static int pg_ps_enabled = 1;
360 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
361 &pg_ps_enabled, 0, "Are large page mappings enabled?");
363 #define PAT_INDEX_SIZE 8
364 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
366 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
367 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
368 u_int64_t KPDPphys; /* phys addr of kernel level 3 */
369 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
371 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
372 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
373 static int ndmpdpphys; /* number of DMPDPphys pages */
376 * pmap_mapdev support pre initialization (i.e. console)
378 #define PMAP_PREINIT_MAPPING_COUNT 8
379 static struct pmap_preinit_mapping {
384 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
385 static int pmap_initialized;
388 * Data for the pv entry allocation mechanism.
389 * Updates to pv_invl_gen are protected by the pv_list_locks[]
390 * elements, but reads are not.
392 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
393 static struct mtx __exclusive_cache_line pv_chunks_mutex;
394 static struct rwlock __exclusive_cache_line pv_list_locks[NPV_LIST_LOCKS];
395 static u_long pv_invl_gen[NPV_LIST_LOCKS];
396 static struct md_page *pv_table;
397 static struct md_page pv_dummy;
400 * All those kernel PT submaps that BSD is so fond of
402 pt_entry_t *CMAP1 = NULL;
404 static vm_offset_t qframe = 0;
405 static struct mtx qframe_mtx;
407 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
409 int pmap_pcid_enabled = 1;
410 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
411 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
412 int invpcid_works = 0;
413 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
414 "Is the invpcid instruction available ?");
417 SYSCTL_INT(_vm_pmap, OID_AUTO, pti, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
419 "Page Table Isolation enabled");
420 static vm_object_t pti_obj;
421 static pml4_entry_t *pti_pml4;
422 static vm_pindex_t pti_pg_idx;
423 static bool pti_finalized;
426 pmap_pcid_save_cnt_proc(SYSCTL_HANDLER_ARGS)
433 res += cpuid_to_pcpu[i]->pc_pm_save_cnt;
435 return (sysctl_handle_64(oidp, &res, 0, req));
437 SYSCTL_PROC(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLTYPE_U64 | CTLFLAG_RW |
438 CTLFLAG_MPSAFE, NULL, 0, pmap_pcid_save_cnt_proc, "QU",
439 "Count of saved TLB context on switch");
441 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
442 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
443 static struct mtx invl_gen_mtx;
444 static u_long pmap_invl_gen = 0;
445 /* Fake lock object to satisfy turnstiles interface. */
446 static struct lock_object invl_gen_ts = {
454 return (curthread->td_md.md_invl_gen.gen == 0);
457 #define PMAP_ASSERT_NOT_IN_DI() \
458 KASSERT(pmap_not_in_di(), ("DI already started"))
461 * Start a new Delayed Invalidation (DI) block of code, executed by
462 * the current thread. Within a DI block, the current thread may
463 * destroy both the page table and PV list entries for a mapping and
464 * then release the corresponding PV list lock before ensuring that
465 * the mapping is flushed from the TLBs of any processors with the
469 pmap_delayed_invl_started(void)
471 struct pmap_invl_gen *invl_gen;
474 invl_gen = &curthread->td_md.md_invl_gen;
475 PMAP_ASSERT_NOT_IN_DI();
476 mtx_lock(&invl_gen_mtx);
477 if (LIST_EMPTY(&pmap_invl_gen_tracker))
478 currgen = pmap_invl_gen;
480 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
481 invl_gen->gen = currgen + 1;
482 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
483 mtx_unlock(&invl_gen_mtx);
487 * Finish the DI block, previously started by the current thread. All
488 * required TLB flushes for the pages marked by
489 * pmap_delayed_invl_page() must be finished before this function is
492 * This function works by bumping the global DI generation number to
493 * the generation number of the current thread's DI, unless there is a
494 * pending DI that started earlier. In the latter case, bumping the
495 * global DI generation number would incorrectly signal that the
496 * earlier DI had finished. Instead, this function bumps the earlier
497 * DI's generation number to match the generation number of the
498 * current thread's DI.
501 pmap_delayed_invl_finished(void)
503 struct pmap_invl_gen *invl_gen, *next;
504 struct turnstile *ts;
506 invl_gen = &curthread->td_md.md_invl_gen;
507 KASSERT(invl_gen->gen != 0, ("missed invl_started"));
508 mtx_lock(&invl_gen_mtx);
509 next = LIST_NEXT(invl_gen, link);
511 turnstile_chain_lock(&invl_gen_ts);
512 ts = turnstile_lookup(&invl_gen_ts);
513 pmap_invl_gen = invl_gen->gen;
515 turnstile_broadcast(ts, TS_SHARED_QUEUE);
516 turnstile_unpend(ts, TS_SHARED_LOCK);
518 turnstile_chain_unlock(&invl_gen_ts);
520 next->gen = invl_gen->gen;
522 LIST_REMOVE(invl_gen, link);
523 mtx_unlock(&invl_gen_mtx);
528 static long invl_wait;
529 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
530 "Number of times DI invalidation blocked pmap_remove_all/write");
534 pmap_delayed_invl_genp(vm_page_t m)
537 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
541 * Ensure that all currently executing DI blocks, that need to flush
542 * TLB for the given page m, actually flushed the TLB at the time the
543 * function returned. If the page m has an empty PV list and we call
544 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
545 * valid mapping for the page m in either its page table or TLB.
547 * This function works by blocking until the global DI generation
548 * number catches up with the generation number associated with the
549 * given page m and its PV list. Since this function's callers
550 * typically own an object lock and sometimes own a page lock, it
551 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
555 pmap_delayed_invl_wait(vm_page_t m)
557 struct turnstile *ts;
560 bool accounted = false;
563 m_gen = pmap_delayed_invl_genp(m);
564 while (*m_gen > pmap_invl_gen) {
567 atomic_add_long(&invl_wait, 1);
571 ts = turnstile_trywait(&invl_gen_ts);
572 if (*m_gen > pmap_invl_gen)
573 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
575 turnstile_cancel(ts);
580 * Mark the page m's PV list as participating in the current thread's
581 * DI block. Any threads concurrently using m's PV list to remove or
582 * restrict all mappings to m will wait for the current thread's DI
583 * block to complete before proceeding.
585 * The function works by setting the DI generation number for m's PV
586 * list to at least the DI generation number of the current thread.
587 * This forces a caller of pmap_delayed_invl_wait() to block until
588 * current thread calls pmap_delayed_invl_finished().
591 pmap_delayed_invl_page(vm_page_t m)
595 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
596 gen = curthread->td_md.md_invl_gen.gen;
599 m_gen = pmap_delayed_invl_genp(m);
607 static caddr_t crashdumpmap;
610 * Internal flags for pmap_enter()'s helper functions.
612 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
613 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
615 static void free_pv_chunk(struct pv_chunk *pc);
616 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
617 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
618 static int popcnt_pc_map_pq(uint64_t *map);
619 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
620 static void reserve_pv_entries(pmap_t pmap, int needed,
621 struct rwlock **lockp);
622 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
623 struct rwlock **lockp);
624 static bool pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
625 u_int flags, struct rwlock **lockp);
626 #if VM_NRESERVLEVEL > 0
627 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
628 struct rwlock **lockp);
630 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
631 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
634 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode);
635 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
636 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
637 vm_offset_t va, struct rwlock **lockp);
638 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
640 static bool pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
641 vm_prot_t prot, struct rwlock **lockp);
642 static int pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
643 u_int flags, vm_page_t m, struct rwlock **lockp);
644 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
645 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
646 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
647 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
648 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
650 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
651 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask);
652 #if VM_NRESERVLEVEL > 0
653 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
654 struct rwlock **lockp);
656 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
658 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
659 static void pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva,
661 static pdp_entry_t *pmap_pti_pdpe(vm_offset_t va);
662 static pd_entry_t *pmap_pti_pde(vm_offset_t va);
663 static void pmap_pti_wire_pte(void *pte);
664 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
665 struct spglist *free, struct rwlock **lockp);
666 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
667 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
668 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
669 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
670 struct spglist *free);
671 static bool pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
672 pd_entry_t *pde, struct spglist *free,
673 struct rwlock **lockp);
674 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
675 vm_page_t m, struct rwlock **lockp);
676 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
678 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
680 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
681 struct rwlock **lockp);
682 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
683 struct rwlock **lockp);
684 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
685 struct rwlock **lockp);
687 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
688 struct spglist *free);
689 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
690 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
693 * Move the kernel virtual free pointer to the next
694 * 2MB. This is used to help improve performance
695 * by using a large (2MB) page for much of the kernel
696 * (.text, .data, .bss)
699 pmap_kmem_choose(vm_offset_t addr)
701 vm_offset_t newaddr = addr;
703 newaddr = roundup2(addr, NBPDR);
707 /********************/
708 /* Inline functions */
709 /********************/
711 /* Return a non-clipped PD index for a given VA */
712 static __inline vm_pindex_t
713 pmap_pde_pindex(vm_offset_t va)
715 return (va >> PDRSHIFT);
719 /* Return a pointer to the PML4 slot that corresponds to a VA */
720 static __inline pml4_entry_t *
721 pmap_pml4e(pmap_t pmap, vm_offset_t va)
724 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
727 /* Return a pointer to the PDP slot that corresponds to a VA */
728 static __inline pdp_entry_t *
729 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
733 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
734 return (&pdpe[pmap_pdpe_index(va)]);
737 /* Return a pointer to the PDP slot that corresponds to a VA */
738 static __inline pdp_entry_t *
739 pmap_pdpe(pmap_t pmap, vm_offset_t va)
744 PG_V = pmap_valid_bit(pmap);
745 pml4e = pmap_pml4e(pmap, va);
746 if ((*pml4e & PG_V) == 0)
748 return (pmap_pml4e_to_pdpe(pml4e, va));
751 /* Return a pointer to the PD slot that corresponds to a VA */
752 static __inline pd_entry_t *
753 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
757 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
758 return (&pde[pmap_pde_index(va)]);
761 /* Return a pointer to the PD slot that corresponds to a VA */
762 static __inline pd_entry_t *
763 pmap_pde(pmap_t pmap, vm_offset_t va)
768 PG_V = pmap_valid_bit(pmap);
769 pdpe = pmap_pdpe(pmap, va);
770 if (pdpe == NULL || (*pdpe & PG_V) == 0)
772 return (pmap_pdpe_to_pde(pdpe, va));
775 /* Return a pointer to the PT slot that corresponds to a VA */
776 static __inline pt_entry_t *
777 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
781 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
782 return (&pte[pmap_pte_index(va)]);
785 /* Return a pointer to the PT slot that corresponds to a VA */
786 static __inline pt_entry_t *
787 pmap_pte(pmap_t pmap, vm_offset_t va)
792 PG_V = pmap_valid_bit(pmap);
793 pde = pmap_pde(pmap, va);
794 if (pde == NULL || (*pde & PG_V) == 0)
796 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
797 return ((pt_entry_t *)pde);
798 return (pmap_pde_to_pte(pde, va));
802 pmap_resident_count_inc(pmap_t pmap, int count)
805 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
806 pmap->pm_stats.resident_count += count;
810 pmap_resident_count_dec(pmap_t pmap, int count)
813 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
814 KASSERT(pmap->pm_stats.resident_count >= count,
815 ("pmap %p resident count underflow %ld %d", pmap,
816 pmap->pm_stats.resident_count, count));
817 pmap->pm_stats.resident_count -= count;
820 PMAP_INLINE pt_entry_t *
821 vtopte(vm_offset_t va)
823 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
825 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
827 return (PTmap + ((va >> PAGE_SHIFT) & mask));
830 static __inline pd_entry_t *
831 vtopde(vm_offset_t va)
833 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
835 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
837 return (PDmap + ((va >> PDRSHIFT) & mask));
841 allocpages(vm_paddr_t *firstaddr, int n)
846 bzero((void *)ret, n * PAGE_SIZE);
847 *firstaddr += n * PAGE_SIZE;
851 CTASSERT(powerof2(NDMPML4E));
853 /* number of kernel PDP slots */
854 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
857 nkpt_init(vm_paddr_t addr)
864 pt_pages = howmany(addr, 1 << PDRSHIFT);
865 pt_pages += NKPDPE(pt_pages);
868 * Add some slop beyond the bare minimum required for bootstrapping
871 * This is quite important when allocating KVA for kernel modules.
872 * The modules are required to be linked in the negative 2GB of
873 * the address space. If we run out of KVA in this region then
874 * pmap_growkernel() will need to allocate page table pages to map
875 * the entire 512GB of KVA space which is an unnecessary tax on
878 * Secondly, device memory mapped as part of setting up the low-
879 * level console(s) is taken from KVA, starting at virtual_avail.
880 * This is because cninit() is called after pmap_bootstrap() but
881 * before vm_init() and pmap_init(). 20MB for a frame buffer is
884 pt_pages += 32; /* 64MB additional slop. */
890 create_pagetables(vm_paddr_t *firstaddr)
892 int i, j, ndm1g, nkpdpe;
898 /* Allocate page table pages for the direct map */
899 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
900 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
902 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
903 if (ndmpdpphys > NDMPML4E) {
905 * Each NDMPML4E allows 512 GB, so limit to that,
906 * and then readjust ndmpdp and ndmpdpphys.
908 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
909 Maxmem = atop(NDMPML4E * NBPML4);
910 ndmpdpphys = NDMPML4E;
911 ndmpdp = NDMPML4E * NPDEPG;
913 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
915 if ((amd_feature & AMDID_PAGE1GB) != 0)
916 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
918 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
919 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
922 KPML4phys = allocpages(firstaddr, 1);
923 KPDPphys = allocpages(firstaddr, NKPML4E);
926 * Allocate the initial number of kernel page table pages required to
927 * bootstrap. We defer this until after all memory-size dependent
928 * allocations are done (e.g. direct map), so that we don't have to
929 * build in too much slop in our estimate.
931 * Note that when NKPML4E > 1, we have an empty page underneath
932 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
933 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
935 nkpt_init(*firstaddr);
936 nkpdpe = NKPDPE(nkpt);
938 KPTphys = allocpages(firstaddr, nkpt);
939 KPDphys = allocpages(firstaddr, nkpdpe);
941 /* Fill in the underlying page table pages */
942 /* Nominally read-only (but really R/W) from zero to physfree */
943 /* XXX not fully used, underneath 2M pages */
944 pt_p = (pt_entry_t *)KPTphys;
945 for (i = 0; ptoa(i) < *firstaddr; i++)
946 pt_p[i] = ptoa(i) | X86_PG_RW | X86_PG_V | pg_g;
948 /* Now map the page tables at their location within PTmap */
949 pd_p = (pd_entry_t *)KPDphys;
950 for (i = 0; i < nkpt; i++)
951 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
953 /* Map from zero to end of allocations under 2M pages */
954 /* This replaces some of the KPTphys entries above */
955 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
956 pd_p[i] = (i << PDRSHIFT) | X86_PG_RW | X86_PG_V | PG_PS |
960 * Because we map the physical blocks in 2M pages, adjust firstaddr
961 * to record the physical blocks we've actually mapped into kernel
962 * virtual address space.
964 *firstaddr = round_2mpage(*firstaddr);
966 /* And connect up the PD to the PDP (leaving room for L4 pages) */
967 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
968 for (i = 0; i < nkpdpe; i++)
969 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
973 * Now, set up the direct map region using 2MB and/or 1GB pages. If
974 * the end of physical memory is not aligned to a 1GB page boundary,
975 * then the residual physical memory is mapped with 2MB pages. Later,
976 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
977 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
978 * that are partially used.
980 pd_p = (pd_entry_t *)DMPDphys;
981 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
982 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
983 /* Preset PG_M and PG_A because demotion expects it. */
984 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
985 X86_PG_M | X86_PG_A | pg_nx;
987 pdp_p = (pdp_entry_t *)DMPDPphys;
988 for (i = 0; i < ndm1g; i++) {
989 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
990 /* Preset PG_M and PG_A because demotion expects it. */
991 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
992 X86_PG_M | X86_PG_A | pg_nx;
994 for (j = 0; i < ndmpdp; i++, j++) {
995 pdp_p[i] = DMPDphys + ptoa(j);
996 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_U;
999 /* And recursively map PML4 to itself in order to get PTmap */
1000 p4_p = (pml4_entry_t *)KPML4phys;
1001 p4_p[PML4PML4I] = KPML4phys;
1002 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | PG_U;
1004 /* Connect the Direct Map slot(s) up to the PML4. */
1005 for (i = 0; i < ndmpdpphys; i++) {
1006 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
1007 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | PG_U;
1010 /* Connect the KVA slots up to the PML4 */
1011 for (i = 0; i < NKPML4E; i++) {
1012 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
1013 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V | PG_U;
1018 * Bootstrap the system enough to run with virtual memory.
1020 * On amd64 this is called after mapping has already been enabled
1021 * and just syncs the pmap module with what has already been done.
1022 * [We can't call it easily with mapping off since the kernel is not
1023 * mapped with PA == VA, hence we would have to relocate every address
1024 * from the linked base (virtual) address "KERNBASE" to the actual
1025 * (physical) address starting relative to 0]
1028 pmap_bootstrap(vm_paddr_t *firstaddr)
1038 * Create an initial set of page tables to run the kernel in.
1040 create_pagetables(firstaddr);
1043 * Add a physical memory segment (vm_phys_seg) corresponding to the
1044 * preallocated kernel page table pages so that vm_page structures
1045 * representing these pages will be created. The vm_page structures
1046 * are required for promotion of the corresponding kernel virtual
1047 * addresses to superpage mappings.
1049 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1051 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
1052 virtual_avail = pmap_kmem_choose(virtual_avail);
1054 virtual_end = VM_MAX_KERNEL_ADDRESS;
1057 /* XXX do %cr0 as well */
1058 load_cr4(rcr4() | CR4_PGE);
1059 load_cr3(KPML4phys);
1060 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1061 load_cr4(rcr4() | CR4_SMEP);
1064 * Initialize the kernel pmap (which is statically allocated).
1066 PMAP_LOCK_INIT(kernel_pmap);
1067 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1068 kernel_pmap->pm_cr3 = KPML4phys;
1069 kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
1070 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1071 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1072 kernel_pmap->pm_flags = pmap_flags;
1075 * Initialize the TLB invalidations generation number lock.
1077 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1080 * Reserve some special page table entries/VA space for temporary
1083 #define SYSMAP(c, p, v, n) \
1084 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1090 * Crashdump maps. The first page is reused as CMAP1 for the
1093 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1094 CADDR1 = crashdumpmap;
1099 * Initialize the PAT MSR.
1100 * pmap_init_pat() clears and sets CR4_PGE, which, as a
1101 * side-effect, invalidates stale PG_G TLB entries that might
1102 * have been created in our pre-boot environment.
1106 /* Initialize TLB Context Id. */
1107 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1108 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1109 /* Check for INVPCID support */
1110 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1112 for (i = 0; i < MAXCPU; i++) {
1113 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1114 kernel_pmap->pm_pcids[i].pm_gen = 1;
1116 PCPU_SET(pcid_next, PMAP_PCID_KERN + 1);
1117 PCPU_SET(pcid_gen, 1);
1119 * pcpu area for APs is zeroed during AP startup.
1120 * pc_pcid_next and pc_pcid_gen are initialized by AP
1121 * during pcpu setup.
1123 load_cr4(rcr4() | CR4_PCIDE);
1125 pmap_pcid_enabled = 0;
1130 * Setup the PAT MSR.
1135 int pat_table[PAT_INDEX_SIZE];
1140 /* Bail if this CPU doesn't implement PAT. */
1141 if ((cpu_feature & CPUID_PAT) == 0)
1144 /* Set default PAT index table. */
1145 for (i = 0; i < PAT_INDEX_SIZE; i++)
1147 pat_table[PAT_WRITE_BACK] = 0;
1148 pat_table[PAT_WRITE_THROUGH] = 1;
1149 pat_table[PAT_UNCACHEABLE] = 3;
1150 pat_table[PAT_WRITE_COMBINING] = 3;
1151 pat_table[PAT_WRITE_PROTECTED] = 3;
1152 pat_table[PAT_UNCACHED] = 3;
1154 /* Initialize default PAT entries. */
1155 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1156 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1157 PAT_VALUE(2, PAT_UNCACHED) |
1158 PAT_VALUE(3, PAT_UNCACHEABLE) |
1159 PAT_VALUE(4, PAT_WRITE_BACK) |
1160 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1161 PAT_VALUE(6, PAT_UNCACHED) |
1162 PAT_VALUE(7, PAT_UNCACHEABLE);
1166 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1167 * Program 5 and 6 as WP and WC.
1168 * Leave 4 and 7 as WB and UC.
1170 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1171 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1172 PAT_VALUE(6, PAT_WRITE_COMBINING);
1173 pat_table[PAT_UNCACHED] = 2;
1174 pat_table[PAT_WRITE_PROTECTED] = 5;
1175 pat_table[PAT_WRITE_COMBINING] = 6;
1178 * Just replace PAT Index 2 with WC instead of UC-.
1180 pat_msr &= ~PAT_MASK(2);
1181 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1182 pat_table[PAT_WRITE_COMBINING] = 2;
1187 load_cr4(cr4 & ~CR4_PGE);
1189 /* Disable caches (CD = 1, NW = 0). */
1191 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1193 /* Flushes caches and TLBs. */
1197 /* Update PAT and index table. */
1198 wrmsr(MSR_PAT, pat_msr);
1199 for (i = 0; i < PAT_INDEX_SIZE; i++)
1200 pat_index[i] = pat_table[i];
1202 /* Flush caches and TLBs again. */
1206 /* Restore caches and PGE. */
1212 * Initialize a vm_page's machine-dependent fields.
1215 pmap_page_init(vm_page_t m)
1218 TAILQ_INIT(&m->md.pv_list);
1219 m->md.pat_mode = PAT_WRITE_BACK;
1223 * Initialize the pmap module.
1224 * Called by vm_init, to initialize any structures that the pmap
1225 * system needs to map virtual memory.
1230 struct pmap_preinit_mapping *ppim;
1233 int error, i, pv_npg;
1236 * Initialize the vm page array entries for the kernel pmap's
1239 for (i = 0; i < nkpt; i++) {
1240 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1241 KASSERT(mpte >= vm_page_array &&
1242 mpte < &vm_page_array[vm_page_array_size],
1243 ("pmap_init: page table page is out of range"));
1244 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1245 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1246 mpte->wire_count = 1;
1251 * If the kernel is running on a virtual machine, then it must assume
1252 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1253 * be prepared for the hypervisor changing the vendor and family that
1254 * are reported by CPUID. Consequently, the workaround for AMD Family
1255 * 10h Erratum 383 is enabled if the processor's feature set does not
1256 * include at least one feature that is only supported by older Intel
1257 * or newer AMD processors.
1259 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1260 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1261 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1263 workaround_erratum383 = 1;
1266 * Are large page mappings enabled?
1268 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1269 if (pg_ps_enabled) {
1270 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1271 ("pmap_init: can't assign to pagesizes[1]"));
1272 pagesizes[1] = NBPDR;
1276 * Initialize the pv chunk list mutex.
1278 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1281 * Initialize the pool of pv list locks.
1283 for (i = 0; i < NPV_LIST_LOCKS; i++)
1284 rw_init(&pv_list_locks[i], "pmap pv list");
1287 * Calculate the size of the pv head table for superpages.
1289 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1292 * Allocate memory for the pv head table for superpages.
1294 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1296 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1298 for (i = 0; i < pv_npg; i++)
1299 TAILQ_INIT(&pv_table[i].pv_list);
1300 TAILQ_INIT(&pv_dummy.pv_list);
1302 pmap_initialized = 1;
1303 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1304 ppim = pmap_preinit_mapping + i;
1307 /* Make the direct map consistent */
1308 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1309 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1310 ppim->sz, ppim->mode);
1314 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1315 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1318 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1319 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1320 (vmem_addr_t *)&qframe);
1322 panic("qframe allocation failed");
1325 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1326 "2MB page mapping counters");
1328 static u_long pmap_pde_demotions;
1329 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1330 &pmap_pde_demotions, 0, "2MB page demotions");
1332 static u_long pmap_pde_mappings;
1333 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1334 &pmap_pde_mappings, 0, "2MB page mappings");
1336 static u_long pmap_pde_p_failures;
1337 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1338 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1340 static u_long pmap_pde_promotions;
1341 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1342 &pmap_pde_promotions, 0, "2MB page promotions");
1344 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1345 "1GB page mapping counters");
1347 static u_long pmap_pdpe_demotions;
1348 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1349 &pmap_pdpe_demotions, 0, "1GB page demotions");
1351 /***************************************************
1352 * Low level helper routines.....
1353 ***************************************************/
1356 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1358 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1360 switch (pmap->pm_type) {
1363 /* Verify that both PAT bits are not set at the same time */
1364 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1365 ("Invalid PAT bits in entry %#lx", entry));
1367 /* Swap the PAT bits if one of them is set */
1368 if ((entry & x86_pat_bits) != 0)
1369 entry ^= x86_pat_bits;
1373 * Nothing to do - the memory attributes are represented
1374 * the same way for regular pages and superpages.
1378 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1385 * Determine the appropriate bits to set in a PTE or PDE for a specified
1389 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1391 int cache_bits, pat_flag, pat_idx;
1393 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1394 panic("Unknown caching mode %d\n", mode);
1396 switch (pmap->pm_type) {
1399 /* The PAT bit is different for PTE's and PDE's. */
1400 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1402 /* Map the caching mode to a PAT index. */
1403 pat_idx = pat_index[mode];
1405 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1408 cache_bits |= pat_flag;
1410 cache_bits |= PG_NC_PCD;
1412 cache_bits |= PG_NC_PWT;
1416 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1420 panic("unsupported pmap type %d", pmap->pm_type);
1423 return (cache_bits);
1427 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1431 switch (pmap->pm_type) {
1434 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1437 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1440 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1447 pmap_ps_enabled(pmap_t pmap)
1450 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1454 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1457 switch (pmap->pm_type) {
1464 * This is a little bogus since the generation number is
1465 * supposed to be bumped up when a region of the address
1466 * space is invalidated in the page tables.
1468 * In this case the old PDE entry is valid but yet we want
1469 * to make sure that any mappings using the old entry are
1470 * invalidated in the TLB.
1472 * The reason this works as expected is because we rendezvous
1473 * "all" host cpus and force any vcpu context to exit as a
1476 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1479 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1481 pde_store(pde, newpde);
1485 * After changing the page size for the specified virtual address in the page
1486 * table, flush the corresponding entries from the processor's TLB. Only the
1487 * calling processor's TLB is affected.
1489 * The calling thread must be pinned to a processor.
1492 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1496 if (pmap_type_guest(pmap))
1499 KASSERT(pmap->pm_type == PT_X86,
1500 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1502 PG_G = pmap_global_bit(pmap);
1504 if ((newpde & PG_PS) == 0)
1505 /* Demotion: flush a specific 2MB page mapping. */
1507 else if ((newpde & PG_G) == 0)
1509 * Promotion: flush every 4KB page mapping from the TLB
1510 * because there are too many to flush individually.
1515 * Promotion: flush every 4KB page mapping from the TLB,
1516 * including any global (PG_G) mappings.
1524 * For SMP, these functions have to use the IPI mechanism for coherence.
1526 * N.B.: Before calling any of the following TLB invalidation functions,
1527 * the calling processor must ensure that all stores updating a non-
1528 * kernel page table are globally performed. Otherwise, another
1529 * processor could cache an old, pre-update entry without being
1530 * invalidated. This can happen one of two ways: (1) The pmap becomes
1531 * active on another processor after its pm_active field is checked by
1532 * one of the following functions but before a store updating the page
1533 * table is globally performed. (2) The pmap becomes active on another
1534 * processor before its pm_active field is checked but due to
1535 * speculative loads one of the following functions stills reads the
1536 * pmap as inactive on the other processor.
1538 * The kernel page table is exempt because its pm_active field is
1539 * immutable. The kernel page table is always active on every
1544 * Interrupt the cpus that are executing in the guest context.
1545 * This will force the vcpu to exit and the cached EPT mappings
1546 * will be invalidated by the host before the next vmresume.
1548 static __inline void
1549 pmap_invalidate_ept(pmap_t pmap)
1554 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1555 ("pmap_invalidate_ept: absurd pm_active"));
1558 * The TLB mappings associated with a vcpu context are not
1559 * flushed each time a different vcpu is chosen to execute.
1561 * This is in contrast with a process's vtop mappings that
1562 * are flushed from the TLB on each context switch.
1564 * Therefore we need to do more than just a TLB shootdown on
1565 * the active cpus in 'pmap->pm_active'. To do this we keep
1566 * track of the number of invalidations performed on this pmap.
1568 * Each vcpu keeps a cache of this counter and compares it
1569 * just before a vmresume. If the counter is out-of-date an
1570 * invept will be done to flush stale mappings from the TLB.
1572 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1575 * Force the vcpu to exit and trap back into the hypervisor.
1577 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1578 ipi_selected(pmap->pm_active, ipinum);
1583 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1586 struct invpcid_descr d;
1587 uint64_t kcr3, ucr3;
1591 if (pmap_type_guest(pmap)) {
1592 pmap_invalidate_ept(pmap);
1596 KASSERT(pmap->pm_type == PT_X86,
1597 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1600 if (pmap == kernel_pmap) {
1604 cpuid = PCPU_GET(cpuid);
1605 if (pmap == PCPU_GET(curpmap)) {
1607 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1609 * Disable context switching. pm_pcid
1610 * is recalculated on switch, which
1611 * might make us use wrong pcid below.
1614 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1616 if (invpcid_works) {
1617 d.pcid = pcid | PMAP_PCID_USER_PT;
1620 invpcid(&d, INVPCID_ADDR);
1622 kcr3 = pmap->pm_cr3 | pcid |
1624 ucr3 = pmap->pm_ucr3 | pcid |
1625 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1626 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1630 } else if (pmap_pcid_enabled)
1631 pmap->pm_pcids[cpuid].pm_gen = 0;
1632 if (pmap_pcid_enabled) {
1635 pmap->pm_pcids[i].pm_gen = 0;
1638 mask = &pmap->pm_active;
1640 smp_masked_invlpg(*mask, va, pmap);
1644 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1645 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1648 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1651 struct invpcid_descr d;
1653 uint64_t kcr3, ucr3;
1657 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1658 pmap_invalidate_all(pmap);
1662 if (pmap_type_guest(pmap)) {
1663 pmap_invalidate_ept(pmap);
1667 KASSERT(pmap->pm_type == PT_X86,
1668 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1671 cpuid = PCPU_GET(cpuid);
1672 if (pmap == kernel_pmap) {
1673 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1677 if (pmap == PCPU_GET(curpmap)) {
1678 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1680 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1682 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1683 if (invpcid_works) {
1684 d.pcid = pcid | PMAP_PCID_USER_PT;
1687 for (; d.addr < eva; d.addr +=
1689 invpcid(&d, INVPCID_ADDR);
1691 kcr3 = pmap->pm_cr3 | pcid |
1693 ucr3 = pmap->pm_ucr3 | pcid |
1694 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1695 pmap_pti_pcid_invlrng(ucr3, kcr3, sva,
1700 } else if (pmap_pcid_enabled) {
1701 pmap->pm_pcids[cpuid].pm_gen = 0;
1703 if (pmap_pcid_enabled) {
1706 pmap->pm_pcids[i].pm_gen = 0;
1709 mask = &pmap->pm_active;
1711 smp_masked_invlpg_range(*mask, sva, eva, pmap);
1716 pmap_invalidate_all(pmap_t pmap)
1719 struct invpcid_descr d;
1720 uint64_t kcr3, ucr3;
1724 if (pmap_type_guest(pmap)) {
1725 pmap_invalidate_ept(pmap);
1729 KASSERT(pmap->pm_type == PT_X86,
1730 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1733 if (pmap == kernel_pmap) {
1734 if (pmap_pcid_enabled && invpcid_works) {
1735 bzero(&d, sizeof(d));
1736 invpcid(&d, INVPCID_CTXGLOB);
1742 cpuid = PCPU_GET(cpuid);
1743 if (pmap == PCPU_GET(curpmap)) {
1744 if (pmap_pcid_enabled) {
1746 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1747 if (invpcid_works) {
1751 invpcid(&d, INVPCID_CTX);
1752 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1753 d.pcid |= PMAP_PCID_USER_PT;
1754 invpcid(&d, INVPCID_CTX);
1757 kcr3 = pmap->pm_cr3 | pcid;
1758 ucr3 = pmap->pm_ucr3;
1759 if (ucr3 != PMAP_NO_CR3) {
1760 ucr3 |= pcid | PMAP_PCID_USER_PT;
1761 pmap_pti_pcid_invalidate(ucr3,
1771 } else if (pmap_pcid_enabled) {
1772 pmap->pm_pcids[cpuid].pm_gen = 0;
1774 if (pmap_pcid_enabled) {
1777 pmap->pm_pcids[i].pm_gen = 0;
1780 mask = &pmap->pm_active;
1782 smp_masked_invltlb(*mask, pmap);
1787 pmap_invalidate_cache(void)
1797 cpuset_t invalidate; /* processors that invalidate their TLB */
1802 u_int store; /* processor that updates the PDE */
1806 pmap_update_pde_action(void *arg)
1808 struct pde_action *act = arg;
1810 if (act->store == PCPU_GET(cpuid))
1811 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1815 pmap_update_pde_teardown(void *arg)
1817 struct pde_action *act = arg;
1819 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1820 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1824 * Change the page size for the specified virtual address in a way that
1825 * prevents any possibility of the TLB ever having two entries that map the
1826 * same virtual address using different page sizes. This is the recommended
1827 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1828 * machine check exception for a TLB state that is improperly diagnosed as a
1832 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1834 struct pde_action act;
1835 cpuset_t active, other_cpus;
1839 cpuid = PCPU_GET(cpuid);
1840 other_cpus = all_cpus;
1841 CPU_CLR(cpuid, &other_cpus);
1842 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1845 active = pmap->pm_active;
1847 if (CPU_OVERLAP(&active, &other_cpus)) {
1849 act.invalidate = active;
1853 act.newpde = newpde;
1854 CPU_SET(cpuid, &active);
1855 smp_rendezvous_cpus(active,
1856 smp_no_rendezvous_barrier, pmap_update_pde_action,
1857 pmap_update_pde_teardown, &act);
1859 pmap_update_pde_store(pmap, pde, newpde);
1860 if (CPU_ISSET(cpuid, &active))
1861 pmap_update_pde_invalidate(pmap, va, newpde);
1867 * Normal, non-SMP, invalidation functions.
1870 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1872 struct invpcid_descr d;
1873 uint64_t kcr3, ucr3;
1876 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1880 KASSERT(pmap->pm_type == PT_X86,
1881 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1883 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1885 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
1886 pmap->pm_ucr3 != PMAP_NO_CR3) {
1888 pcid = pmap->pm_pcids[0].pm_pcid;
1889 if (invpcid_works) {
1890 d.pcid = pcid | PMAP_PCID_USER_PT;
1893 invpcid(&d, INVPCID_ADDR);
1895 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
1896 ucr3 = pmap->pm_ucr3 | pcid |
1897 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1898 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1902 } else if (pmap_pcid_enabled)
1903 pmap->pm_pcids[0].pm_gen = 0;
1907 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1909 struct invpcid_descr d;
1911 uint64_t kcr3, ucr3;
1913 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1917 KASSERT(pmap->pm_type == PT_X86,
1918 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1920 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1921 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1923 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
1924 pmap->pm_ucr3 != PMAP_NO_CR3) {
1926 if (invpcid_works) {
1927 d.pcid = pmap->pm_pcids[0].pm_pcid |
1931 for (; d.addr < eva; d.addr += PAGE_SIZE)
1932 invpcid(&d, INVPCID_ADDR);
1934 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].
1935 pm_pcid | CR3_PCID_SAVE;
1936 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[0].
1937 pm_pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1938 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
1942 } else if (pmap_pcid_enabled) {
1943 pmap->pm_pcids[0].pm_gen = 0;
1948 pmap_invalidate_all(pmap_t pmap)
1950 struct invpcid_descr d;
1951 uint64_t kcr3, ucr3;
1953 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1957 KASSERT(pmap->pm_type == PT_X86,
1958 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
1960 if (pmap == kernel_pmap) {
1961 if (pmap_pcid_enabled && invpcid_works) {
1962 bzero(&d, sizeof(d));
1963 invpcid(&d, INVPCID_CTXGLOB);
1967 } else if (pmap == PCPU_GET(curpmap)) {
1968 if (pmap_pcid_enabled) {
1970 if (invpcid_works) {
1971 d.pcid = pmap->pm_pcids[0].pm_pcid;
1974 invpcid(&d, INVPCID_CTX);
1975 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1976 d.pcid |= PMAP_PCID_USER_PT;
1977 invpcid(&d, INVPCID_CTX);
1980 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].pm_pcid;
1981 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1982 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[
1983 0].pm_pcid | PMAP_PCID_USER_PT;
1984 pmap_pti_pcid_invalidate(ucr3, kcr3);
1992 } else if (pmap_pcid_enabled) {
1993 pmap->pm_pcids[0].pm_gen = 0;
1998 pmap_invalidate_cache(void)
2005 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
2008 pmap_update_pde_store(pmap, pde, newpde);
2009 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
2010 pmap_update_pde_invalidate(pmap, va, newpde);
2012 pmap->pm_pcids[0].pm_gen = 0;
2017 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
2021 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
2022 * by a promotion that did not invalidate the 512 4KB page mappings
2023 * that might exist in the TLB. Consequently, at this point, the TLB
2024 * may hold both 4KB and 2MB page mappings for the address range [va,
2025 * va + NBPDR). Therefore, the entire range must be invalidated here.
2026 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
2027 * 4KB page mappings for the address range [va, va + NBPDR), and so a
2028 * single INVLPG suffices to invalidate the 2MB page mapping from the
2031 if ((pde & PG_PROMOTED) != 0)
2032 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
2034 pmap_invalidate_page(pmap, va);
2037 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
2040 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
2044 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
2046 KASSERT((sva & PAGE_MASK) == 0,
2047 ("pmap_invalidate_cache_range: sva not page-aligned"));
2048 KASSERT((eva & PAGE_MASK) == 0,
2049 ("pmap_invalidate_cache_range: eva not page-aligned"));
2052 if ((cpu_feature & CPUID_SS) != 0 && !force)
2053 ; /* If "Self Snoop" is supported and allowed, do nothing. */
2054 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
2055 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2057 * XXX: Some CPUs fault, hang, or trash the local APIC
2058 * registers if we use CLFLUSH on the local APIC
2059 * range. The local APIC is always uncached, so we
2060 * don't need to flush for that range anyway.
2062 if (pmap_kextract(sva) == lapic_paddr)
2066 * Otherwise, do per-cache line flush. Use the sfence
2067 * instruction to insure that previous stores are
2068 * included in the write-back. The processor
2069 * propagates flush to other processors in the cache
2073 for (; sva < eva; sva += cpu_clflush_line_size)
2076 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
2077 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2078 if (pmap_kextract(sva) == lapic_paddr)
2081 * Writes are ordered by CLFLUSH on Intel CPUs.
2083 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2085 for (; sva < eva; sva += cpu_clflush_line_size)
2087 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2092 * No targeted cache flush methods are supported by CPU,
2093 * or the supplied range is bigger than 2MB.
2094 * Globally invalidate cache.
2096 pmap_invalidate_cache();
2101 * Remove the specified set of pages from the data and instruction caches.
2103 * In contrast to pmap_invalidate_cache_range(), this function does not
2104 * rely on the CPU's self-snoop feature, because it is intended for use
2105 * when moving pages into a different cache domain.
2108 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
2110 vm_offset_t daddr, eva;
2114 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
2115 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
2116 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
2117 pmap_invalidate_cache();
2121 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2123 for (i = 0; i < count; i++) {
2124 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
2125 eva = daddr + PAGE_SIZE;
2126 for (; daddr < eva; daddr += cpu_clflush_line_size) {
2135 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2141 * Routine: pmap_extract
2143 * Extract the physical page address associated
2144 * with the given map/virtual_address pair.
2147 pmap_extract(pmap_t pmap, vm_offset_t va)
2151 pt_entry_t *pte, PG_V;
2155 PG_V = pmap_valid_bit(pmap);
2157 pdpe = pmap_pdpe(pmap, va);
2158 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2159 if ((*pdpe & PG_PS) != 0)
2160 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
2162 pde = pmap_pdpe_to_pde(pdpe, va);
2163 if ((*pde & PG_V) != 0) {
2164 if ((*pde & PG_PS) != 0) {
2165 pa = (*pde & PG_PS_FRAME) |
2168 pte = pmap_pde_to_pte(pde, va);
2169 pa = (*pte & PG_FRAME) |
2180 * Routine: pmap_extract_and_hold
2182 * Atomically extract and hold the physical page
2183 * with the given pmap and virtual address pair
2184 * if that mapping permits the given protection.
2187 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
2189 pd_entry_t pde, *pdep;
2190 pt_entry_t pte, PG_RW, PG_V;
2196 PG_RW = pmap_rw_bit(pmap);
2197 PG_V = pmap_valid_bit(pmap);
2200 pdep = pmap_pde(pmap, va);
2201 if (pdep != NULL && (pde = *pdep)) {
2203 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2204 if (vm_page_pa_tryrelock(pmap, (pde &
2205 PG_PS_FRAME) | (va & PDRMASK), &pa))
2207 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
2212 pte = *pmap_pde_to_pte(pdep, va);
2214 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2215 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2218 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
2229 pmap_kextract(vm_offset_t va)
2234 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2235 pa = DMAP_TO_PHYS(va);
2239 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2242 * Beware of a concurrent promotion that changes the
2243 * PDE at this point! For example, vtopte() must not
2244 * be used to access the PTE because it would use the
2245 * new PDE. It is, however, safe to use the old PDE
2246 * because the page table page is preserved by the
2249 pa = *pmap_pde_to_pte(&pde, va);
2250 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2256 /***************************************************
2257 * Low level mapping routines.....
2258 ***************************************************/
2261 * Add a wired page to the kva.
2262 * Note: not SMP coherent.
2265 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2270 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g);
2273 static __inline void
2274 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2280 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2281 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | cache_bits);
2285 * Remove a page from the kernel pagetables.
2286 * Note: not SMP coherent.
2289 pmap_kremove(vm_offset_t va)
2298 * Used to map a range of physical addresses into kernel
2299 * virtual address space.
2301 * The value passed in '*virt' is a suggested virtual address for
2302 * the mapping. Architectures which can support a direct-mapped
2303 * physical to virtual region can return the appropriate address
2304 * within that region, leaving '*virt' unchanged. Other
2305 * architectures should map the pages starting at '*virt' and
2306 * update '*virt' with the first usable address after the mapped
2310 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2312 return PHYS_TO_DMAP(start);
2317 * Add a list of wired pages to the kva
2318 * this routine is only used for temporary
2319 * kernel mappings that do not need to have
2320 * page modification or references recorded.
2321 * Note that old mappings are simply written
2322 * over. The page *must* be wired.
2323 * Note: SMP coherent. Uses a ranged shootdown IPI.
2326 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2328 pt_entry_t *endpte, oldpte, pa, *pte;
2334 endpte = pte + count;
2335 while (pte < endpte) {
2337 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2338 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2339 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2341 pte_store(pte, pa | pg_g | pg_nx | X86_PG_RW | X86_PG_V);
2345 if (__predict_false((oldpte & X86_PG_V) != 0))
2346 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2351 * This routine tears out page mappings from the
2352 * kernel -- it is meant only for temporary mappings.
2353 * Note: SMP coherent. Uses a ranged shootdown IPI.
2356 pmap_qremove(vm_offset_t sva, int count)
2361 while (count-- > 0) {
2362 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2366 pmap_invalidate_range(kernel_pmap, sva, va);
2369 /***************************************************
2370 * Page table page management routines.....
2371 ***************************************************/
2372 static __inline void
2373 pmap_free_zero_pages(struct spglist *free)
2378 for (count = 0; (m = SLIST_FIRST(free)) != NULL; count++) {
2379 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2380 /* Preserve the page's PG_ZERO setting. */
2381 vm_page_free_toq(m);
2387 * Schedule the specified unused page table page to be freed. Specifically,
2388 * add the page to the specified list of pages that will be released to the
2389 * physical memory manager after the TLB has been updated.
2391 static __inline void
2392 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2393 boolean_t set_PG_ZERO)
2397 m->flags |= PG_ZERO;
2399 m->flags &= ~PG_ZERO;
2400 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2404 * Inserts the specified page table page into the specified pmap's collection
2405 * of idle page table pages. Each of a pmap's page table pages is responsible
2406 * for mapping a distinct range of virtual addresses. The pmap's collection is
2407 * ordered by this virtual address range.
2410 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2413 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2414 return (vm_radix_insert(&pmap->pm_root, mpte));
2418 * Removes the page table page mapping the specified virtual address from the
2419 * specified pmap's collection of idle page table pages, and returns it.
2420 * Otherwise, returns NULL if there is no page table page corresponding to the
2421 * specified virtual address.
2423 static __inline vm_page_t
2424 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
2427 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2428 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
2432 * Decrements a page table page's wire count, which is used to record the
2433 * number of valid page table entries within the page. If the wire count
2434 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2435 * page table page was unmapped and FALSE otherwise.
2437 static inline boolean_t
2438 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2442 if (m->wire_count == 0) {
2443 _pmap_unwire_ptp(pmap, va, m, free);
2450 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2453 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2455 * unmap the page table page
2457 if (m->pindex >= (NUPDE + NUPDPE)) {
2460 pml4 = pmap_pml4e(pmap, va);
2462 if (pmap->pm_pml4u != NULL && va <= VM_MAXUSER_ADDRESS) {
2463 pml4 = &pmap->pm_pml4u[pmap_pml4e_index(va)];
2466 } else if (m->pindex >= NUPDE) {
2469 pdp = pmap_pdpe(pmap, va);
2474 pd = pmap_pde(pmap, va);
2477 pmap_resident_count_dec(pmap, 1);
2478 if (m->pindex < NUPDE) {
2479 /* We just released a PT, unhold the matching PD */
2482 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2483 pmap_unwire_ptp(pmap, va, pdpg, free);
2485 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2486 /* We just released a PD, unhold the matching PDP */
2489 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2490 pmap_unwire_ptp(pmap, va, pdppg, free);
2494 * Put page on a list so that it is released after
2495 * *ALL* TLB shootdown is done
2497 pmap_add_delayed_free_list(m, free, TRUE);
2501 * After removing a page table entry, this routine is used to
2502 * conditionally free the page, and manage the hold/wire counts.
2505 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2506 struct spglist *free)
2510 if (va >= VM_MAXUSER_ADDRESS)
2512 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2513 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2514 return (pmap_unwire_ptp(pmap, va, mpte, free));
2518 pmap_pinit0(pmap_t pmap)
2522 PMAP_LOCK_INIT(pmap);
2523 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2524 pmap->pm_pml4u = NULL;
2525 pmap->pm_cr3 = KPML4phys;
2526 /* hack to keep pmap_pti_pcid_invalidate() alive */
2527 pmap->pm_ucr3 = PMAP_NO_CR3;
2528 pmap->pm_root.rt_root = 0;
2529 CPU_ZERO(&pmap->pm_active);
2530 TAILQ_INIT(&pmap->pm_pvchunk);
2531 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2532 pmap->pm_flags = pmap_flags;
2534 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2535 pmap->pm_pcids[i].pm_gen = 0;
2537 __pcpu[i].pc_kcr3 = PMAP_NO_CR3;
2539 PCPU_SET(curpmap, kernel_pmap);
2540 pmap_activate(curthread);
2541 CPU_FILL(&kernel_pmap->pm_active);
2545 pmap_pinit_pml4(vm_page_t pml4pg)
2547 pml4_entry_t *pm_pml4;
2550 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2552 /* Wire in kernel global address entries. */
2553 for (i = 0; i < NKPML4E; i++) {
2554 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2557 for (i = 0; i < ndmpdpphys; i++) {
2558 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2562 /* install self-referential address mapping entry(s) */
2563 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2564 X86_PG_A | X86_PG_M;
2568 pmap_pinit_pml4_pti(vm_page_t pml4pg)
2570 pml4_entry_t *pm_pml4;
2573 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2574 for (i = 0; i < NPML4EPG; i++)
2575 pm_pml4[i] = pti_pml4[i];
2579 * Initialize a preallocated and zeroed pmap structure,
2580 * such as one in a vmspace structure.
2583 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2585 vm_page_t pml4pg, pml4pgu;
2586 vm_paddr_t pml4phys;
2590 * allocate the page directory page
2592 pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
2593 VM_ALLOC_WIRED | VM_ALLOC_ZERO | VM_ALLOC_WAITOK);
2595 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2596 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2598 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2599 pmap->pm_pcids[i].pm_gen = 0;
2601 pmap->pm_cr3 = PMAP_NO_CR3; /* initialize to an invalid value */
2602 pmap->pm_ucr3 = PMAP_NO_CR3;
2603 pmap->pm_pml4u = NULL;
2605 pmap->pm_type = pm_type;
2606 if ((pml4pg->flags & PG_ZERO) == 0)
2607 pagezero(pmap->pm_pml4);
2610 * Do not install the host kernel mappings in the nested page
2611 * tables. These mappings are meaningless in the guest physical
2613 * Install minimal kernel mappings in PTI case.
2615 if (pm_type == PT_X86) {
2616 pmap->pm_cr3 = pml4phys;
2617 pmap_pinit_pml4(pml4pg);
2619 pml4pgu = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2620 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2621 pmap->pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(
2622 VM_PAGE_TO_PHYS(pml4pgu));
2623 pmap_pinit_pml4_pti(pml4pgu);
2624 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pml4pgu);
2628 pmap->pm_root.rt_root = 0;
2629 CPU_ZERO(&pmap->pm_active);
2630 TAILQ_INIT(&pmap->pm_pvchunk);
2631 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2632 pmap->pm_flags = flags;
2633 pmap->pm_eptgen = 0;
2639 pmap_pinit(pmap_t pmap)
2642 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2646 * This routine is called if the desired page table page does not exist.
2648 * If page table page allocation fails, this routine may sleep before
2649 * returning NULL. It sleeps only if a lock pointer was given.
2651 * Note: If a page allocation fails at page table level two or three,
2652 * one or two pages may be held during the wait, only to be released
2653 * afterwards. This conservative approach is easily argued to avoid
2657 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2659 vm_page_t m, pdppg, pdpg;
2660 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2662 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2664 PG_A = pmap_accessed_bit(pmap);
2665 PG_M = pmap_modified_bit(pmap);
2666 PG_V = pmap_valid_bit(pmap);
2667 PG_RW = pmap_rw_bit(pmap);
2670 * Allocate a page table page.
2672 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2673 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2674 if (lockp != NULL) {
2675 RELEASE_PV_LIST_LOCK(lockp);
2677 PMAP_ASSERT_NOT_IN_DI();
2683 * Indicate the need to retry. While waiting, the page table
2684 * page may have been allocated.
2688 if ((m->flags & PG_ZERO) == 0)
2692 * Map the pagetable page into the process address space, if
2693 * it isn't already there.
2696 if (ptepindex >= (NUPDE + NUPDPE)) {
2697 pml4_entry_t *pml4, *pml4u;
2698 vm_pindex_t pml4index;
2700 /* Wire up a new PDPE page */
2701 pml4index = ptepindex - (NUPDE + NUPDPE);
2702 pml4 = &pmap->pm_pml4[pml4index];
2703 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2704 if (pmap->pm_pml4u != NULL && pml4index < NUPML4E) {
2706 * PTI: Make all user-space mappings in the
2707 * kernel-mode page table no-execute so that
2708 * we detect any programming errors that leave
2709 * the kernel-mode page table active on return
2714 pml4u = &pmap->pm_pml4u[pml4index];
2715 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
2719 } else if (ptepindex >= NUPDE) {
2720 vm_pindex_t pml4index;
2721 vm_pindex_t pdpindex;
2725 /* Wire up a new PDE page */
2726 pdpindex = ptepindex - NUPDE;
2727 pml4index = pdpindex >> NPML4EPGSHIFT;
2729 pml4 = &pmap->pm_pml4[pml4index];
2730 if ((*pml4 & PG_V) == 0) {
2731 /* Have to allocate a new pdp, recurse */
2732 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2734 vm_page_unwire_noq(m);
2735 vm_page_free_zero(m);
2739 /* Add reference to pdp page */
2740 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2741 pdppg->wire_count++;
2743 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2745 /* Now find the pdp page */
2746 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2747 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2750 vm_pindex_t pml4index;
2751 vm_pindex_t pdpindex;
2756 /* Wire up a new PTE page */
2757 pdpindex = ptepindex >> NPDPEPGSHIFT;
2758 pml4index = pdpindex >> NPML4EPGSHIFT;
2760 /* First, find the pdp and check that its valid. */
2761 pml4 = &pmap->pm_pml4[pml4index];
2762 if ((*pml4 & PG_V) == 0) {
2763 /* Have to allocate a new pd, recurse */
2764 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2766 vm_page_unwire_noq(m);
2767 vm_page_free_zero(m);
2770 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2771 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2773 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2774 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2775 if ((*pdp & PG_V) == 0) {
2776 /* Have to allocate a new pd, recurse */
2777 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2779 vm_page_unwire_noq(m);
2780 vm_page_free_zero(m);
2784 /* Add reference to the pd page */
2785 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2789 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2791 /* Now we know where the page directory page is */
2792 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2793 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2796 pmap_resident_count_inc(pmap, 1);
2802 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2804 vm_pindex_t pdpindex, ptepindex;
2805 pdp_entry_t *pdpe, PG_V;
2808 PG_V = pmap_valid_bit(pmap);
2811 pdpe = pmap_pdpe(pmap, va);
2812 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2813 /* Add a reference to the pd page. */
2814 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2817 /* Allocate a pd page. */
2818 ptepindex = pmap_pde_pindex(va);
2819 pdpindex = ptepindex >> NPDPEPGSHIFT;
2820 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2821 if (pdpg == NULL && lockp != NULL)
2828 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2830 vm_pindex_t ptepindex;
2831 pd_entry_t *pd, PG_V;
2834 PG_V = pmap_valid_bit(pmap);
2837 * Calculate pagetable page index
2839 ptepindex = pmap_pde_pindex(va);
2842 * Get the page directory entry
2844 pd = pmap_pde(pmap, va);
2847 * This supports switching from a 2MB page to a
2850 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2851 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2853 * Invalidation of the 2MB page mapping may have caused
2854 * the deallocation of the underlying PD page.
2861 * If the page table page is mapped, we just increment the
2862 * hold count, and activate it.
2864 if (pd != NULL && (*pd & PG_V) != 0) {
2865 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2869 * Here if the pte page isn't mapped, or if it has been
2872 m = _pmap_allocpte(pmap, ptepindex, lockp);
2873 if (m == NULL && lockp != NULL)
2880 /***************************************************
2881 * Pmap allocation/deallocation routines.
2882 ***************************************************/
2885 * Release any resources held by the given physical map.
2886 * Called when a pmap initialized by pmap_pinit is being released.
2887 * Should only be called if the map contains no valid mappings.
2890 pmap_release(pmap_t pmap)
2895 KASSERT(pmap->pm_stats.resident_count == 0,
2896 ("pmap_release: pmap resident count %ld != 0",
2897 pmap->pm_stats.resident_count));
2898 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2899 ("pmap_release: pmap has reserved page table page(s)"));
2900 KASSERT(CPU_EMPTY(&pmap->pm_active),
2901 ("releasing active pmap %p", pmap));
2903 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2905 for (i = 0; i < NKPML4E; i++) /* KVA */
2906 pmap->pm_pml4[KPML4BASE + i] = 0;
2907 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
2908 pmap->pm_pml4[DMPML4I + i] = 0;
2909 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
2911 vm_page_unwire_noq(m);
2912 vm_page_free_zero(m);
2914 if (pmap->pm_pml4u != NULL) {
2915 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4u));
2916 vm_page_unwire_noq(m);
2922 kvm_size(SYSCTL_HANDLER_ARGS)
2924 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2926 return sysctl_handle_long(oidp, &ksize, 0, req);
2928 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2929 0, 0, kvm_size, "LU", "Size of KVM");
2932 kvm_free(SYSCTL_HANDLER_ARGS)
2934 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2936 return sysctl_handle_long(oidp, &kfree, 0, req);
2938 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2939 0, 0, kvm_free, "LU", "Amount of KVM free");
2942 * grow the number of kernel page table entries, if needed
2945 pmap_growkernel(vm_offset_t addr)
2949 pd_entry_t *pde, newpdir;
2952 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2955 * Return if "addr" is within the range of kernel page table pages
2956 * that were preallocated during pmap bootstrap. Moreover, leave
2957 * "kernel_vm_end" and the kernel page table as they were.
2959 * The correctness of this action is based on the following
2960 * argument: vm_map_insert() allocates contiguous ranges of the
2961 * kernel virtual address space. It calls this function if a range
2962 * ends after "kernel_vm_end". If the kernel is mapped between
2963 * "kernel_vm_end" and "addr", then the range cannot begin at
2964 * "kernel_vm_end". In fact, its beginning address cannot be less
2965 * than the kernel. Thus, there is no immediate need to allocate
2966 * any new kernel page table pages between "kernel_vm_end" and
2969 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
2972 addr = roundup2(addr, NBPDR);
2973 if (addr - 1 >= kernel_map->max_offset)
2974 addr = kernel_map->max_offset;
2975 while (kernel_vm_end < addr) {
2976 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
2977 if ((*pdpe & X86_PG_V) == 0) {
2978 /* We need a new PDP entry */
2979 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
2980 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
2981 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2983 panic("pmap_growkernel: no memory to grow kernel");
2984 if ((nkpg->flags & PG_ZERO) == 0)
2985 pmap_zero_page(nkpg);
2986 paddr = VM_PAGE_TO_PHYS(nkpg);
2987 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
2988 X86_PG_A | X86_PG_M);
2989 continue; /* try again */
2991 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
2992 if ((*pde & X86_PG_V) != 0) {
2993 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2994 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2995 kernel_vm_end = kernel_map->max_offset;
3001 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
3002 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
3005 panic("pmap_growkernel: no memory to grow kernel");
3006 if ((nkpg->flags & PG_ZERO) == 0)
3007 pmap_zero_page(nkpg);
3008 paddr = VM_PAGE_TO_PHYS(nkpg);
3009 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
3010 pde_store(pde, newpdir);
3012 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3013 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
3014 kernel_vm_end = kernel_map->max_offset;
3021 /***************************************************
3022 * page management routines.
3023 ***************************************************/
3025 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
3026 CTASSERT(_NPCM == 3);
3027 CTASSERT(_NPCPV == 168);
3029 static __inline struct pv_chunk *
3030 pv_to_chunk(pv_entry_t pv)
3033 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
3036 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
3038 #define PC_FREE0 0xfffffffffffffffful
3039 #define PC_FREE1 0xfffffffffffffffful
3040 #define PC_FREE2 0x000000fffffffffful
3042 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
3045 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
3047 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
3048 "Current number of pv entry chunks");
3049 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
3050 "Current number of pv entry chunks allocated");
3051 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
3052 "Current number of pv entry chunks frees");
3053 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
3054 "Number of times tried to get a chunk page but failed.");
3056 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
3057 static int pv_entry_spare;
3059 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
3060 "Current number of pv entry frees");
3061 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
3062 "Current number of pv entry allocs");
3063 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
3064 "Current number of pv entries");
3065 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
3066 "Current number of spare pv entries");
3070 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
3075 pmap_invalidate_all(pmap);
3076 if (pmap != locked_pmap)
3079 pmap_delayed_invl_finished();
3083 * We are in a serious low memory condition. Resort to
3084 * drastic measures to free some pages so we can allocate
3085 * another pv entry chunk.
3087 * Returns NULL if PV entries were reclaimed from the specified pmap.
3089 * We do not, however, unmap 2mpages because subsequent accesses will
3090 * allocate per-page pv entries until repromotion occurs, thereby
3091 * exacerbating the shortage of free pv entries.
3094 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
3096 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
3097 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
3098 struct md_page *pvh;
3100 pmap_t next_pmap, pmap;
3101 pt_entry_t *pte, tpte;
3102 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3106 struct spglist free;
3108 int bit, field, freed;
3110 static int active_reclaims = 0;
3112 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
3113 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
3116 PG_G = PG_A = PG_M = PG_RW = 0;
3118 bzero(&pc_marker_b, sizeof(pc_marker_b));
3119 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
3120 pc_marker = (struct pv_chunk *)&pc_marker_b;
3121 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
3124 * A delayed invalidation block should already be active if
3125 * pmap_advise() or pmap_remove() called this function by way
3126 * of pmap_demote_pde_locked().
3128 start_di = pmap_not_in_di();
3130 mtx_lock(&pv_chunks_mutex);
3132 TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
3133 TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
3134 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
3135 SLIST_EMPTY(&free)) {
3136 next_pmap = pc->pc_pmap;
3137 if (next_pmap == NULL) {
3139 * The next chunk is a marker. However, it is
3140 * not our marker, so active_reclaims must be
3141 * > 1. Consequently, the next_chunk code
3142 * will not rotate the pv_chunks list.
3146 mtx_unlock(&pv_chunks_mutex);
3149 * A pv_chunk can only be removed from the pc_lru list
3150 * when both pc_chunks_mutex is owned and the
3151 * corresponding pmap is locked.
3153 if (pmap != next_pmap) {
3154 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
3157 /* Avoid deadlock and lock recursion. */
3158 if (pmap > locked_pmap) {
3159 RELEASE_PV_LIST_LOCK(lockp);
3162 pmap_delayed_invl_started();
3163 mtx_lock(&pv_chunks_mutex);
3165 } else if (pmap != locked_pmap) {
3166 if (PMAP_TRYLOCK(pmap)) {
3168 pmap_delayed_invl_started();
3169 mtx_lock(&pv_chunks_mutex);
3172 pmap = NULL; /* pmap is not locked */
3173 mtx_lock(&pv_chunks_mutex);
3174 pc = TAILQ_NEXT(pc_marker, pc_lru);
3176 pc->pc_pmap != next_pmap)
3180 } else if (start_di)
3181 pmap_delayed_invl_started();
3182 PG_G = pmap_global_bit(pmap);
3183 PG_A = pmap_accessed_bit(pmap);
3184 PG_M = pmap_modified_bit(pmap);
3185 PG_RW = pmap_rw_bit(pmap);
3189 * Destroy every non-wired, 4 KB page mapping in the chunk.
3192 for (field = 0; field < _NPCM; field++) {
3193 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
3194 inuse != 0; inuse &= ~(1UL << bit)) {
3196 pv = &pc->pc_pventry[field * 64 + bit];
3198 pde = pmap_pde(pmap, va);
3199 if ((*pde & PG_PS) != 0)
3201 pte = pmap_pde_to_pte(pde, va);
3202 if ((*pte & PG_W) != 0)
3204 tpte = pte_load_clear(pte);
3205 if ((tpte & PG_G) != 0)
3206 pmap_invalidate_page(pmap, va);
3207 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3208 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3210 if ((tpte & PG_A) != 0)
3211 vm_page_aflag_set(m, PGA_REFERENCED);
3212 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3213 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3215 if (TAILQ_EMPTY(&m->md.pv_list) &&
3216 (m->flags & PG_FICTITIOUS) == 0) {
3217 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3218 if (TAILQ_EMPTY(&pvh->pv_list)) {
3219 vm_page_aflag_clear(m,
3223 pmap_delayed_invl_page(m);
3224 pc->pc_map[field] |= 1UL << bit;
3225 pmap_unuse_pt(pmap, va, *pde, &free);
3230 mtx_lock(&pv_chunks_mutex);
3233 /* Every freed mapping is for a 4 KB page. */
3234 pmap_resident_count_dec(pmap, freed);
3235 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
3236 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
3237 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
3238 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3239 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
3240 pc->pc_map[2] == PC_FREE2) {
3241 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3242 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3243 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3244 /* Entire chunk is free; return it. */
3245 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3246 dump_drop_page(m_pc->phys_addr);
3247 mtx_lock(&pv_chunks_mutex);
3248 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3251 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3252 mtx_lock(&pv_chunks_mutex);
3253 /* One freed pv entry in locked_pmap is sufficient. */
3254 if (pmap == locked_pmap)
3257 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3258 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
3259 if (active_reclaims == 1 && pmap != NULL) {
3261 * Rotate the pv chunks list so that we do not
3262 * scan the same pv chunks that could not be
3263 * freed (because they contained a wired
3264 * and/or superpage mapping) on every
3265 * invocation of reclaim_pv_chunk().
3267 while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
3268 MPASS(pc->pc_pmap != NULL);
3269 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3270 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3274 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3275 TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
3277 mtx_unlock(&pv_chunks_mutex);
3278 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
3279 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
3280 m_pc = SLIST_FIRST(&free);
3281 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3282 /* Recycle a freed page table page. */
3283 m_pc->wire_count = 1;
3285 pmap_free_zero_pages(&free);
3290 * free the pv_entry back to the free list
3293 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3295 struct pv_chunk *pc;
3296 int idx, field, bit;
3298 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3299 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3300 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3301 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3302 pc = pv_to_chunk(pv);
3303 idx = pv - &pc->pc_pventry[0];
3306 pc->pc_map[field] |= 1ul << bit;
3307 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3308 pc->pc_map[2] != PC_FREE2) {
3309 /* 98% of the time, pc is already at the head of the list. */
3310 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3311 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3312 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3316 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3321 free_pv_chunk(struct pv_chunk *pc)
3325 mtx_lock(&pv_chunks_mutex);
3326 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3327 mtx_unlock(&pv_chunks_mutex);
3328 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3329 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3330 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3331 /* entire chunk is free, return it */
3332 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3333 dump_drop_page(m->phys_addr);
3334 vm_page_unwire(m, PQ_NONE);
3339 * Returns a new PV entry, allocating a new PV chunk from the system when
3340 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3341 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3344 * The given PV list lock may be released.
3347 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3351 struct pv_chunk *pc;
3354 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3355 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3357 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3359 for (field = 0; field < _NPCM; field++) {
3360 if (pc->pc_map[field]) {
3361 bit = bsfq(pc->pc_map[field]);
3365 if (field < _NPCM) {
3366 pv = &pc->pc_pventry[field * 64 + bit];
3367 pc->pc_map[field] &= ~(1ul << bit);
3368 /* If this was the last item, move it to tail */
3369 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3370 pc->pc_map[2] == 0) {
3371 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3372 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3375 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3376 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3380 /* No free items, allocate another chunk */
3381 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3384 if (lockp == NULL) {
3385 PV_STAT(pc_chunk_tryfail++);
3388 m = reclaim_pv_chunk(pmap, lockp);
3392 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3393 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3394 dump_add_page(m->phys_addr);
3395 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3397 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3398 pc->pc_map[1] = PC_FREE1;
3399 pc->pc_map[2] = PC_FREE2;
3400 mtx_lock(&pv_chunks_mutex);
3401 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3402 mtx_unlock(&pv_chunks_mutex);
3403 pv = &pc->pc_pventry[0];
3404 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3405 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3406 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3411 * Returns the number of one bits within the given PV chunk map.
3413 * The erratas for Intel processors state that "POPCNT Instruction May
3414 * Take Longer to Execute Than Expected". It is believed that the
3415 * issue is the spurious dependency on the destination register.
3416 * Provide a hint to the register rename logic that the destination
3417 * value is overwritten, by clearing it, as suggested in the
3418 * optimization manual. It should be cheap for unaffected processors
3421 * Reference numbers for erratas are
3422 * 4th Gen Core: HSD146
3423 * 5th Gen Core: BDM85
3424 * 6th Gen Core: SKL029
3427 popcnt_pc_map_pq(uint64_t *map)
3431 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3432 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3433 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3434 : "=&r" (result), "=&r" (tmp)
3435 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3440 * Ensure that the number of spare PV entries in the specified pmap meets or
3441 * exceeds the given count, "needed".
3443 * The given PV list lock may be released.
3446 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3448 struct pch new_tail;
3449 struct pv_chunk *pc;
3453 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3454 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3457 * Newly allocated PV chunks must be stored in a private list until
3458 * the required number of PV chunks have been allocated. Otherwise,
3459 * reclaim_pv_chunk() could recycle one of these chunks. In
3460 * contrast, these chunks must be added to the pmap upon allocation.
3462 TAILQ_INIT(&new_tail);
3465 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3467 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3468 bit_count((bitstr_t *)pc->pc_map, 0,
3469 sizeof(pc->pc_map) * NBBY, &free);
3472 free = popcnt_pc_map_pq(pc->pc_map);
3476 if (avail >= needed)
3479 for (; avail < needed; avail += _NPCPV) {
3480 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3483 m = reclaim_pv_chunk(pmap, lockp);
3487 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3488 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3489 dump_add_page(m->phys_addr);
3490 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3492 pc->pc_map[0] = PC_FREE0;
3493 pc->pc_map[1] = PC_FREE1;
3494 pc->pc_map[2] = PC_FREE2;
3495 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3496 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3497 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3499 if (!TAILQ_EMPTY(&new_tail)) {
3500 mtx_lock(&pv_chunks_mutex);
3501 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3502 mtx_unlock(&pv_chunks_mutex);
3507 * First find and then remove the pv entry for the specified pmap and virtual
3508 * address from the specified pv list. Returns the pv entry if found and NULL
3509 * otherwise. This operation can be performed on pv lists for either 4KB or
3510 * 2MB page mappings.
3512 static __inline pv_entry_t
3513 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3517 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3518 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3519 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3528 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3529 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3530 * entries for each of the 4KB page mappings.
3533 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3534 struct rwlock **lockp)
3536 struct md_page *pvh;
3537 struct pv_chunk *pc;
3539 vm_offset_t va_last;
3543 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3544 KASSERT((pa & PDRMASK) == 0,
3545 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3546 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3549 * Transfer the 2mpage's pv entry for this mapping to the first
3550 * page's pv list. Once this transfer begins, the pv list lock
3551 * must not be released until the last pv entry is reinstantiated.
3553 pvh = pa_to_pvh(pa);
3554 va = trunc_2mpage(va);
3555 pv = pmap_pvh_remove(pvh, pmap, va);
3556 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3557 m = PHYS_TO_VM_PAGE(pa);
3558 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3560 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3561 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3562 va_last = va + NBPDR - PAGE_SIZE;
3564 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3565 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3566 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3567 for (field = 0; field < _NPCM; field++) {
3568 while (pc->pc_map[field]) {
3569 bit = bsfq(pc->pc_map[field]);
3570 pc->pc_map[field] &= ~(1ul << bit);
3571 pv = &pc->pc_pventry[field * 64 + bit];
3575 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3576 ("pmap_pv_demote_pde: page %p is not managed", m));
3577 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3583 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3584 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3587 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3588 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3589 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3591 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3592 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3595 #if VM_NRESERVLEVEL > 0
3597 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3598 * replace the many pv entries for the 4KB page mappings by a single pv entry
3599 * for the 2MB page mapping.
3602 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3603 struct rwlock **lockp)
3605 struct md_page *pvh;
3607 vm_offset_t va_last;
3610 KASSERT((pa & PDRMASK) == 0,
3611 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3612 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3615 * Transfer the first page's pv entry for this mapping to the 2mpage's
3616 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3617 * a transfer avoids the possibility that get_pv_entry() calls
3618 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3619 * mappings that is being promoted.
3621 m = PHYS_TO_VM_PAGE(pa);
3622 va = trunc_2mpage(va);
3623 pv = pmap_pvh_remove(&m->md, pmap, va);
3624 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3625 pvh = pa_to_pvh(pa);
3626 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3628 /* Free the remaining NPTEPG - 1 pv entries. */
3629 va_last = va + NBPDR - PAGE_SIZE;
3633 pmap_pvh_free(&m->md, pmap, va);
3634 } while (va < va_last);
3636 #endif /* VM_NRESERVLEVEL > 0 */
3639 * First find and then destroy the pv entry for the specified pmap and virtual
3640 * address. This operation can be performed on pv lists for either 4KB or 2MB
3644 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3648 pv = pmap_pvh_remove(pvh, pmap, va);
3649 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3650 free_pv_entry(pmap, pv);
3654 * Conditionally create the PV entry for a 4KB page mapping if the required
3655 * memory can be allocated without resorting to reclamation.
3658 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3659 struct rwlock **lockp)
3663 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3664 /* Pass NULL instead of the lock pointer to disable reclamation. */
3665 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3667 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3668 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3676 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3677 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3678 * false if the PV entry cannot be allocated without resorting to reclamation.
3681 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
3682 struct rwlock **lockp)
3684 struct md_page *pvh;
3688 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3689 /* Pass NULL instead of the lock pointer to disable reclamation. */
3690 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3691 NULL : lockp)) == NULL)
3694 pa = pde & PG_PS_FRAME;
3695 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3696 pvh = pa_to_pvh(pa);
3697 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3703 * Fills a page table page with mappings to consecutive physical pages.
3706 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3710 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3712 newpte += PAGE_SIZE;
3717 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3718 * mapping is invalidated.
3721 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3723 struct rwlock *lock;
3727 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3734 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3735 struct rwlock **lockp)
3737 pd_entry_t newpde, oldpde;
3738 pt_entry_t *firstpte, newpte;
3739 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3742 struct spglist free;
3746 PG_G = pmap_global_bit(pmap);
3747 PG_A = pmap_accessed_bit(pmap);
3748 PG_M = pmap_modified_bit(pmap);
3749 PG_RW = pmap_rw_bit(pmap);
3750 PG_V = pmap_valid_bit(pmap);
3751 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3753 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3755 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3756 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3757 if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
3759 KASSERT((oldpde & PG_W) == 0,
3760 ("pmap_demote_pde: page table page for a wired mapping"
3764 * Invalidate the 2MB page mapping and return "failure" if the
3765 * mapping was never accessed or the allocation of the new
3766 * page table page fails. If the 2MB page mapping belongs to
3767 * the direct map region of the kernel's address space, then
3768 * the page allocation request specifies the highest possible
3769 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3770 * normal. Page table pages are preallocated for every other
3771 * part of the kernel address space, so the direct map region
3772 * is the only part of the kernel address space that must be
3775 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3776 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3777 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3778 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3780 sva = trunc_2mpage(va);
3781 pmap_remove_pde(pmap, pde, sva, &free, lockp);
3782 if ((oldpde & PG_G) == 0)
3783 pmap_invalidate_pde_page(pmap, sva, oldpde);
3784 pmap_free_zero_pages(&free);
3785 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3786 " in pmap %p", va, pmap);
3789 if (va < VM_MAXUSER_ADDRESS)
3790 pmap_resident_count_inc(pmap, 1);
3792 mptepa = VM_PAGE_TO_PHYS(mpte);
3793 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3794 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3795 KASSERT((oldpde & PG_A) != 0,
3796 ("pmap_demote_pde: oldpde is missing PG_A"));
3797 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3798 ("pmap_demote_pde: oldpde is missing PG_M"));
3799 newpte = oldpde & ~PG_PS;
3800 newpte = pmap_swap_pat(pmap, newpte);
3803 * If the page table page is new, initialize it.
3805 if (mpte->wire_count == 1) {
3806 mpte->wire_count = NPTEPG;
3807 pmap_fill_ptp(firstpte, newpte);
3809 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3810 ("pmap_demote_pde: firstpte and newpte map different physical"
3814 * If the mapping has changed attributes, update the page table
3817 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3818 pmap_fill_ptp(firstpte, newpte);
3821 * The spare PV entries must be reserved prior to demoting the
3822 * mapping, that is, prior to changing the PDE. Otherwise, the state
3823 * of the PDE and the PV lists will be inconsistent, which can result
3824 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3825 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3826 * PV entry for the 2MB page mapping that is being demoted.
3828 if ((oldpde & PG_MANAGED) != 0)
3829 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3832 * Demote the mapping. This pmap is locked. The old PDE has
3833 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3834 * set. Thus, there is no danger of a race with another
3835 * processor changing the setting of PG_A and/or PG_M between
3836 * the read above and the store below.
3838 if (workaround_erratum383)
3839 pmap_update_pde(pmap, va, pde, newpde);
3841 pde_store(pde, newpde);
3844 * Invalidate a stale recursive mapping of the page table page.
3846 if (va >= VM_MAXUSER_ADDRESS)
3847 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3850 * Demote the PV entry.
3852 if ((oldpde & PG_MANAGED) != 0)
3853 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3855 atomic_add_long(&pmap_pde_demotions, 1);
3856 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3857 " in pmap %p", va, pmap);
3862 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3865 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3871 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3872 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3873 mpte = pmap_remove_pt_page(pmap, va);
3875 panic("pmap_remove_kernel_pde: Missing pt page.");
3877 mptepa = VM_PAGE_TO_PHYS(mpte);
3878 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3881 * Initialize the page table page.
3883 pagezero((void *)PHYS_TO_DMAP(mptepa));
3886 * Demote the mapping.
3888 if (workaround_erratum383)
3889 pmap_update_pde(pmap, va, pde, newpde);
3891 pde_store(pde, newpde);
3894 * Invalidate a stale recursive mapping of the page table page.
3896 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3900 * pmap_remove_pde: do the things to unmap a superpage in a process
3903 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
3904 struct spglist *free, struct rwlock **lockp)
3906 struct md_page *pvh;
3908 vm_offset_t eva, va;
3910 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3912 PG_G = pmap_global_bit(pmap);
3913 PG_A = pmap_accessed_bit(pmap);
3914 PG_M = pmap_modified_bit(pmap);
3915 PG_RW = pmap_rw_bit(pmap);
3917 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3918 KASSERT((sva & PDRMASK) == 0,
3919 ("pmap_remove_pde: sva is not 2mpage aligned"));
3920 oldpde = pte_load_clear(pdq);
3922 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
3923 if ((oldpde & PG_G) != 0)
3924 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
3925 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
3926 if (oldpde & PG_MANAGED) {
3927 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
3928 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
3929 pmap_pvh_free(pvh, pmap, sva);
3931 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3932 va < eva; va += PAGE_SIZE, m++) {
3933 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3936 vm_page_aflag_set(m, PGA_REFERENCED);
3937 if (TAILQ_EMPTY(&m->md.pv_list) &&
3938 TAILQ_EMPTY(&pvh->pv_list))
3939 vm_page_aflag_clear(m, PGA_WRITEABLE);
3940 pmap_delayed_invl_page(m);
3943 if (pmap == kernel_pmap) {
3944 pmap_remove_kernel_pde(pmap, pdq, sva);
3946 mpte = pmap_remove_pt_page(pmap, sva);
3948 pmap_resident_count_dec(pmap, 1);
3949 KASSERT(mpte->wire_count == NPTEPG,
3950 ("pmap_remove_pde: pte page wire count error"));
3951 mpte->wire_count = 0;
3952 pmap_add_delayed_free_list(mpte, free, FALSE);
3955 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
3959 * pmap_remove_pte: do the things to unmap a page in a process
3962 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
3963 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
3965 struct md_page *pvh;
3966 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
3969 PG_A = pmap_accessed_bit(pmap);
3970 PG_M = pmap_modified_bit(pmap);
3971 PG_RW = pmap_rw_bit(pmap);
3973 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3974 oldpte = pte_load_clear(ptq);
3976 pmap->pm_stats.wired_count -= 1;
3977 pmap_resident_count_dec(pmap, 1);
3978 if (oldpte & PG_MANAGED) {
3979 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
3980 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3983 vm_page_aflag_set(m, PGA_REFERENCED);
3984 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3985 pmap_pvh_free(&m->md, pmap, va);
3986 if (TAILQ_EMPTY(&m->md.pv_list) &&
3987 (m->flags & PG_FICTITIOUS) == 0) {
3988 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3989 if (TAILQ_EMPTY(&pvh->pv_list))
3990 vm_page_aflag_clear(m, PGA_WRITEABLE);
3992 pmap_delayed_invl_page(m);
3994 return (pmap_unuse_pt(pmap, va, ptepde, free));
3998 * Remove a single page from a process address space
4001 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
4002 struct spglist *free)
4004 struct rwlock *lock;
4005 pt_entry_t *pte, PG_V;
4007 PG_V = pmap_valid_bit(pmap);
4008 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4009 if ((*pde & PG_V) == 0)
4011 pte = pmap_pde_to_pte(pde, va);
4012 if ((*pte & PG_V) == 0)
4015 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
4018 pmap_invalidate_page(pmap, va);
4022 * Removes the specified range of addresses from the page table page.
4025 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
4026 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
4028 pt_entry_t PG_G, *pte;
4032 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4033 PG_G = pmap_global_bit(pmap);
4036 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
4040 pmap_invalidate_range(pmap, va, sva);
4045 if ((*pte & PG_G) == 0)
4049 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
4055 pmap_invalidate_range(pmap, va, sva);
4060 * Remove the given range of addresses from the specified map.
4062 * It is assumed that the start and end are properly
4063 * rounded to the page size.
4066 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4068 struct rwlock *lock;
4069 vm_offset_t va_next;
4070 pml4_entry_t *pml4e;
4072 pd_entry_t ptpaddr, *pde;
4073 pt_entry_t PG_G, PG_V;
4074 struct spglist free;
4077 PG_G = pmap_global_bit(pmap);
4078 PG_V = pmap_valid_bit(pmap);
4081 * Perform an unsynchronized read. This is, however, safe.
4083 if (pmap->pm_stats.resident_count == 0)
4089 pmap_delayed_invl_started();
4093 * special handling of removing one page. a very
4094 * common operation and easy to short circuit some
4097 if (sva + PAGE_SIZE == eva) {
4098 pde = pmap_pde(pmap, sva);
4099 if (pde && (*pde & PG_PS) == 0) {
4100 pmap_remove_page(pmap, sva, pde, &free);
4106 for (; sva < eva; sva = va_next) {
4108 if (pmap->pm_stats.resident_count == 0)
4111 pml4e = pmap_pml4e(pmap, sva);
4112 if ((*pml4e & PG_V) == 0) {
4113 va_next = (sva + NBPML4) & ~PML4MASK;
4119 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4120 if ((*pdpe & PG_V) == 0) {
4121 va_next = (sva + NBPDP) & ~PDPMASK;
4128 * Calculate index for next page table.
4130 va_next = (sva + NBPDR) & ~PDRMASK;
4134 pde = pmap_pdpe_to_pde(pdpe, sva);
4138 * Weed out invalid mappings.
4144 * Check for large page.
4146 if ((ptpaddr & PG_PS) != 0) {
4148 * Are we removing the entire large page? If not,
4149 * demote the mapping and fall through.
4151 if (sva + NBPDR == va_next && eva >= va_next) {
4153 * The TLB entry for a PG_G mapping is
4154 * invalidated by pmap_remove_pde().
4156 if ((ptpaddr & PG_G) == 0)
4158 pmap_remove_pde(pmap, pde, sva, &free, &lock);
4160 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
4162 /* The large page mapping was destroyed. */
4169 * Limit our scan to either the end of the va represented
4170 * by the current page table page, or to the end of the
4171 * range being removed.
4176 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
4183 pmap_invalidate_all(pmap);
4185 pmap_delayed_invl_finished();
4186 pmap_free_zero_pages(&free);
4190 * Routine: pmap_remove_all
4192 * Removes this physical page from
4193 * all physical maps in which it resides.
4194 * Reflects back modify bits to the pager.
4197 * Original versions of this routine were very
4198 * inefficient because they iteratively called
4199 * pmap_remove (slow...)
4203 pmap_remove_all(vm_page_t m)
4205 struct md_page *pvh;
4208 struct rwlock *lock;
4209 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
4212 struct spglist free;
4213 int pvh_gen, md_gen;
4215 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4216 ("pmap_remove_all: page %p is not managed", m));
4218 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4219 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
4220 pa_to_pvh(VM_PAGE_TO_PHYS(m));
4223 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
4225 if (!PMAP_TRYLOCK(pmap)) {
4226 pvh_gen = pvh->pv_gen;
4230 if (pvh_gen != pvh->pv_gen) {
4237 pde = pmap_pde(pmap, va);
4238 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
4241 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4243 if (!PMAP_TRYLOCK(pmap)) {
4244 pvh_gen = pvh->pv_gen;
4245 md_gen = m->md.pv_gen;
4249 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
4255 PG_A = pmap_accessed_bit(pmap);
4256 PG_M = pmap_modified_bit(pmap);
4257 PG_RW = pmap_rw_bit(pmap);
4258 pmap_resident_count_dec(pmap, 1);
4259 pde = pmap_pde(pmap, pv->pv_va);
4260 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
4261 " a 2mpage in page %p's pv list", m));
4262 pte = pmap_pde_to_pte(pde, pv->pv_va);
4263 tpte = pte_load_clear(pte);
4265 pmap->pm_stats.wired_count--;
4267 vm_page_aflag_set(m, PGA_REFERENCED);
4270 * Update the vm_page_t clean and reference bits.
4272 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4274 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
4275 pmap_invalidate_page(pmap, pv->pv_va);
4276 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4278 free_pv_entry(pmap, pv);
4281 vm_page_aflag_clear(m, PGA_WRITEABLE);
4283 pmap_delayed_invl_wait(m);
4284 pmap_free_zero_pages(&free);
4288 * pmap_protect_pde: do the things to protect a 2mpage in a process
4291 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
4293 pd_entry_t newpde, oldpde;
4294 vm_offset_t eva, va;
4296 boolean_t anychanged;
4297 pt_entry_t PG_G, PG_M, PG_RW;
4299 PG_G = pmap_global_bit(pmap);
4300 PG_M = pmap_modified_bit(pmap);
4301 PG_RW = pmap_rw_bit(pmap);
4303 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4304 KASSERT((sva & PDRMASK) == 0,
4305 ("pmap_protect_pde: sva is not 2mpage aligned"));
4308 oldpde = newpde = *pde;
4309 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4310 (PG_MANAGED | PG_M | PG_RW)) {
4312 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4313 va < eva; va += PAGE_SIZE, m++)
4316 if ((prot & VM_PROT_WRITE) == 0)
4317 newpde &= ~(PG_RW | PG_M);
4318 if ((prot & VM_PROT_EXECUTE) == 0)
4320 if (newpde != oldpde) {
4322 * As an optimization to future operations on this PDE, clear
4323 * PG_PROMOTED. The impending invalidation will remove any
4324 * lingering 4KB page mappings from the TLB.
4326 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
4328 if ((oldpde & PG_G) != 0)
4329 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4333 return (anychanged);
4337 * Set the physical protection on the
4338 * specified range of this map as requested.
4341 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4343 vm_offset_t va_next;
4344 pml4_entry_t *pml4e;
4346 pd_entry_t ptpaddr, *pde;
4347 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4348 boolean_t anychanged;
4350 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4351 if (prot == VM_PROT_NONE) {
4352 pmap_remove(pmap, sva, eva);
4356 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4357 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4360 PG_G = pmap_global_bit(pmap);
4361 PG_M = pmap_modified_bit(pmap);
4362 PG_V = pmap_valid_bit(pmap);
4363 PG_RW = pmap_rw_bit(pmap);
4367 * Although this function delays and batches the invalidation
4368 * of stale TLB entries, it does not need to call
4369 * pmap_delayed_invl_started() and
4370 * pmap_delayed_invl_finished(), because it does not
4371 * ordinarily destroy mappings. Stale TLB entries from
4372 * protection-only changes need only be invalidated before the
4373 * pmap lock is released, because protection-only changes do
4374 * not destroy PV entries. Even operations that iterate over
4375 * a physical page's PV list of mappings, like
4376 * pmap_remove_write(), acquire the pmap lock for each
4377 * mapping. Consequently, for protection-only changes, the
4378 * pmap lock suffices to synchronize both page table and TLB
4381 * This function only destroys a mapping if pmap_demote_pde()
4382 * fails. In that case, stale TLB entries are immediately
4387 for (; sva < eva; sva = va_next) {
4389 pml4e = pmap_pml4e(pmap, sva);
4390 if ((*pml4e & PG_V) == 0) {
4391 va_next = (sva + NBPML4) & ~PML4MASK;
4397 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4398 if ((*pdpe & PG_V) == 0) {
4399 va_next = (sva + NBPDP) & ~PDPMASK;
4405 va_next = (sva + NBPDR) & ~PDRMASK;
4409 pde = pmap_pdpe_to_pde(pdpe, sva);
4413 * Weed out invalid mappings.
4419 * Check for large page.
4421 if ((ptpaddr & PG_PS) != 0) {
4423 * Are we protecting the entire large page? If not,
4424 * demote the mapping and fall through.
4426 if (sva + NBPDR == va_next && eva >= va_next) {
4428 * The TLB entry for a PG_G mapping is
4429 * invalidated by pmap_protect_pde().
4431 if (pmap_protect_pde(pmap, pde, sva, prot))
4434 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4436 * The large page mapping was destroyed.
4445 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4447 pt_entry_t obits, pbits;
4451 obits = pbits = *pte;
4452 if ((pbits & PG_V) == 0)
4455 if ((prot & VM_PROT_WRITE) == 0) {
4456 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4457 (PG_MANAGED | PG_M | PG_RW)) {
4458 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4461 pbits &= ~(PG_RW | PG_M);
4463 if ((prot & VM_PROT_EXECUTE) == 0)
4466 if (pbits != obits) {
4467 if (!atomic_cmpset_long(pte, obits, pbits))
4470 pmap_invalidate_page(pmap, sva);
4477 pmap_invalidate_all(pmap);
4481 #if VM_NRESERVLEVEL > 0
4483 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4484 * single page table page (PTP) to a single 2MB page mapping. For promotion
4485 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4486 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4487 * identical characteristics.
4490 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4491 struct rwlock **lockp)
4494 pt_entry_t *firstpte, oldpte, pa, *pte;
4495 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4499 PG_A = pmap_accessed_bit(pmap);
4500 PG_G = pmap_global_bit(pmap);
4501 PG_M = pmap_modified_bit(pmap);
4502 PG_V = pmap_valid_bit(pmap);
4503 PG_RW = pmap_rw_bit(pmap);
4504 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4506 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4509 * Examine the first PTE in the specified PTP. Abort if this PTE is
4510 * either invalid, unused, or does not map the first 4KB physical page
4511 * within a 2MB page.
4513 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4516 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4517 atomic_add_long(&pmap_pde_p_failures, 1);
4518 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4519 " in pmap %p", va, pmap);
4522 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4524 * When PG_M is already clear, PG_RW can be cleared without
4525 * a TLB invalidation.
4527 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4533 * Examine each of the other PTEs in the specified PTP. Abort if this
4534 * PTE maps an unexpected 4KB physical page or does not have identical
4535 * characteristics to the first PTE.
4537 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4538 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4541 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4542 atomic_add_long(&pmap_pde_p_failures, 1);
4543 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4544 " in pmap %p", va, pmap);
4547 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4549 * When PG_M is already clear, PG_RW can be cleared
4550 * without a TLB invalidation.
4552 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4555 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4556 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4557 (va & ~PDRMASK), pmap);
4559 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4560 atomic_add_long(&pmap_pde_p_failures, 1);
4561 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4562 " in pmap %p", va, pmap);
4569 * Save the page table page in its current state until the PDE
4570 * mapping the superpage is demoted by pmap_demote_pde() or
4571 * destroyed by pmap_remove_pde().
4573 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4574 KASSERT(mpte >= vm_page_array &&
4575 mpte < &vm_page_array[vm_page_array_size],
4576 ("pmap_promote_pde: page table page is out of range"));
4577 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4578 ("pmap_promote_pde: page table page's pindex is wrong"));
4579 if (pmap_insert_pt_page(pmap, mpte)) {
4580 atomic_add_long(&pmap_pde_p_failures, 1);
4582 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4588 * Promote the pv entries.
4590 if ((newpde & PG_MANAGED) != 0)
4591 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4594 * Propagate the PAT index to its proper position.
4596 newpde = pmap_swap_pat(pmap, newpde);
4599 * Map the superpage.
4601 if (workaround_erratum383)
4602 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4604 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
4606 atomic_add_long(&pmap_pde_promotions, 1);
4607 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4608 " in pmap %p", va, pmap);
4610 #endif /* VM_NRESERVLEVEL > 0 */
4613 * Insert the given physical page (p) at
4614 * the specified virtual address (v) in the
4615 * target physical map with the protection requested.
4617 * If specified, the page will be wired down, meaning
4618 * that the related pte can not be reclaimed.
4620 * NB: This is the only routine which MAY NOT lazy-evaluate
4621 * or lose information. That is, this routine must actually
4622 * insert this page into the given map NOW.
4624 * When destroying both a page table and PV entry, this function
4625 * performs the TLB invalidation before releasing the PV list
4626 * lock, so we do not need pmap_delayed_invl_page() calls here.
4629 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4630 u_int flags, int8_t psind)
4632 struct rwlock *lock;
4634 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4635 pt_entry_t newpte, origpte;
4642 PG_A = pmap_accessed_bit(pmap);
4643 PG_G = pmap_global_bit(pmap);
4644 PG_M = pmap_modified_bit(pmap);
4645 PG_V = pmap_valid_bit(pmap);
4646 PG_RW = pmap_rw_bit(pmap);
4648 va = trunc_page(va);
4649 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4650 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4651 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4653 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4654 va >= kmi.clean_eva,
4655 ("pmap_enter: managed mapping within the clean submap"));
4656 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4657 VM_OBJECT_ASSERT_LOCKED(m->object);
4658 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
4659 ("pmap_enter: flags %u has reserved bits set", flags));
4660 pa = VM_PAGE_TO_PHYS(m);
4661 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4662 if ((flags & VM_PROT_WRITE) != 0)
4664 if ((prot & VM_PROT_WRITE) != 0)
4666 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4667 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4668 if ((prot & VM_PROT_EXECUTE) == 0)
4670 if ((flags & PMAP_ENTER_WIRED) != 0)
4672 if (va < VM_MAXUSER_ADDRESS)
4674 if (pmap == kernel_pmap)
4676 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
4679 * Set modified bit gratuitously for writeable mappings if
4680 * the page is unmanaged. We do not want to take a fault
4681 * to do the dirty bit accounting for these mappings.
4683 if ((m->oflags & VPO_UNMANAGED) != 0) {
4684 if ((newpte & PG_RW) != 0)
4687 newpte |= PG_MANAGED;
4692 /* Assert the required virtual and physical alignment. */
4693 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
4694 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4695 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
4701 * In the case that a page table page is not
4702 * resident, we are creating it here.
4705 pde = pmap_pde(pmap, va);
4706 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4707 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4708 pte = pmap_pde_to_pte(pde, va);
4709 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4710 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4713 } else if (va < VM_MAXUSER_ADDRESS) {
4715 * Here if the pte page isn't mapped, or if it has been
4718 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4719 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4720 nosleep ? NULL : &lock);
4721 if (mpte == NULL && nosleep) {
4722 rv = KERN_RESOURCE_SHORTAGE;
4727 panic("pmap_enter: invalid page directory va=%#lx", va);
4732 * Is the specified virtual address already mapped?
4734 if ((origpte & PG_V) != 0) {
4736 * Wiring change, just update stats. We don't worry about
4737 * wiring PT pages as they remain resident as long as there
4738 * are valid mappings in them. Hence, if a user page is wired,
4739 * the PT page will be also.
4741 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4742 pmap->pm_stats.wired_count++;
4743 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4744 pmap->pm_stats.wired_count--;
4747 * Remove the extra PT page reference.
4751 KASSERT(mpte->wire_count > 0,
4752 ("pmap_enter: missing reference to page table page,"
4757 * Has the physical page changed?
4759 opa = origpte & PG_FRAME;
4762 * No, might be a protection or wiring change.
4764 if ((origpte & PG_MANAGED) != 0 &&
4765 (newpte & PG_RW) != 0)
4766 vm_page_aflag_set(m, PGA_WRITEABLE);
4767 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4773 * Increment the counters.
4775 if ((newpte & PG_W) != 0)
4776 pmap->pm_stats.wired_count++;
4777 pmap_resident_count_inc(pmap, 1);
4781 * Enter on the PV list if part of our managed memory.
4783 if ((newpte & PG_MANAGED) != 0) {
4784 pv = get_pv_entry(pmap, &lock);
4786 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4787 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4789 if ((newpte & PG_RW) != 0)
4790 vm_page_aflag_set(m, PGA_WRITEABLE);
4796 if ((origpte & PG_V) != 0) {
4798 origpte = pte_load_store(pte, newpte);
4799 opa = origpte & PG_FRAME;
4801 if ((origpte & PG_MANAGED) != 0) {
4802 om = PHYS_TO_VM_PAGE(opa);
4803 if ((origpte & (PG_M | PG_RW)) == (PG_M |
4806 if ((origpte & PG_A) != 0)
4807 vm_page_aflag_set(om, PGA_REFERENCED);
4808 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4809 pmap_pvh_free(&om->md, pmap, va);
4810 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4811 TAILQ_EMPTY(&om->md.pv_list) &&
4812 ((om->flags & PG_FICTITIOUS) != 0 ||
4813 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4814 vm_page_aflag_clear(om, PGA_WRITEABLE);
4816 } else if ((newpte & PG_M) == 0 && (origpte & (PG_M |
4817 PG_RW)) == (PG_M | PG_RW)) {
4818 if ((origpte & PG_MANAGED) != 0)
4822 * Although the PTE may still have PG_RW set, TLB
4823 * invalidation may nonetheless be required because
4824 * the PTE no longer has PG_M set.
4826 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4828 * This PTE change does not require TLB invalidation.
4832 if ((origpte & PG_A) != 0)
4833 pmap_invalidate_page(pmap, va);
4835 pte_store(pte, newpte);
4839 #if VM_NRESERVLEVEL > 0
4841 * If both the page table page and the reservation are fully
4842 * populated, then attempt promotion.
4844 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4845 pmap_ps_enabled(pmap) &&
4846 (m->flags & PG_FICTITIOUS) == 0 &&
4847 vm_reserv_level_iffullpop(m) == 0)
4848 pmap_promote_pde(pmap, pde, va, &lock);
4860 * Tries to create a read- and/or execute-only 2MB page mapping. Returns true
4861 * if successful. Returns false if (1) a page table page cannot be allocated
4862 * without sleeping, (2) a mapping already exists at the specified virtual
4863 * address, or (3) a PV entry cannot be allocated without reclaiming another
4867 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4868 struct rwlock **lockp)
4873 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4874 PG_V = pmap_valid_bit(pmap);
4875 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
4877 if ((m->oflags & VPO_UNMANAGED) == 0)
4878 newpde |= PG_MANAGED;
4879 if ((prot & VM_PROT_EXECUTE) == 0)
4881 if (va < VM_MAXUSER_ADDRESS)
4883 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
4884 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
4889 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
4890 * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
4891 * otherwise. Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
4892 * a mapping already exists at the specified virtual address. Returns
4893 * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
4894 * page allocation failed. Returns KERN_RESOURCE_SHORTAGE if
4895 * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
4897 * The parameter "m" is only used when creating a managed, writeable mapping.
4900 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
4901 vm_page_t m, struct rwlock **lockp)
4903 struct spglist free;
4904 pd_entry_t oldpde, *pde;
4905 pt_entry_t PG_G, PG_RW, PG_V;
4908 PG_G = pmap_global_bit(pmap);
4909 PG_RW = pmap_rw_bit(pmap);
4910 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
4911 ("pmap_enter_pde: newpde is missing PG_M"));
4912 PG_V = pmap_valid_bit(pmap);
4913 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4915 if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
4916 NULL : lockp)) == NULL) {
4917 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4918 " in pmap %p", va, pmap);
4919 return (KERN_RESOURCE_SHORTAGE);
4921 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4922 pde = &pde[pmap_pde_index(va)];
4924 if ((oldpde & PG_V) != 0) {
4925 KASSERT(pdpg->wire_count > 1,
4926 ("pmap_enter_pde: pdpg's wire count is too low"));
4927 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
4929 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4930 " in pmap %p", va, pmap);
4931 return (KERN_FAILURE);
4933 /* Break the existing mapping(s). */
4935 if ((oldpde & PG_PS) != 0) {
4937 * The reference to the PD page that was acquired by
4938 * pmap_allocpde() ensures that it won't be freed.
4939 * However, if the PDE resulted from a promotion, then
4940 * a reserved PT page could be freed.
4942 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
4943 if ((oldpde & PG_G) == 0)
4944 pmap_invalidate_pde_page(pmap, va, oldpde);
4946 pmap_delayed_invl_started();
4947 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
4949 pmap_invalidate_all(pmap);
4950 pmap_delayed_invl_finished();
4952 pmap_free_zero_pages(&free);
4953 if (va >= VM_MAXUSER_ADDRESS) {
4954 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4955 if (pmap_insert_pt_page(pmap, mt)) {
4957 * XXX Currently, this can't happen because
4958 * we do not perform pmap_enter(psind == 1)
4959 * on the kernel pmap.
4961 panic("pmap_enter_pde: trie insert failed");
4964 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
4967 if ((newpde & PG_MANAGED) != 0) {
4969 * Abort this mapping if its PV entry could not be created.
4971 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
4973 if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
4975 * Although "va" is not mapped, paging-
4976 * structure caches could nonetheless have
4977 * entries that refer to the freed page table
4978 * pages. Invalidate those entries.
4980 pmap_invalidate_page(pmap, va);
4981 pmap_free_zero_pages(&free);
4983 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4984 " in pmap %p", va, pmap);
4985 return (KERN_RESOURCE_SHORTAGE);
4987 if ((newpde & PG_RW) != 0) {
4988 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
4989 vm_page_aflag_set(mt, PGA_WRITEABLE);
4994 * Increment counters.
4996 if ((newpde & PG_W) != 0)
4997 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
4998 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5001 * Map the superpage. (This is not a promoted mapping; there will not
5002 * be any lingering 4KB page mappings in the TLB.)
5004 pde_store(pde, newpde);
5006 atomic_add_long(&pmap_pde_mappings, 1);
5007 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
5008 " in pmap %p", va, pmap);
5009 return (KERN_SUCCESS);
5013 * Maps a sequence of resident pages belonging to the same object.
5014 * The sequence begins with the given page m_start. This page is
5015 * mapped at the given virtual address start. Each subsequent page is
5016 * mapped at a virtual address that is offset from start by the same
5017 * amount as the page is offset from m_start within the object. The
5018 * last page in the sequence is the page with the largest offset from
5019 * m_start that can be mapped at a virtual address less than the given
5020 * virtual address end. Not every virtual page between start and end
5021 * is mapped; only those for which a resident page exists with the
5022 * corresponding offset from m_start are mapped.
5025 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
5026 vm_page_t m_start, vm_prot_t prot)
5028 struct rwlock *lock;
5031 vm_pindex_t diff, psize;
5033 VM_OBJECT_ASSERT_LOCKED(m_start->object);
5035 psize = atop(end - start);
5040 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
5041 va = start + ptoa(diff);
5042 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
5043 m->psind == 1 && pmap_ps_enabled(pmap) &&
5044 pmap_enter_2mpage(pmap, va, m, prot, &lock))
5045 m = &m[NBPDR / PAGE_SIZE - 1];
5047 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
5049 m = TAILQ_NEXT(m, listq);
5057 * this code makes some *MAJOR* assumptions:
5058 * 1. Current pmap & pmap exists.
5061 * 4. No page table pages.
5062 * but is *MUCH* faster than pmap_enter...
5066 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
5068 struct rwlock *lock;
5072 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
5079 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
5080 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
5082 struct spglist free;
5083 pt_entry_t *pte, PG_V;
5086 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
5087 (m->oflags & VPO_UNMANAGED) != 0,
5088 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
5089 PG_V = pmap_valid_bit(pmap);
5090 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5093 * In the case that a page table page is not
5094 * resident, we are creating it here.
5096 if (va < VM_MAXUSER_ADDRESS) {
5097 vm_pindex_t ptepindex;
5101 * Calculate pagetable page index
5103 ptepindex = pmap_pde_pindex(va);
5104 if (mpte && (mpte->pindex == ptepindex)) {
5108 * Get the page directory entry
5110 ptepa = pmap_pde(pmap, va);
5113 * If the page table page is mapped, we just increment
5114 * the hold count, and activate it. Otherwise, we
5115 * attempt to allocate a page table page. If this
5116 * attempt fails, we don't retry. Instead, we give up.
5118 if (ptepa && (*ptepa & PG_V) != 0) {
5121 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
5125 * Pass NULL instead of the PV list lock
5126 * pointer, because we don't intend to sleep.
5128 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
5133 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
5134 pte = &pte[pmap_pte_index(va)];
5148 * Enter on the PV list if part of our managed memory.
5150 if ((m->oflags & VPO_UNMANAGED) == 0 &&
5151 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
5154 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
5156 * Although "va" is not mapped, paging-
5157 * structure caches could nonetheless have
5158 * entries that refer to the freed page table
5159 * pages. Invalidate those entries.
5161 pmap_invalidate_page(pmap, va);
5162 pmap_free_zero_pages(&free);
5170 * Increment counters
5172 pmap_resident_count_inc(pmap, 1);
5174 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
5175 if ((prot & VM_PROT_EXECUTE) == 0)
5179 * Now validate mapping with RO protection
5181 if ((m->oflags & VPO_UNMANAGED) != 0)
5182 pte_store(pte, pa | PG_V | PG_U);
5184 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
5189 * Make a temporary mapping for a physical address. This is only intended
5190 * to be used for panic dumps.
5193 pmap_kenter_temporary(vm_paddr_t pa, int i)
5197 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
5198 pmap_kenter(va, pa);
5200 return ((void *)crashdumpmap);
5204 * This code maps large physical mmap regions into the
5205 * processor address space. Note that some shortcuts
5206 * are taken, but the code works.
5209 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
5210 vm_pindex_t pindex, vm_size_t size)
5213 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5214 vm_paddr_t pa, ptepa;
5218 PG_A = pmap_accessed_bit(pmap);
5219 PG_M = pmap_modified_bit(pmap);
5220 PG_V = pmap_valid_bit(pmap);
5221 PG_RW = pmap_rw_bit(pmap);
5223 VM_OBJECT_ASSERT_WLOCKED(object);
5224 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
5225 ("pmap_object_init_pt: non-device object"));
5226 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
5227 if (!pmap_ps_enabled(pmap))
5229 if (!vm_object_populate(object, pindex, pindex + atop(size)))
5231 p = vm_page_lookup(object, pindex);
5232 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5233 ("pmap_object_init_pt: invalid page %p", p));
5234 pat_mode = p->md.pat_mode;
5237 * Abort the mapping if the first page is not physically
5238 * aligned to a 2MB page boundary.
5240 ptepa = VM_PAGE_TO_PHYS(p);
5241 if (ptepa & (NBPDR - 1))
5245 * Skip the first page. Abort the mapping if the rest of
5246 * the pages are not physically contiguous or have differing
5247 * memory attributes.
5249 p = TAILQ_NEXT(p, listq);
5250 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
5252 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5253 ("pmap_object_init_pt: invalid page %p", p));
5254 if (pa != VM_PAGE_TO_PHYS(p) ||
5255 pat_mode != p->md.pat_mode)
5257 p = TAILQ_NEXT(p, listq);
5261 * Map using 2MB pages. Since "ptepa" is 2M aligned and
5262 * "size" is a multiple of 2M, adding the PAT setting to "pa"
5263 * will not affect the termination of this loop.
5266 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
5267 pa < ptepa + size; pa += NBPDR) {
5268 pdpg = pmap_allocpde(pmap, addr, NULL);
5271 * The creation of mappings below is only an
5272 * optimization. If a page directory page
5273 * cannot be allocated without blocking,
5274 * continue on to the next mapping rather than
5280 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5281 pde = &pde[pmap_pde_index(addr)];
5282 if ((*pde & PG_V) == 0) {
5283 pde_store(pde, pa | PG_PS | PG_M | PG_A |
5284 PG_U | PG_RW | PG_V);
5285 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5286 atomic_add_long(&pmap_pde_mappings, 1);
5288 /* Continue on if the PDE is already valid. */
5290 KASSERT(pdpg->wire_count > 0,
5291 ("pmap_object_init_pt: missing reference "
5292 "to page directory page, va: 0x%lx", addr));
5301 * Clear the wired attribute from the mappings for the specified range of
5302 * addresses in the given pmap. Every valid mapping within that range
5303 * must have the wired attribute set. In contrast, invalid mappings
5304 * cannot have the wired attribute set, so they are ignored.
5306 * The wired attribute of the page table entry is not a hardware
5307 * feature, so there is no need to invalidate any TLB entries.
5308 * Since pmap_demote_pde() for the wired entry must never fail,
5309 * pmap_delayed_invl_started()/finished() calls around the
5310 * function are not needed.
5313 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5315 vm_offset_t va_next;
5316 pml4_entry_t *pml4e;
5319 pt_entry_t *pte, PG_V;
5321 PG_V = pmap_valid_bit(pmap);
5323 for (; sva < eva; sva = va_next) {
5324 pml4e = pmap_pml4e(pmap, sva);
5325 if ((*pml4e & PG_V) == 0) {
5326 va_next = (sva + NBPML4) & ~PML4MASK;
5331 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5332 if ((*pdpe & PG_V) == 0) {
5333 va_next = (sva + NBPDP) & ~PDPMASK;
5338 va_next = (sva + NBPDR) & ~PDRMASK;
5341 pde = pmap_pdpe_to_pde(pdpe, sva);
5342 if ((*pde & PG_V) == 0)
5344 if ((*pde & PG_PS) != 0) {
5345 if ((*pde & PG_W) == 0)
5346 panic("pmap_unwire: pde %#jx is missing PG_W",
5350 * Are we unwiring the entire large page? If not,
5351 * demote the mapping and fall through.
5353 if (sva + NBPDR == va_next && eva >= va_next) {
5354 atomic_clear_long(pde, PG_W);
5355 pmap->pm_stats.wired_count -= NBPDR /
5358 } else if (!pmap_demote_pde(pmap, pde, sva))
5359 panic("pmap_unwire: demotion failed");
5363 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
5365 if ((*pte & PG_V) == 0)
5367 if ((*pte & PG_W) == 0)
5368 panic("pmap_unwire: pte %#jx is missing PG_W",
5372 * PG_W must be cleared atomically. Although the pmap
5373 * lock synchronizes access to PG_W, another processor
5374 * could be setting PG_M and/or PG_A concurrently.
5376 atomic_clear_long(pte, PG_W);
5377 pmap->pm_stats.wired_count--;
5384 * Copy the range specified by src_addr/len
5385 * from the source map to the range dst_addr/len
5386 * in the destination map.
5388 * This routine is only advisory and need not do anything.
5392 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5393 vm_offset_t src_addr)
5395 struct rwlock *lock;
5396 struct spglist free;
5398 vm_offset_t end_addr = src_addr + len;
5399 vm_offset_t va_next;
5400 vm_page_t dst_pdpg, dstmpte, srcmpte;
5401 pt_entry_t PG_A, PG_M, PG_V;
5403 if (dst_addr != src_addr)
5406 if (dst_pmap->pm_type != src_pmap->pm_type)
5410 * EPT page table entries that require emulation of A/D bits are
5411 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5412 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5413 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5414 * implementations flag an EPT misconfiguration for exec-only
5415 * mappings we skip this function entirely for emulated pmaps.
5417 if (pmap_emulate_ad_bits(dst_pmap))
5421 if (dst_pmap < src_pmap) {
5422 PMAP_LOCK(dst_pmap);
5423 PMAP_LOCK(src_pmap);
5425 PMAP_LOCK(src_pmap);
5426 PMAP_LOCK(dst_pmap);
5429 PG_A = pmap_accessed_bit(dst_pmap);
5430 PG_M = pmap_modified_bit(dst_pmap);
5431 PG_V = pmap_valid_bit(dst_pmap);
5433 for (addr = src_addr; addr < end_addr; addr = va_next) {
5434 pt_entry_t *src_pte, *dst_pte;
5435 pml4_entry_t *pml4e;
5437 pd_entry_t srcptepaddr, *pde;
5439 KASSERT(addr < UPT_MIN_ADDRESS,
5440 ("pmap_copy: invalid to pmap_copy page tables"));
5442 pml4e = pmap_pml4e(src_pmap, addr);
5443 if ((*pml4e & PG_V) == 0) {
5444 va_next = (addr + NBPML4) & ~PML4MASK;
5450 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5451 if ((*pdpe & PG_V) == 0) {
5452 va_next = (addr + NBPDP) & ~PDPMASK;
5458 va_next = (addr + NBPDR) & ~PDRMASK;
5462 pde = pmap_pdpe_to_pde(pdpe, addr);
5464 if (srcptepaddr == 0)
5467 if (srcptepaddr & PG_PS) {
5468 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5470 dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
5471 if (dst_pdpg == NULL)
5473 pde = (pd_entry_t *)
5474 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
5475 pde = &pde[pmap_pde_index(addr)];
5476 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5477 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
5478 PMAP_ENTER_NORECLAIM, &lock))) {
5479 *pde = srcptepaddr & ~PG_W;
5480 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5481 atomic_add_long(&pmap_pde_mappings, 1);
5483 dst_pdpg->wire_count--;
5487 srcptepaddr &= PG_FRAME;
5488 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5489 KASSERT(srcmpte->wire_count > 0,
5490 ("pmap_copy: source page table page is unused"));
5492 if (va_next > end_addr)
5495 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5496 src_pte = &src_pte[pmap_pte_index(addr)];
5498 while (addr < va_next) {
5502 * we only virtual copy managed pages
5504 if ((ptetemp & PG_MANAGED) != 0) {
5505 if (dstmpte != NULL &&
5506 dstmpte->pindex == pmap_pde_pindex(addr))
5507 dstmpte->wire_count++;
5508 else if ((dstmpte = pmap_allocpte(dst_pmap,
5509 addr, NULL)) == NULL)
5511 dst_pte = (pt_entry_t *)
5512 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5513 dst_pte = &dst_pte[pmap_pte_index(addr)];
5514 if (*dst_pte == 0 &&
5515 pmap_try_insert_pv_entry(dst_pmap, addr,
5516 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5519 * Clear the wired, modified, and
5520 * accessed (referenced) bits
5523 *dst_pte = ptetemp & ~(PG_W | PG_M |
5525 pmap_resident_count_inc(dst_pmap, 1);
5528 if (pmap_unwire_ptp(dst_pmap, addr,
5531 * Although "addr" is not
5532 * mapped, paging-structure
5533 * caches could nonetheless
5534 * have entries that refer to
5535 * the freed page table pages.
5536 * Invalidate those entries.
5538 pmap_invalidate_page(dst_pmap,
5540 pmap_free_zero_pages(&free);
5544 if (dstmpte->wire_count >= srcmpte->wire_count)
5554 PMAP_UNLOCK(src_pmap);
5555 PMAP_UNLOCK(dst_pmap);
5559 * Zero the specified hardware page.
5562 pmap_zero_page(vm_page_t m)
5564 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5566 pagezero((void *)va);
5570 * Zero an an area within a single hardware page. off and size must not
5571 * cover an area beyond a single hardware page.
5574 pmap_zero_page_area(vm_page_t m, int off, int size)
5576 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5578 if (off == 0 && size == PAGE_SIZE)
5579 pagezero((void *)va);
5581 bzero((char *)va + off, size);
5585 * Copy 1 specified hardware page to another.
5588 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5590 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5591 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5593 pagecopy((void *)src, (void *)dst);
5596 int unmapped_buf_allowed = 1;
5599 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5600 vm_offset_t b_offset, int xfersize)
5604 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5608 while (xfersize > 0) {
5609 a_pg_offset = a_offset & PAGE_MASK;
5610 pages[0] = ma[a_offset >> PAGE_SHIFT];
5611 b_pg_offset = b_offset & PAGE_MASK;
5612 pages[1] = mb[b_offset >> PAGE_SHIFT];
5613 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5614 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5615 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5616 a_cp = (char *)vaddr[0] + a_pg_offset;
5617 b_cp = (char *)vaddr[1] + b_pg_offset;
5618 bcopy(a_cp, b_cp, cnt);
5619 if (__predict_false(mapped))
5620 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5628 * Returns true if the pmap's pv is one of the first
5629 * 16 pvs linked to from this page. This count may
5630 * be changed upwards or downwards in the future; it
5631 * is only necessary that true be returned for a small
5632 * subset of pmaps for proper page aging.
5635 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5637 struct md_page *pvh;
5638 struct rwlock *lock;
5643 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5644 ("pmap_page_exists_quick: page %p is not managed", m));
5646 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5648 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5649 if (PV_PMAP(pv) == pmap) {
5657 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5658 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5659 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5660 if (PV_PMAP(pv) == pmap) {
5674 * pmap_page_wired_mappings:
5676 * Return the number of managed mappings to the given physical page
5680 pmap_page_wired_mappings(vm_page_t m)
5682 struct rwlock *lock;
5683 struct md_page *pvh;
5687 int count, md_gen, pvh_gen;
5689 if ((m->oflags & VPO_UNMANAGED) != 0)
5691 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5695 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5697 if (!PMAP_TRYLOCK(pmap)) {
5698 md_gen = m->md.pv_gen;
5702 if (md_gen != m->md.pv_gen) {
5707 pte = pmap_pte(pmap, pv->pv_va);
5708 if ((*pte & PG_W) != 0)
5712 if ((m->flags & PG_FICTITIOUS) == 0) {
5713 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5714 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5716 if (!PMAP_TRYLOCK(pmap)) {
5717 md_gen = m->md.pv_gen;
5718 pvh_gen = pvh->pv_gen;
5722 if (md_gen != m->md.pv_gen ||
5723 pvh_gen != pvh->pv_gen) {
5728 pte = pmap_pde(pmap, pv->pv_va);
5729 if ((*pte & PG_W) != 0)
5739 * Returns TRUE if the given page is mapped individually or as part of
5740 * a 2mpage. Otherwise, returns FALSE.
5743 pmap_page_is_mapped(vm_page_t m)
5745 struct rwlock *lock;
5748 if ((m->oflags & VPO_UNMANAGED) != 0)
5750 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5752 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5753 ((m->flags & PG_FICTITIOUS) == 0 &&
5754 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5760 * Destroy all managed, non-wired mappings in the given user-space
5761 * pmap. This pmap cannot be active on any processor besides the
5764 * This function cannot be applied to the kernel pmap. Moreover, it
5765 * is not intended for general use. It is only to be used during
5766 * process termination. Consequently, it can be implemented in ways
5767 * that make it faster than pmap_remove(). First, it can more quickly
5768 * destroy mappings by iterating over the pmap's collection of PV
5769 * entries, rather than searching the page table. Second, it doesn't
5770 * have to test and clear the page table entries atomically, because
5771 * no processor is currently accessing the user address space. In
5772 * particular, a page table entry's dirty bit won't change state once
5773 * this function starts.
5775 * Although this function destroys all of the pmap's managed,
5776 * non-wired mappings, it can delay and batch the invalidation of TLB
5777 * entries without calling pmap_delayed_invl_started() and
5778 * pmap_delayed_invl_finished(). Because the pmap is not active on
5779 * any other processor, none of these TLB entries will ever be used
5780 * before their eventual invalidation. Consequently, there is no need
5781 * for either pmap_remove_all() or pmap_remove_write() to wait for
5782 * that eventual TLB invalidation.
5785 pmap_remove_pages(pmap_t pmap)
5788 pt_entry_t *pte, tpte;
5789 pt_entry_t PG_M, PG_RW, PG_V;
5790 struct spglist free;
5791 vm_page_t m, mpte, mt;
5793 struct md_page *pvh;
5794 struct pv_chunk *pc, *npc;
5795 struct rwlock *lock;
5797 uint64_t inuse, bitmask;
5798 int allfree, field, freed, idx;
5799 boolean_t superpage;
5803 * Assert that the given pmap is only active on the current
5804 * CPU. Unfortunately, we cannot block another CPU from
5805 * activating the pmap while this function is executing.
5807 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5810 cpuset_t other_cpus;
5812 other_cpus = all_cpus;
5814 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5815 CPU_AND(&other_cpus, &pmap->pm_active);
5817 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5822 PG_M = pmap_modified_bit(pmap);
5823 PG_V = pmap_valid_bit(pmap);
5824 PG_RW = pmap_rw_bit(pmap);
5828 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5831 for (field = 0; field < _NPCM; field++) {
5832 inuse = ~pc->pc_map[field] & pc_freemask[field];
5833 while (inuse != 0) {
5835 bitmask = 1UL << bit;
5836 idx = field * 64 + bit;
5837 pv = &pc->pc_pventry[idx];
5840 pte = pmap_pdpe(pmap, pv->pv_va);
5842 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5844 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5847 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5849 pte = &pte[pmap_pte_index(pv->pv_va)];
5853 * Keep track whether 'tpte' is a
5854 * superpage explicitly instead of
5855 * relying on PG_PS being set.
5857 * This is because PG_PS is numerically
5858 * identical to PG_PTE_PAT and thus a
5859 * regular page could be mistaken for
5865 if ((tpte & PG_V) == 0) {
5866 panic("bad pte va %lx pte %lx",
5871 * We cannot remove wired pages from a process' mapping at this time
5879 pa = tpte & PG_PS_FRAME;
5881 pa = tpte & PG_FRAME;
5883 m = PHYS_TO_VM_PAGE(pa);
5884 KASSERT(m->phys_addr == pa,
5885 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5886 m, (uintmax_t)m->phys_addr,
5889 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5890 m < &vm_page_array[vm_page_array_size],
5891 ("pmap_remove_pages: bad tpte %#jx",
5897 * Update the vm_page_t clean/reference bits.
5899 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5901 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5907 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5910 pc->pc_map[field] |= bitmask;
5912 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
5913 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
5914 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5916 if (TAILQ_EMPTY(&pvh->pv_list)) {
5917 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5918 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
5919 TAILQ_EMPTY(&mt->md.pv_list))
5920 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5922 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
5924 pmap_resident_count_dec(pmap, 1);
5925 KASSERT(mpte->wire_count == NPTEPG,
5926 ("pmap_remove_pages: pte page wire count error"));
5927 mpte->wire_count = 0;
5928 pmap_add_delayed_free_list(mpte, &free, FALSE);
5931 pmap_resident_count_dec(pmap, 1);
5932 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5934 if ((m->aflags & PGA_WRITEABLE) != 0 &&
5935 TAILQ_EMPTY(&m->md.pv_list) &&
5936 (m->flags & PG_FICTITIOUS) == 0) {
5937 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5938 if (TAILQ_EMPTY(&pvh->pv_list))
5939 vm_page_aflag_clear(m, PGA_WRITEABLE);
5942 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
5946 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5947 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5948 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5950 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5956 pmap_invalidate_all(pmap);
5958 pmap_free_zero_pages(&free);
5962 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
5964 struct rwlock *lock;
5966 struct md_page *pvh;
5967 pt_entry_t *pte, mask;
5968 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5970 int md_gen, pvh_gen;
5974 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5977 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5979 if (!PMAP_TRYLOCK(pmap)) {
5980 md_gen = m->md.pv_gen;
5984 if (md_gen != m->md.pv_gen) {
5989 pte = pmap_pte(pmap, pv->pv_va);
5992 PG_M = pmap_modified_bit(pmap);
5993 PG_RW = pmap_rw_bit(pmap);
5994 mask |= PG_RW | PG_M;
5997 PG_A = pmap_accessed_bit(pmap);
5998 PG_V = pmap_valid_bit(pmap);
5999 mask |= PG_V | PG_A;
6001 rv = (*pte & mask) == mask;
6006 if ((m->flags & PG_FICTITIOUS) == 0) {
6007 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6008 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
6010 if (!PMAP_TRYLOCK(pmap)) {
6011 md_gen = m->md.pv_gen;
6012 pvh_gen = pvh->pv_gen;
6016 if (md_gen != m->md.pv_gen ||
6017 pvh_gen != pvh->pv_gen) {
6022 pte = pmap_pde(pmap, pv->pv_va);
6025 PG_M = pmap_modified_bit(pmap);
6026 PG_RW = pmap_rw_bit(pmap);
6027 mask |= PG_RW | PG_M;
6030 PG_A = pmap_accessed_bit(pmap);
6031 PG_V = pmap_valid_bit(pmap);
6032 mask |= PG_V | PG_A;
6034 rv = (*pte & mask) == mask;
6048 * Return whether or not the specified physical page was modified
6049 * in any physical maps.
6052 pmap_is_modified(vm_page_t m)
6055 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6056 ("pmap_is_modified: page %p is not managed", m));
6059 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6060 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
6061 * is clear, no PTEs can have PG_M set.
6063 VM_OBJECT_ASSERT_WLOCKED(m->object);
6064 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6066 return (pmap_page_test_mappings(m, FALSE, TRUE));
6070 * pmap_is_prefaultable:
6072 * Return whether or not the specified virtual address is eligible
6076 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
6079 pt_entry_t *pte, PG_V;
6082 PG_V = pmap_valid_bit(pmap);
6085 pde = pmap_pde(pmap, addr);
6086 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
6087 pte = pmap_pde_to_pte(pde, addr);
6088 rv = (*pte & PG_V) == 0;
6095 * pmap_is_referenced:
6097 * Return whether or not the specified physical page was referenced
6098 * in any physical maps.
6101 pmap_is_referenced(vm_page_t m)
6104 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6105 ("pmap_is_referenced: page %p is not managed", m));
6106 return (pmap_page_test_mappings(m, TRUE, FALSE));
6110 * Clear the write and modified bits in each of the given page's mappings.
6113 pmap_remove_write(vm_page_t m)
6115 struct md_page *pvh;
6117 struct rwlock *lock;
6118 pv_entry_t next_pv, pv;
6120 pt_entry_t oldpte, *pte, PG_M, PG_RW;
6122 int pvh_gen, md_gen;
6124 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6125 ("pmap_remove_write: page %p is not managed", m));
6128 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6129 * set by another thread while the object is locked. Thus,
6130 * if PGA_WRITEABLE is clear, no page table entries need updating.
6132 VM_OBJECT_ASSERT_WLOCKED(m->object);
6133 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6135 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6136 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6137 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6140 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6142 if (!PMAP_TRYLOCK(pmap)) {
6143 pvh_gen = pvh->pv_gen;
6147 if (pvh_gen != pvh->pv_gen) {
6153 PG_RW = pmap_rw_bit(pmap);
6155 pde = pmap_pde(pmap, va);
6156 if ((*pde & PG_RW) != 0)
6157 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6158 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6159 ("inconsistent pv lock %p %p for page %p",
6160 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6163 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6165 if (!PMAP_TRYLOCK(pmap)) {
6166 pvh_gen = pvh->pv_gen;
6167 md_gen = m->md.pv_gen;
6171 if (pvh_gen != pvh->pv_gen ||
6172 md_gen != m->md.pv_gen) {
6178 PG_M = pmap_modified_bit(pmap);
6179 PG_RW = pmap_rw_bit(pmap);
6180 pde = pmap_pde(pmap, pv->pv_va);
6181 KASSERT((*pde & PG_PS) == 0,
6182 ("pmap_remove_write: found a 2mpage in page %p's pv list",
6184 pte = pmap_pde_to_pte(pde, pv->pv_va);
6187 if (oldpte & PG_RW) {
6188 if (!atomic_cmpset_long(pte, oldpte, oldpte &
6191 if ((oldpte & PG_M) != 0)
6193 pmap_invalidate_page(pmap, pv->pv_va);
6198 vm_page_aflag_clear(m, PGA_WRITEABLE);
6199 pmap_delayed_invl_wait(m);
6202 static __inline boolean_t
6203 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
6206 if (!pmap_emulate_ad_bits(pmap))
6209 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
6212 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
6213 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
6214 * if the EPT_PG_WRITE bit is set.
6216 if ((pte & EPT_PG_WRITE) != 0)
6220 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
6222 if ((pte & EPT_PG_EXECUTE) == 0 ||
6223 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
6230 * pmap_ts_referenced:
6232 * Return a count of reference bits for a page, clearing those bits.
6233 * It is not necessary for every reference bit to be cleared, but it
6234 * is necessary that 0 only be returned when there are truly no
6235 * reference bits set.
6237 * As an optimization, update the page's dirty field if a modified bit is
6238 * found while counting reference bits. This opportunistic update can be
6239 * performed at low cost and can eliminate the need for some future calls
6240 * to pmap_is_modified(). However, since this function stops after
6241 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
6242 * dirty pages. Those dirty pages will only be detected by a future call
6243 * to pmap_is_modified().
6245 * A DI block is not needed within this function, because
6246 * invalidations are performed before the PV list lock is
6250 pmap_ts_referenced(vm_page_t m)
6252 struct md_page *pvh;
6255 struct rwlock *lock;
6256 pd_entry_t oldpde, *pde;
6257 pt_entry_t *pte, PG_A, PG_M, PG_RW;
6260 int cleared, md_gen, not_cleared, pvh_gen;
6261 struct spglist free;
6264 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6265 ("pmap_ts_referenced: page %p is not managed", m));
6268 pa = VM_PAGE_TO_PHYS(m);
6269 lock = PHYS_TO_PV_LIST_LOCK(pa);
6270 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
6274 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6275 goto small_mappings;
6281 if (!PMAP_TRYLOCK(pmap)) {
6282 pvh_gen = pvh->pv_gen;
6286 if (pvh_gen != pvh->pv_gen) {
6291 PG_A = pmap_accessed_bit(pmap);
6292 PG_M = pmap_modified_bit(pmap);
6293 PG_RW = pmap_rw_bit(pmap);
6295 pde = pmap_pde(pmap, pv->pv_va);
6297 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6299 * Although "oldpde" is mapping a 2MB page, because
6300 * this function is called at a 4KB page granularity,
6301 * we only update the 4KB page under test.
6305 if ((oldpde & PG_A) != 0) {
6307 * Since this reference bit is shared by 512 4KB
6308 * pages, it should not be cleared every time it is
6309 * tested. Apply a simple "hash" function on the
6310 * physical page number, the virtual superpage number,
6311 * and the pmap address to select one 4KB page out of
6312 * the 512 on which testing the reference bit will
6313 * result in clearing that reference bit. This
6314 * function is designed to avoid the selection of the
6315 * same 4KB page for every 2MB page mapping.
6317 * On demotion, a mapping that hasn't been referenced
6318 * is simply destroyed. To avoid the possibility of a
6319 * subsequent page fault on a demoted wired mapping,
6320 * always leave its reference bit set. Moreover,
6321 * since the superpage is wired, the current state of
6322 * its reference bit won't affect page replacement.
6324 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
6325 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
6326 (oldpde & PG_W) == 0) {
6327 if (safe_to_clear_referenced(pmap, oldpde)) {
6328 atomic_clear_long(pde, PG_A);
6329 pmap_invalidate_page(pmap, pv->pv_va);
6331 } else if (pmap_demote_pde_locked(pmap, pde,
6332 pv->pv_va, &lock)) {
6334 * Remove the mapping to a single page
6335 * so that a subsequent access may
6336 * repromote. Since the underlying
6337 * page table page is fully populated,
6338 * this removal never frees a page
6342 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6344 pte = pmap_pde_to_pte(pde, va);
6345 pmap_remove_pte(pmap, pte, va, *pde,
6347 pmap_invalidate_page(pmap, va);
6353 * The superpage mapping was removed
6354 * entirely and therefore 'pv' is no
6362 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6363 ("inconsistent pv lock %p %p for page %p",
6364 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6369 /* Rotate the PV list if it has more than one entry. */
6370 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6371 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6372 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6375 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6377 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6379 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6386 if (!PMAP_TRYLOCK(pmap)) {
6387 pvh_gen = pvh->pv_gen;
6388 md_gen = m->md.pv_gen;
6392 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6397 PG_A = pmap_accessed_bit(pmap);
6398 PG_M = pmap_modified_bit(pmap);
6399 PG_RW = pmap_rw_bit(pmap);
6400 pde = pmap_pde(pmap, pv->pv_va);
6401 KASSERT((*pde & PG_PS) == 0,
6402 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6404 pte = pmap_pde_to_pte(pde, pv->pv_va);
6405 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6407 if ((*pte & PG_A) != 0) {
6408 if (safe_to_clear_referenced(pmap, *pte)) {
6409 atomic_clear_long(pte, PG_A);
6410 pmap_invalidate_page(pmap, pv->pv_va);
6412 } else if ((*pte & PG_W) == 0) {
6414 * Wired pages cannot be paged out so
6415 * doing accessed bit emulation for
6416 * them is wasted effort. We do the
6417 * hard work for unwired pages only.
6419 pmap_remove_pte(pmap, pte, pv->pv_va,
6420 *pde, &free, &lock);
6421 pmap_invalidate_page(pmap, pv->pv_va);
6426 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6427 ("inconsistent pv lock %p %p for page %p",
6428 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6433 /* Rotate the PV list if it has more than one entry. */
6434 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6435 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6436 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6439 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6440 not_cleared < PMAP_TS_REFERENCED_MAX);
6443 pmap_free_zero_pages(&free);
6444 return (cleared + not_cleared);
6448 * Apply the given advice to the specified range of addresses within the
6449 * given pmap. Depending on the advice, clear the referenced and/or
6450 * modified flags in each mapping and set the mapped page's dirty field.
6453 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6455 struct rwlock *lock;
6456 pml4_entry_t *pml4e;
6458 pd_entry_t oldpde, *pde;
6459 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6460 vm_offset_t va, va_next;
6462 boolean_t anychanged;
6464 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6468 * A/D bit emulation requires an alternate code path when clearing
6469 * the modified and accessed bits below. Since this function is
6470 * advisory in nature we skip it entirely for pmaps that require
6471 * A/D bit emulation.
6473 if (pmap_emulate_ad_bits(pmap))
6476 PG_A = pmap_accessed_bit(pmap);
6477 PG_G = pmap_global_bit(pmap);
6478 PG_M = pmap_modified_bit(pmap);
6479 PG_V = pmap_valid_bit(pmap);
6480 PG_RW = pmap_rw_bit(pmap);
6482 pmap_delayed_invl_started();
6484 for (; sva < eva; sva = va_next) {
6485 pml4e = pmap_pml4e(pmap, sva);
6486 if ((*pml4e & PG_V) == 0) {
6487 va_next = (sva + NBPML4) & ~PML4MASK;
6492 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6493 if ((*pdpe & PG_V) == 0) {
6494 va_next = (sva + NBPDP) & ~PDPMASK;
6499 va_next = (sva + NBPDR) & ~PDRMASK;
6502 pde = pmap_pdpe_to_pde(pdpe, sva);
6504 if ((oldpde & PG_V) == 0)
6506 else if ((oldpde & PG_PS) != 0) {
6507 if ((oldpde & PG_MANAGED) == 0)
6510 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6515 * The large page mapping was destroyed.
6521 * Unless the page mappings are wired, remove the
6522 * mapping to a single page so that a subsequent
6523 * access may repromote. Since the underlying page
6524 * table page is fully populated, this removal never
6525 * frees a page table page.
6527 if ((oldpde & PG_W) == 0) {
6528 pte = pmap_pde_to_pte(pde, sva);
6529 KASSERT((*pte & PG_V) != 0,
6530 ("pmap_advise: invalid PTE"));
6531 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6541 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6543 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6545 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6546 if (advice == MADV_DONTNEED) {
6548 * Future calls to pmap_is_modified()
6549 * can be avoided by making the page
6552 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6555 atomic_clear_long(pte, PG_M | PG_A);
6556 } else if ((*pte & PG_A) != 0)
6557 atomic_clear_long(pte, PG_A);
6561 if ((*pte & PG_G) != 0) {
6568 if (va != va_next) {
6569 pmap_invalidate_range(pmap, va, sva);
6574 pmap_invalidate_range(pmap, va, sva);
6577 pmap_invalidate_all(pmap);
6579 pmap_delayed_invl_finished();
6583 * Clear the modify bits on the specified physical page.
6586 pmap_clear_modify(vm_page_t m)
6588 struct md_page *pvh;
6590 pv_entry_t next_pv, pv;
6591 pd_entry_t oldpde, *pde;
6592 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6593 struct rwlock *lock;
6595 int md_gen, pvh_gen;
6597 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6598 ("pmap_clear_modify: page %p is not managed", m));
6599 VM_OBJECT_ASSERT_WLOCKED(m->object);
6600 KASSERT(!vm_page_xbusied(m),
6601 ("pmap_clear_modify: page %p is exclusive busied", m));
6604 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6605 * If the object containing the page is locked and the page is not
6606 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6608 if ((m->aflags & PGA_WRITEABLE) == 0)
6610 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6611 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6612 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6615 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6617 if (!PMAP_TRYLOCK(pmap)) {
6618 pvh_gen = pvh->pv_gen;
6622 if (pvh_gen != pvh->pv_gen) {
6627 PG_M = pmap_modified_bit(pmap);
6628 PG_V = pmap_valid_bit(pmap);
6629 PG_RW = pmap_rw_bit(pmap);
6631 pde = pmap_pde(pmap, va);
6633 if ((oldpde & PG_RW) != 0) {
6634 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6635 if ((oldpde & PG_W) == 0) {
6637 * Write protect the mapping to a
6638 * single page so that a subsequent
6639 * write access may repromote.
6641 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6643 pte = pmap_pde_to_pte(pde, va);
6645 if ((oldpte & PG_V) != 0) {
6646 while (!atomic_cmpset_long(pte,
6648 oldpte & ~(PG_M | PG_RW)))
6651 pmap_invalidate_page(pmap, va);
6658 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6660 if (!PMAP_TRYLOCK(pmap)) {
6661 md_gen = m->md.pv_gen;
6662 pvh_gen = pvh->pv_gen;
6666 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6671 PG_M = pmap_modified_bit(pmap);
6672 PG_RW = pmap_rw_bit(pmap);
6673 pde = pmap_pde(pmap, pv->pv_va);
6674 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6675 " a 2mpage in page %p's pv list", m));
6676 pte = pmap_pde_to_pte(pde, pv->pv_va);
6677 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6678 atomic_clear_long(pte, PG_M);
6679 pmap_invalidate_page(pmap, pv->pv_va);
6687 * Miscellaneous support routines follow
6690 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6691 static __inline void
6692 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6697 * The cache mode bits are all in the low 32-bits of the
6698 * PTE, so we can just spin on updating the low 32-bits.
6701 opte = *(u_int *)pte;
6702 npte = opte & ~mask;
6704 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6707 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6708 static __inline void
6709 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6714 * The cache mode bits are all in the low 32-bits of the
6715 * PDE, so we can just spin on updating the low 32-bits.
6718 opde = *(u_int *)pde;
6719 npde = opde & ~mask;
6721 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6725 * Map a set of physical memory pages into the kernel virtual
6726 * address space. Return a pointer to where it is mapped. This
6727 * routine is intended to be used for mapping device memory,
6731 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6733 struct pmap_preinit_mapping *ppim;
6734 vm_offset_t va, offset;
6738 offset = pa & PAGE_MASK;
6739 size = round_page(offset + size);
6740 pa = trunc_page(pa);
6742 if (!pmap_initialized) {
6744 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6745 ppim = pmap_preinit_mapping + i;
6746 if (ppim->va == 0) {
6750 ppim->va = virtual_avail;
6751 virtual_avail += size;
6757 panic("%s: too many preinit mappings", __func__);
6760 * If we have a preinit mapping, re-use it.
6762 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6763 ppim = pmap_preinit_mapping + i;
6764 if (ppim->pa == pa && ppim->sz == size &&
6766 return ((void *)(ppim->va + offset));
6769 * If the specified range of physical addresses fits within
6770 * the direct map window, use the direct map.
6772 if (pa < dmaplimit && pa + size < dmaplimit) {
6773 va = PHYS_TO_DMAP(pa);
6774 if (!pmap_change_attr(va, size, mode))
6775 return ((void *)(va + offset));
6777 va = kva_alloc(size);
6779 panic("%s: Couldn't allocate KVA", __func__);
6781 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6782 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6783 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6784 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6785 return ((void *)(va + offset));
6789 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6792 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6796 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6799 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6803 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6805 struct pmap_preinit_mapping *ppim;
6809 /* If we gave a direct map region in pmap_mapdev, do nothing */
6810 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6812 offset = va & PAGE_MASK;
6813 size = round_page(offset + size);
6814 va = trunc_page(va);
6815 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6816 ppim = pmap_preinit_mapping + i;
6817 if (ppim->va == va && ppim->sz == size) {
6818 if (pmap_initialized)
6824 if (va + size == virtual_avail)
6829 if (pmap_initialized)
6834 * Tries to demote a 1GB page mapping.
6837 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6839 pdp_entry_t newpdpe, oldpdpe;
6840 pd_entry_t *firstpde, newpde, *pde;
6841 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6845 PG_A = pmap_accessed_bit(pmap);
6846 PG_M = pmap_modified_bit(pmap);
6847 PG_V = pmap_valid_bit(pmap);
6848 PG_RW = pmap_rw_bit(pmap);
6850 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6852 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6853 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6854 if ((pdpg = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6855 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6856 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6857 " in pmap %p", va, pmap);
6860 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
6861 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
6862 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6863 KASSERT((oldpdpe & PG_A) != 0,
6864 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6865 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6866 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
6870 * Initialize the page directory page.
6872 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
6878 * Demote the mapping.
6883 * Invalidate a stale recursive mapping of the page directory page.
6885 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
6887 pmap_pdpe_demotions++;
6888 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
6889 " in pmap %p", va, pmap);
6894 * Sets the memory attribute for the specified page.
6897 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6900 m->md.pat_mode = ma;
6903 * If "m" is a normal page, update its direct mapping. This update
6904 * can be relied upon to perform any cache operations that are
6905 * required for data coherence.
6907 if ((m->flags & PG_FICTITIOUS) == 0 &&
6908 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6910 panic("memory attribute change on the direct map failed");
6914 * Changes the specified virtual address range's memory type to that given by
6915 * the parameter "mode". The specified virtual address range must be
6916 * completely contained within either the direct map or the kernel map. If
6917 * the virtual address range is contained within the kernel map, then the
6918 * memory type for each of the corresponding ranges of the direct map is also
6919 * changed. (The corresponding ranges of the direct map are those ranges that
6920 * map the same physical pages as the specified virtual address range.) These
6921 * changes to the direct map are necessary because Intel describes the
6922 * behavior of their processors as "undefined" if two or more mappings to the
6923 * same physical page have different memory types.
6925 * Returns zero if the change completed successfully, and either EINVAL or
6926 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6927 * of the virtual address range was not mapped, and ENOMEM is returned if
6928 * there was insufficient memory available to complete the change. In the
6929 * latter case, the memory type may have been changed on some part of the
6930 * virtual address range or the direct map.
6933 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6937 PMAP_LOCK(kernel_pmap);
6938 error = pmap_change_attr_locked(va, size, mode);
6939 PMAP_UNLOCK(kernel_pmap);
6944 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
6946 vm_offset_t base, offset, tmpva;
6947 vm_paddr_t pa_start, pa_end, pa_end1;
6951 int cache_bits_pte, cache_bits_pde, error;
6954 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6955 base = trunc_page(va);
6956 offset = va & PAGE_MASK;
6957 size = round_page(offset + size);
6960 * Only supported on kernel virtual addresses, including the direct
6961 * map but excluding the recursive map.
6963 if (base < DMAP_MIN_ADDRESS)
6966 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
6967 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
6971 * Pages that aren't mapped aren't supported. Also break down 2MB pages
6972 * into 4KB pages if required.
6974 for (tmpva = base; tmpva < base + size; ) {
6975 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6976 if (pdpe == NULL || *pdpe == 0)
6978 if (*pdpe & PG_PS) {
6980 * If the current 1GB page already has the required
6981 * memory type, then we need not demote this page. Just
6982 * increment tmpva to the next 1GB page frame.
6984 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
6985 tmpva = trunc_1gpage(tmpva) + NBPDP;
6990 * If the current offset aligns with a 1GB page frame
6991 * and there is at least 1GB left within the range, then
6992 * we need not break down this page into 2MB pages.
6994 if ((tmpva & PDPMASK) == 0 &&
6995 tmpva + PDPMASK < base + size) {
6999 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
7002 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7007 * If the current 2MB page already has the required
7008 * memory type, then we need not demote this page. Just
7009 * increment tmpva to the next 2MB page frame.
7011 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
7012 tmpva = trunc_2mpage(tmpva) + NBPDR;
7017 * If the current offset aligns with a 2MB page frame
7018 * and there is at least 2MB left within the range, then
7019 * we need not break down this page into 4KB pages.
7021 if ((tmpva & PDRMASK) == 0 &&
7022 tmpva + PDRMASK < base + size) {
7026 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
7029 pte = pmap_pde_to_pte(pde, tmpva);
7037 * Ok, all the pages exist, so run through them updating their
7038 * cache mode if required.
7040 pa_start = pa_end = 0;
7041 for (tmpva = base; tmpva < base + size; ) {
7042 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7043 if (*pdpe & PG_PS) {
7044 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
7045 pmap_pde_attr(pdpe, cache_bits_pde,
7049 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7050 (*pdpe & PG_PS_FRAME) < dmaplimit) {
7051 if (pa_start == pa_end) {
7052 /* Start physical address run. */
7053 pa_start = *pdpe & PG_PS_FRAME;
7054 pa_end = pa_start + NBPDP;
7055 } else if (pa_end == (*pdpe & PG_PS_FRAME))
7058 /* Run ended, update direct map. */
7059 error = pmap_change_attr_locked(
7060 PHYS_TO_DMAP(pa_start),
7061 pa_end - pa_start, mode);
7064 /* Start physical address run. */
7065 pa_start = *pdpe & PG_PS_FRAME;
7066 pa_end = pa_start + NBPDP;
7069 tmpva = trunc_1gpage(tmpva) + NBPDP;
7072 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7074 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
7075 pmap_pde_attr(pde, cache_bits_pde,
7079 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7080 (*pde & PG_PS_FRAME) < dmaplimit) {
7081 if (pa_start == pa_end) {
7082 /* Start physical address run. */
7083 pa_start = *pde & PG_PS_FRAME;
7084 pa_end = pa_start + NBPDR;
7085 } else if (pa_end == (*pde & PG_PS_FRAME))
7088 /* Run ended, update direct map. */
7089 error = pmap_change_attr_locked(
7090 PHYS_TO_DMAP(pa_start),
7091 pa_end - pa_start, mode);
7094 /* Start physical address run. */
7095 pa_start = *pde & PG_PS_FRAME;
7096 pa_end = pa_start + NBPDR;
7099 tmpva = trunc_2mpage(tmpva) + NBPDR;
7101 pte = pmap_pde_to_pte(pde, tmpva);
7102 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
7103 pmap_pte_attr(pte, cache_bits_pte,
7107 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7108 (*pte & PG_FRAME) < dmaplimit) {
7109 if (pa_start == pa_end) {
7110 /* Start physical address run. */
7111 pa_start = *pte & PG_FRAME;
7112 pa_end = pa_start + PAGE_SIZE;
7113 } else if (pa_end == (*pte & PG_FRAME))
7114 pa_end += PAGE_SIZE;
7116 /* Run ended, update direct map. */
7117 error = pmap_change_attr_locked(
7118 PHYS_TO_DMAP(pa_start),
7119 pa_end - pa_start, mode);
7122 /* Start physical address run. */
7123 pa_start = *pte & PG_FRAME;
7124 pa_end = pa_start + PAGE_SIZE;
7130 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
7131 pa_end1 = MIN(pa_end, dmaplimit);
7132 if (pa_start != pa_end1)
7133 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
7134 pa_end1 - pa_start, mode);
7138 * Flush CPU caches if required to make sure any data isn't cached that
7139 * shouldn't be, etc.
7142 pmap_invalidate_range(kernel_pmap, base, tmpva);
7143 pmap_invalidate_cache_range(base, tmpva, FALSE);
7149 * Demotes any mapping within the direct map region that covers more than the
7150 * specified range of physical addresses. This range's size must be a power
7151 * of two and its starting address must be a multiple of its size. Since the
7152 * demotion does not change any attributes of the mapping, a TLB invalidation
7153 * is not mandatory. The caller may, however, request a TLB invalidation.
7156 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
7165 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
7166 KASSERT((base & (len - 1)) == 0,
7167 ("pmap_demote_DMAP: base is not a multiple of len"));
7168 if (len < NBPDP && base < dmaplimit) {
7169 va = PHYS_TO_DMAP(base);
7171 PMAP_LOCK(kernel_pmap);
7172 pdpe = pmap_pdpe(kernel_pmap, va);
7173 if ((*pdpe & X86_PG_V) == 0)
7174 panic("pmap_demote_DMAP: invalid PDPE");
7175 if ((*pdpe & PG_PS) != 0) {
7176 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
7177 panic("pmap_demote_DMAP: PDPE failed");
7181 pde = pmap_pdpe_to_pde(pdpe, va);
7182 if ((*pde & X86_PG_V) == 0)
7183 panic("pmap_demote_DMAP: invalid PDE");
7184 if ((*pde & PG_PS) != 0) {
7185 if (!pmap_demote_pde(kernel_pmap, pde, va))
7186 panic("pmap_demote_DMAP: PDE failed");
7190 if (changed && invalidate)
7191 pmap_invalidate_page(kernel_pmap, va);
7192 PMAP_UNLOCK(kernel_pmap);
7197 * perform the pmap work for mincore
7200 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
7203 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
7207 PG_A = pmap_accessed_bit(pmap);
7208 PG_M = pmap_modified_bit(pmap);
7209 PG_V = pmap_valid_bit(pmap);
7210 PG_RW = pmap_rw_bit(pmap);
7214 pdep = pmap_pde(pmap, addr);
7215 if (pdep != NULL && (*pdep & PG_V)) {
7216 if (*pdep & PG_PS) {
7218 /* Compute the physical address of the 4KB page. */
7219 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
7221 val = MINCORE_SUPER;
7223 pte = *pmap_pde_to_pte(pdep, addr);
7224 pa = pte & PG_FRAME;
7232 if ((pte & PG_V) != 0) {
7233 val |= MINCORE_INCORE;
7234 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7235 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
7236 if ((pte & PG_A) != 0)
7237 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
7239 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
7240 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
7241 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
7242 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
7243 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
7246 PA_UNLOCK_COND(*locked_pa);
7252 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
7254 uint32_t gen, new_gen, pcid_next;
7256 CRITICAL_ASSERT(curthread);
7257 gen = PCPU_GET(pcid_gen);
7258 if (!pti && (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN ||
7259 pmap->pm_pcids[cpuid].pm_gen == gen))
7260 return (CR3_PCID_SAVE);
7261 pcid_next = PCPU_GET(pcid_next);
7262 KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
7263 (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
7264 ("cpu %d pcid_next %#x", cpuid, pcid_next));
7265 if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
7266 (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
7270 PCPU_SET(pcid_gen, new_gen);
7271 pcid_next = PMAP_PCID_KERN + 1;
7275 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
7276 pmap->pm_pcids[cpuid].pm_gen = new_gen;
7277 PCPU_SET(pcid_next, pcid_next + 1);
7282 pmap_activate_sw(struct thread *td)
7284 pmap_t oldpmap, pmap;
7285 struct invpcid_descr d;
7286 uint64_t cached, cr3, kcr3, ucr3;
7290 oldpmap = PCPU_GET(curpmap);
7291 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7292 if (oldpmap == pmap)
7294 cpuid = PCPU_GET(cpuid);
7296 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7298 CPU_SET(cpuid, &pmap->pm_active);
7301 if (pmap_pcid_enabled) {
7302 cached = pmap_pcid_alloc(pmap, cpuid);
7303 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
7304 pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
7305 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
7306 pmap->pm_pcids[cpuid].pm_pcid));
7307 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
7308 pmap == kernel_pmap,
7309 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
7310 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
7313 * If the INVPCID instruction is not available,
7314 * invltlb_pcid_handler() is used for handle
7315 * invalidate_all IPI, which checks for curpmap ==
7316 * smp_tlb_pmap. Below operations sequence has a
7317 * window where %CR3 is loaded with the new pmap's
7318 * PML4 address, but curpmap value is not yet updated.
7319 * This causes invltlb IPI handler, called between the
7320 * updates, to execute as NOP, which leaves stale TLB
7323 * Note that the most typical use of
7324 * pmap_activate_sw(), from the context switch, is
7325 * immune to this race, because interrupts are
7326 * disabled (while the thread lock is owned), and IPI
7327 * happends after curpmap is updated. Protect other
7328 * callers in a similar way, by disabling interrupts
7329 * around the %cr3 register reload and curpmap
7333 rflags = intr_disable();
7335 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
7336 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
7339 PCPU_INC(pm_save_cnt);
7341 PCPU_SET(curpmap, pmap);
7343 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid;
7344 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[cpuid].pm_pcid |
7348 * Manually invalidate translations cached
7349 * from the user page table, which are not
7350 * flushed by reload of cr3 with the kernel
7351 * page table pointer above.
7353 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
7354 if (invpcid_works) {
7355 d.pcid = PMAP_PCID_USER_PT |
7356 pmap->pm_pcids[cpuid].pm_pcid;
7359 invpcid(&d, INVPCID_CTX);
7361 pmap_pti_pcid_invalidate(ucr3, kcr3);
7365 PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
7366 PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
7369 intr_restore(rflags);
7370 } else if (cr3 != pmap->pm_cr3) {
7371 load_cr3(pmap->pm_cr3);
7372 PCPU_SET(curpmap, pmap);
7374 PCPU_SET(kcr3, pmap->pm_cr3);
7375 PCPU_SET(ucr3, pmap->pm_ucr3);
7379 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
7381 CPU_CLR(cpuid, &oldpmap->pm_active);
7386 pmap_activate(struct thread *td)
7390 pmap_activate_sw(td);
7395 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
7400 * Increase the starting virtual address of the given mapping if a
7401 * different alignment might result in more superpage mappings.
7404 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7405 vm_offset_t *addr, vm_size_t size)
7407 vm_offset_t superpage_offset;
7411 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7412 offset += ptoa(object->pg_color);
7413 superpage_offset = offset & PDRMASK;
7414 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
7415 (*addr & PDRMASK) == superpage_offset)
7417 if ((*addr & PDRMASK) < superpage_offset)
7418 *addr = (*addr & ~PDRMASK) + superpage_offset;
7420 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
7424 static unsigned long num_dirty_emulations;
7425 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
7426 &num_dirty_emulations, 0, NULL);
7428 static unsigned long num_accessed_emulations;
7429 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
7430 &num_accessed_emulations, 0, NULL);
7432 static unsigned long num_superpage_accessed_emulations;
7433 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7434 &num_superpage_accessed_emulations, 0, NULL);
7436 static unsigned long ad_emulation_superpage_promotions;
7437 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7438 &ad_emulation_superpage_promotions, 0, NULL);
7439 #endif /* INVARIANTS */
7442 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7445 struct rwlock *lock;
7446 #if VM_NRESERVLEVEL > 0
7450 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7452 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7453 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7455 if (!pmap_emulate_ad_bits(pmap))
7458 PG_A = pmap_accessed_bit(pmap);
7459 PG_M = pmap_modified_bit(pmap);
7460 PG_V = pmap_valid_bit(pmap);
7461 PG_RW = pmap_rw_bit(pmap);
7467 pde = pmap_pde(pmap, va);
7468 if (pde == NULL || (*pde & PG_V) == 0)
7471 if ((*pde & PG_PS) != 0) {
7472 if (ftype == VM_PROT_READ) {
7474 atomic_add_long(&num_superpage_accessed_emulations, 1);
7482 pte = pmap_pde_to_pte(pde, va);
7483 if ((*pte & PG_V) == 0)
7486 if (ftype == VM_PROT_WRITE) {
7487 if ((*pte & PG_RW) == 0)
7490 * Set the modified and accessed bits simultaneously.
7492 * Intel EPT PTEs that do software emulation of A/D bits map
7493 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7494 * An EPT misconfiguration is triggered if the PTE is writable
7495 * but not readable (WR=10). This is avoided by setting PG_A
7496 * and PG_M simultaneously.
7498 *pte |= PG_M | PG_A;
7503 #if VM_NRESERVLEVEL > 0
7504 /* try to promote the mapping */
7505 if (va < VM_MAXUSER_ADDRESS)
7506 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7510 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7512 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7513 pmap_ps_enabled(pmap) &&
7514 (m->flags & PG_FICTITIOUS) == 0 &&
7515 vm_reserv_level_iffullpop(m) == 0) {
7516 pmap_promote_pde(pmap, pde, va, &lock);
7518 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7524 if (ftype == VM_PROT_WRITE)
7525 atomic_add_long(&num_dirty_emulations, 1);
7527 atomic_add_long(&num_accessed_emulations, 1);
7529 rv = 0; /* success */
7538 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7543 pt_entry_t *pte, PG_V;
7547 PG_V = pmap_valid_bit(pmap);
7550 pml4 = pmap_pml4e(pmap, va);
7552 if ((*pml4 & PG_V) == 0)
7555 pdp = pmap_pml4e_to_pdpe(pml4, va);
7557 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7560 pde = pmap_pdpe_to_pde(pdp, va);
7562 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7565 pte = pmap_pde_to_pte(pde, va);
7574 * Get the kernel virtual address of a set of physical pages. If there are
7575 * physical addresses not covered by the DMAP perform a transient mapping
7576 * that will be removed when calling pmap_unmap_io_transient.
7578 * \param page The pages the caller wishes to obtain the virtual
7579 * address on the kernel memory map.
7580 * \param vaddr On return contains the kernel virtual memory address
7581 * of the pages passed in the page parameter.
7582 * \param count Number of pages passed in.
7583 * \param can_fault TRUE if the thread using the mapped pages can take
7584 * page faults, FALSE otherwise.
7586 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7587 * finished or FALSE otherwise.
7591 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7592 boolean_t can_fault)
7595 boolean_t needs_mapping;
7597 int cache_bits, error, i;
7600 * Allocate any KVA space that we need, this is done in a separate
7601 * loop to prevent calling vmem_alloc while pinned.
7603 needs_mapping = FALSE;
7604 for (i = 0; i < count; i++) {
7605 paddr = VM_PAGE_TO_PHYS(page[i]);
7606 if (__predict_false(paddr >= dmaplimit)) {
7607 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7608 M_BESTFIT | M_WAITOK, &vaddr[i]);
7609 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7610 needs_mapping = TRUE;
7612 vaddr[i] = PHYS_TO_DMAP(paddr);
7616 /* Exit early if everything is covered by the DMAP */
7621 * NB: The sequence of updating a page table followed by accesses
7622 * to the corresponding pages used in the !DMAP case is subject to
7623 * the situation described in the "AMD64 Architecture Programmer's
7624 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7625 * Coherency Considerations". Therefore, issuing the INVLPG right
7626 * after modifying the PTE bits is crucial.
7630 for (i = 0; i < count; i++) {
7631 paddr = VM_PAGE_TO_PHYS(page[i]);
7632 if (paddr >= dmaplimit) {
7635 * Slow path, since we can get page faults
7636 * while mappings are active don't pin the
7637 * thread to the CPU and instead add a global
7638 * mapping visible to all CPUs.
7640 pmap_qenter(vaddr[i], &page[i], 1);
7642 pte = vtopte(vaddr[i]);
7643 cache_bits = pmap_cache_bits(kernel_pmap,
7644 page[i]->md.pat_mode, 0);
7645 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7652 return (needs_mapping);
7656 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7657 boolean_t can_fault)
7664 for (i = 0; i < count; i++) {
7665 paddr = VM_PAGE_TO_PHYS(page[i]);
7666 if (paddr >= dmaplimit) {
7668 pmap_qremove(vaddr[i], 1);
7669 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7675 pmap_quick_enter_page(vm_page_t m)
7679 paddr = VM_PAGE_TO_PHYS(m);
7680 if (paddr < dmaplimit)
7681 return (PHYS_TO_DMAP(paddr));
7682 mtx_lock_spin(&qframe_mtx);
7683 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7684 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7685 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7690 pmap_quick_remove_page(vm_offset_t addr)
7695 pte_store(vtopte(qframe), 0);
7697 mtx_unlock_spin(&qframe_mtx);
7701 pmap_pti_alloc_page(void)
7705 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7706 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_NOBUSY |
7707 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
7712 pmap_pti_free_page(vm_page_t m)
7715 KASSERT(m->wire_count > 0, ("page %p not wired", m));
7716 if (!vm_page_unwire_noq(m))
7718 vm_page_free_zero(m);
7732 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
7733 VM_OBJECT_WLOCK(pti_obj);
7734 pml4_pg = pmap_pti_alloc_page();
7735 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
7736 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
7737 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
7738 pdpe = pmap_pti_pdpe(va);
7739 pmap_pti_wire_pte(pdpe);
7741 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
7742 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
7743 pmap_pti_add_kva_locked((vm_offset_t)gdt, (vm_offset_t)gdt +
7744 sizeof(struct user_segment_descriptor) * NGDT * MAXCPU, false);
7745 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
7746 sizeof(struct gate_descriptor) * NIDT, false);
7747 pmap_pti_add_kva_locked((vm_offset_t)common_tss,
7748 (vm_offset_t)common_tss + sizeof(struct amd64tss) * MAXCPU, false);
7750 /* Doublefault stack IST 1 */
7751 va = common_tss[i].tss_ist1;
7752 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7753 /* NMI stack IST 2 */
7754 va = common_tss[i].tss_ist2 + sizeof(struct nmi_pcpu);
7755 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7756 /* MC# stack IST 3 */
7757 va = common_tss[i].tss_ist3 + sizeof(struct nmi_pcpu);
7758 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7760 pmap_pti_add_kva_locked((vm_offset_t)kernphys + KERNBASE,
7761 (vm_offset_t)etext, true);
7762 pti_finalized = true;
7763 VM_OBJECT_WUNLOCK(pti_obj);
7765 SYSINIT(pmap_pti, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_pti_init, NULL);
7767 static pdp_entry_t *
7768 pmap_pti_pdpe(vm_offset_t va)
7770 pml4_entry_t *pml4e;
7773 vm_pindex_t pml4_idx;
7776 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7778 pml4_idx = pmap_pml4e_index(va);
7779 pml4e = &pti_pml4[pml4_idx];
7783 panic("pml4 alloc after finalization\n");
7784 m = pmap_pti_alloc_page();
7786 pmap_pti_free_page(m);
7787 mphys = *pml4e & ~PAGE_MASK;
7789 mphys = VM_PAGE_TO_PHYS(m);
7790 *pml4e = mphys | X86_PG_RW | X86_PG_V;
7793 mphys = *pml4e & ~PAGE_MASK;
7795 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
7800 pmap_pti_wire_pte(void *pte)
7804 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7805 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7810 pmap_pti_unwire_pde(void *pde, bool only_ref)
7814 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7815 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
7816 MPASS(m->wire_count > 0);
7817 MPASS(only_ref || m->wire_count > 1);
7818 pmap_pti_free_page(m);
7822 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
7827 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7828 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7829 MPASS(m->wire_count > 0);
7830 if (pmap_pti_free_page(m)) {
7831 pde = pmap_pti_pde(va);
7832 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
7834 pmap_pti_unwire_pde(pde, false);
7839 pmap_pti_pde(vm_offset_t va)
7847 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7849 pdpe = pmap_pti_pdpe(va);
7851 m = pmap_pti_alloc_page();
7853 pmap_pti_free_page(m);
7854 MPASS((*pdpe & X86_PG_PS) == 0);
7855 mphys = *pdpe & ~PAGE_MASK;
7857 mphys = VM_PAGE_TO_PHYS(m);
7858 *pdpe = mphys | X86_PG_RW | X86_PG_V;
7861 MPASS((*pdpe & X86_PG_PS) == 0);
7862 mphys = *pdpe & ~PAGE_MASK;
7865 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
7866 pd_idx = pmap_pde_index(va);
7872 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
7879 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7881 pde = pmap_pti_pde(va);
7882 if (unwire_pde != NULL) {
7884 pmap_pti_wire_pte(pde);
7887 m = pmap_pti_alloc_page();
7889 pmap_pti_free_page(m);
7890 MPASS((*pde & X86_PG_PS) == 0);
7891 mphys = *pde & ~(PAGE_MASK | pg_nx);
7893 mphys = VM_PAGE_TO_PHYS(m);
7894 *pde = mphys | X86_PG_RW | X86_PG_V;
7895 if (unwire_pde != NULL)
7896 *unwire_pde = false;
7899 MPASS((*pde & X86_PG_PS) == 0);
7900 mphys = *pde & ~(PAGE_MASK | pg_nx);
7903 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
7904 pte += pmap_pte_index(va);
7910 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
7914 pt_entry_t *pte, ptev;
7917 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7919 sva = trunc_page(sva);
7920 MPASS(sva > VM_MAXUSER_ADDRESS);
7921 eva = round_page(eva);
7923 for (; sva < eva; sva += PAGE_SIZE) {
7924 pte = pmap_pti_pte(sva, &unwire_pde);
7925 pa = pmap_kextract(sva);
7926 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A |
7927 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
7928 VM_MEMATTR_DEFAULT, FALSE);
7930 pte_store(pte, ptev);
7931 pmap_pti_wire_pte(pte);
7933 KASSERT(!pti_finalized,
7934 ("pti overlap after fin %#lx %#lx %#lx",
7936 KASSERT(*pte == ptev,
7937 ("pti non-identical pte after fin %#lx %#lx %#lx",
7941 pde = pmap_pti_pde(sva);
7942 pmap_pti_unwire_pde(pde, true);
7948 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
7953 VM_OBJECT_WLOCK(pti_obj);
7954 pmap_pti_add_kva_locked(sva, eva, exec);
7955 VM_OBJECT_WUNLOCK(pti_obj);
7959 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
7966 sva = rounddown2(sva, PAGE_SIZE);
7967 MPASS(sva > VM_MAXUSER_ADDRESS);
7968 eva = roundup2(eva, PAGE_SIZE);
7970 VM_OBJECT_WLOCK(pti_obj);
7971 for (va = sva; va < eva; va += PAGE_SIZE) {
7972 pte = pmap_pti_pte(va, NULL);
7973 KASSERT((*pte & X86_PG_V) != 0,
7974 ("invalid pte va %#lx pte %#lx pt %#lx", va,
7975 (u_long)pte, *pte));
7977 pmap_pti_unwire_pte(pte, va);
7979 pmap_invalidate_range(kernel_pmap, sva, eva);
7980 VM_OBJECT_WUNLOCK(pti_obj);
7983 #include "opt_ddb.h"
7985 #include <sys/kdb.h>
7986 #include <ddb/ddb.h>
7988 DB_SHOW_COMMAND(pte, pmap_print_pte)
7994 pt_entry_t *pte, PG_V;
7998 db_printf("show pte addr\n");
8001 va = (vm_offset_t)addr;
8003 if (kdb_thread != NULL)
8004 pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
8006 pmap = PCPU_GET(curpmap);
8008 PG_V = pmap_valid_bit(pmap);
8009 pml4 = pmap_pml4e(pmap, va);
8010 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
8011 if ((*pml4 & PG_V) == 0) {
8015 pdp = pmap_pml4e_to_pdpe(pml4, va);
8016 db_printf(" pdpe %#016lx", *pdp);
8017 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
8021 pde = pmap_pdpe_to_pde(pdp, va);
8022 db_printf(" pde %#016lx", *pde);
8023 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
8027 pte = pmap_pde_to_pte(pde, va);
8028 db_printf(" pte %#016lx\n", *pte);
8031 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
8036 a = (vm_paddr_t)addr;
8037 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
8039 db_printf("show phys2dmap addr\n");