2 * Copyright (c) 1991 Regents of the University of California.
4 * Copyright (c) 1994 John S. Dyson
6 * Copyright (c) 1994 David Greenman
8 * Copyright (c) 2003 Peter Wemm
10 * Copyright (c) 2005-2010 Alan L. Cox <alc@cs.rice.edu>
11 * All rights reserved.
12 * Copyright (c) 2014-2018 The FreeBSD Foundation
13 * All rights reserved.
15 * This code is derived from software contributed to Berkeley by
16 * the Systems Programming Group of the University of Utah Computer
17 * Science Department and William Jolitz of UUNET Technologies Inc.
19 * Portions of this software were developed by
20 * Konstantin Belousov <kib@FreeBSD.org> under sponsorship from
21 * the FreeBSD Foundation.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 * must display the following acknowledgement:
33 * This product includes software developed by the University of
34 * California, Berkeley and its contributors.
35 * 4. Neither the name of the University nor the names of its contributors
36 * may be used to endorse or promote products derived from this software
37 * without specific prior written permission.
39 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
40 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
42 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
43 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
44 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
45 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
46 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
47 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
48 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * from: @(#)pmap.c 7.7 (Berkeley) 5/12/91
54 * Copyright (c) 2003 Networks Associates Technology, Inc.
55 * All rights reserved.
57 * This software was developed for the FreeBSD Project by Jake Burkholder,
58 * Safeport Network Services, and Network Associates Laboratories, the
59 * Security Research Division of Network Associates, Inc. under
60 * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
61 * CHATS research program.
63 * Redistribution and use in source and binary forms, with or without
64 * modification, are permitted provided that the following conditions
66 * 1. Redistributions of source code must retain the above copyright
67 * notice, this list of conditions and the following disclaimer.
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in the
70 * documentation and/or other materials provided with the distribution.
72 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
73 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
74 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
75 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
76 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
77 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
78 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
79 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
80 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
81 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
85 #define AMD64_NPT_AWARE
87 #include <sys/cdefs.h>
88 __FBSDID("$FreeBSD$");
91 * Manages physical address maps.
93 * Since the information managed by this module is
94 * also stored by the logical address mapping module,
95 * this module may throw away valid virtual-to-physical
96 * mappings at almost any time. However, invalidations
97 * of virtual-to-physical mappings must be done as
100 * In order to cope with hardware architectures which
101 * make virtual-to-physical map invalidates expensive,
102 * this module may delay invalidate or reduced protection
103 * operations until such time as they are actually
104 * necessary. This module is given full information as
105 * to which processors are currently using which maps,
106 * and to when physical maps must be made correct.
109 #include "opt_pmap.h"
112 #include <sys/param.h>
113 #include <sys/bitstring.h>
115 #include <sys/systm.h>
116 #include <sys/kernel.h>
118 #include <sys/lock.h>
119 #include <sys/malloc.h>
120 #include <sys/mman.h>
121 #include <sys/mutex.h>
122 #include <sys/proc.h>
123 #include <sys/rwlock.h>
125 #include <sys/turnstile.h>
126 #include <sys/vmem.h>
127 #include <sys/vmmeter.h>
128 #include <sys/sched.h>
129 #include <sys/sysctl.h>
133 #include <vm/vm_param.h>
134 #include <vm/vm_kern.h>
135 #include <vm/vm_page.h>
136 #include <vm/vm_map.h>
137 #include <vm/vm_object.h>
138 #include <vm/vm_extern.h>
139 #include <vm/vm_pageout.h>
140 #include <vm/vm_pager.h>
141 #include <vm/vm_phys.h>
142 #include <vm/vm_radix.h>
143 #include <vm/vm_reserv.h>
146 #include <machine/intr_machdep.h>
147 #include <x86/apicvar.h>
148 #include <machine/cpu.h>
149 #include <machine/cputypes.h>
150 #include <machine/md_var.h>
151 #include <machine/pcb.h>
152 #include <machine/specialreg.h>
154 #include <machine/smp.h>
156 #include <machine/tss.h>
158 static __inline boolean_t
159 pmap_type_guest(pmap_t pmap)
162 return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
165 static __inline boolean_t
166 pmap_emulate_ad_bits(pmap_t pmap)
169 return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
172 static __inline pt_entry_t
173 pmap_valid_bit(pmap_t pmap)
177 switch (pmap->pm_type) {
183 if (pmap_emulate_ad_bits(pmap))
184 mask = EPT_PG_EMUL_V;
189 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
195 static __inline pt_entry_t
196 pmap_rw_bit(pmap_t pmap)
200 switch (pmap->pm_type) {
206 if (pmap_emulate_ad_bits(pmap))
207 mask = EPT_PG_EMUL_RW;
212 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
218 static pt_entry_t pg_g;
220 static __inline pt_entry_t
221 pmap_global_bit(pmap_t pmap)
225 switch (pmap->pm_type) {
234 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
240 static __inline pt_entry_t
241 pmap_accessed_bit(pmap_t pmap)
245 switch (pmap->pm_type) {
251 if (pmap_emulate_ad_bits(pmap))
257 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
263 static __inline pt_entry_t
264 pmap_modified_bit(pmap_t pmap)
268 switch (pmap->pm_type) {
274 if (pmap_emulate_ad_bits(pmap))
280 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
286 extern struct pcpu __pcpu[];
288 #if !defined(DIAGNOSTIC)
289 #ifdef __GNUC_GNU_INLINE__
290 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
292 #define PMAP_INLINE extern inline
299 #define PV_STAT(x) do { x ; } while (0)
301 #define PV_STAT(x) do { } while (0)
304 #define pa_index(pa) ((pa) >> PDRSHIFT)
305 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
307 #define NPV_LIST_LOCKS MAXCPU
309 #define PHYS_TO_PV_LIST_LOCK(pa) \
310 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
312 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
313 struct rwlock **_lockp = (lockp); \
314 struct rwlock *_new_lock; \
316 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
317 if (_new_lock != *_lockp) { \
318 if (*_lockp != NULL) \
319 rw_wunlock(*_lockp); \
320 *_lockp = _new_lock; \
325 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
326 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
328 #define RELEASE_PV_LIST_LOCK(lockp) do { \
329 struct rwlock **_lockp = (lockp); \
331 if (*_lockp != NULL) { \
332 rw_wunlock(*_lockp); \
337 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
338 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
340 struct pmap kernel_pmap_store;
342 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
343 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
346 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
347 "Number of kernel page table pages allocated on bootup");
350 vm_paddr_t dmaplimit;
351 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
354 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
356 static int pat_works = 1;
357 SYSCTL_INT(_vm_pmap, OID_AUTO, pat_works, CTLFLAG_RD, &pat_works, 1,
358 "Is page attribute table fully functional?");
360 static int pg_ps_enabled = 1;
361 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
362 &pg_ps_enabled, 0, "Are large page mappings enabled?");
364 #define PAT_INDEX_SIZE 8
365 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
367 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
368 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
369 u_int64_t KPDPphys; /* phys addr of kernel level 3 */
370 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
372 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
373 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
374 static int ndmpdpphys; /* number of DMPDPphys pages */
377 * pmap_mapdev support pre initialization (i.e. console)
379 #define PMAP_PREINIT_MAPPING_COUNT 8
380 static struct pmap_preinit_mapping {
385 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
386 static int pmap_initialized;
389 * Data for the pv entry allocation mechanism.
390 * Updates to pv_invl_gen are protected by the pv_list_locks[]
391 * elements, but reads are not.
393 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
394 static struct mtx pv_chunks_mutex;
395 static struct rwlock pv_list_locks[NPV_LIST_LOCKS];
396 static u_long pv_invl_gen[NPV_LIST_LOCKS];
397 static struct md_page *pv_table;
398 static struct md_page pv_dummy;
401 * All those kernel PT submaps that BSD is so fond of
403 pt_entry_t *CMAP1 = NULL;
405 static vm_offset_t qframe = 0;
406 static struct mtx qframe_mtx;
408 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
410 int pmap_pcid_enabled = 1;
411 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
412 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
413 int invpcid_works = 0;
414 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
415 "Is the invpcid instruction available ?");
418 SYSCTL_INT(_vm_pmap, OID_AUTO, pti, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
420 "Page Table Isolation enabled");
421 static vm_object_t pti_obj;
422 static pml4_entry_t *pti_pml4;
423 static vm_pindex_t pti_pg_idx;
424 static bool pti_finalized;
427 pmap_pcid_save_cnt_proc(SYSCTL_HANDLER_ARGS)
434 res += cpuid_to_pcpu[i]->pc_pm_save_cnt;
436 return (sysctl_handle_64(oidp, &res, 0, req));
438 SYSCTL_PROC(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLTYPE_U64 | CTLFLAG_RW |
439 CTLFLAG_MPSAFE, NULL, 0, pmap_pcid_save_cnt_proc, "QU",
440 "Count of saved TLB context on switch");
442 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
443 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
444 static struct mtx invl_gen_mtx;
445 static u_long pmap_invl_gen = 0;
446 /* Fake lock object to satisfy turnstiles interface. */
447 static struct lock_object invl_gen_ts = {
455 return (curthread->td_md.md_invl_gen.gen == 0);
458 #define PMAP_ASSERT_NOT_IN_DI() \
459 KASSERT(pmap_not_in_di(), ("DI already started"))
462 * Start a new Delayed Invalidation (DI) block of code, executed by
463 * the current thread. Within a DI block, the current thread may
464 * destroy both the page table and PV list entries for a mapping and
465 * then release the corresponding PV list lock before ensuring that
466 * the mapping is flushed from the TLBs of any processors with the
470 pmap_delayed_invl_started(void)
472 struct pmap_invl_gen *invl_gen;
475 invl_gen = &curthread->td_md.md_invl_gen;
476 PMAP_ASSERT_NOT_IN_DI();
477 mtx_lock(&invl_gen_mtx);
478 if (LIST_EMPTY(&pmap_invl_gen_tracker))
479 currgen = pmap_invl_gen;
481 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
482 invl_gen->gen = currgen + 1;
483 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
484 mtx_unlock(&invl_gen_mtx);
488 * Finish the DI block, previously started by the current thread. All
489 * required TLB flushes for the pages marked by
490 * pmap_delayed_invl_page() must be finished before this function is
493 * This function works by bumping the global DI generation number to
494 * the generation number of the current thread's DI, unless there is a
495 * pending DI that started earlier. In the latter case, bumping the
496 * global DI generation number would incorrectly signal that the
497 * earlier DI had finished. Instead, this function bumps the earlier
498 * DI's generation number to match the generation number of the
499 * current thread's DI.
502 pmap_delayed_invl_finished(void)
504 struct pmap_invl_gen *invl_gen, *next;
505 struct turnstile *ts;
507 invl_gen = &curthread->td_md.md_invl_gen;
508 KASSERT(invl_gen->gen != 0, ("missed invl_started"));
509 mtx_lock(&invl_gen_mtx);
510 next = LIST_NEXT(invl_gen, link);
512 turnstile_chain_lock(&invl_gen_ts);
513 ts = turnstile_lookup(&invl_gen_ts);
514 pmap_invl_gen = invl_gen->gen;
516 turnstile_broadcast(ts, TS_SHARED_QUEUE);
517 turnstile_unpend(ts, TS_SHARED_LOCK);
519 turnstile_chain_unlock(&invl_gen_ts);
521 next->gen = invl_gen->gen;
523 LIST_REMOVE(invl_gen, link);
524 mtx_unlock(&invl_gen_mtx);
529 static long invl_wait;
530 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
531 "Number of times DI invalidation blocked pmap_remove_all/write");
535 pmap_delayed_invl_genp(vm_page_t m)
538 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
542 * Ensure that all currently executing DI blocks, that need to flush
543 * TLB for the given page m, actually flushed the TLB at the time the
544 * function returned. If the page m has an empty PV list and we call
545 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
546 * valid mapping for the page m in either its page table or TLB.
548 * This function works by blocking until the global DI generation
549 * number catches up with the generation number associated with the
550 * given page m and its PV list. Since this function's callers
551 * typically own an object lock and sometimes own a page lock, it
552 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
556 pmap_delayed_invl_wait(vm_page_t m)
558 struct turnstile *ts;
561 bool accounted = false;
564 m_gen = pmap_delayed_invl_genp(m);
565 while (*m_gen > pmap_invl_gen) {
568 atomic_add_long(&invl_wait, 1);
572 ts = turnstile_trywait(&invl_gen_ts);
573 if (*m_gen > pmap_invl_gen)
574 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
576 turnstile_cancel(ts);
581 * Mark the page m's PV list as participating in the current thread's
582 * DI block. Any threads concurrently using m's PV list to remove or
583 * restrict all mappings to m will wait for the current thread's DI
584 * block to complete before proceeding.
586 * The function works by setting the DI generation number for m's PV
587 * list to at least the DI generation number of the current thread.
588 * This forces a caller of pmap_delayed_invl_wait() to block until
589 * current thread calls pmap_delayed_invl_finished().
592 pmap_delayed_invl_page(vm_page_t m)
596 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
597 gen = curthread->td_md.md_invl_gen.gen;
600 m_gen = pmap_delayed_invl_genp(m);
608 static caddr_t crashdumpmap;
611 * Internal flags for pmap_enter()'s helper functions.
613 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
614 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
616 static void free_pv_chunk(struct pv_chunk *pc);
617 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
618 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
619 static int popcnt_pc_map_pq(uint64_t *map);
620 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
621 static void reserve_pv_entries(pmap_t pmap, int needed,
622 struct rwlock **lockp);
623 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
624 struct rwlock **lockp);
625 static bool pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
626 u_int flags, struct rwlock **lockp);
627 #if VM_NRESERVLEVEL > 0
628 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
629 struct rwlock **lockp);
631 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
632 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
635 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode);
636 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
637 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
638 vm_offset_t va, struct rwlock **lockp);
639 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
641 static bool pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
642 vm_prot_t prot, struct rwlock **lockp);
643 static int pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
644 u_int flags, vm_page_t m, struct rwlock **lockp);
645 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
646 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
647 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
648 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
649 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
651 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
652 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask);
653 #if VM_NRESERVLEVEL > 0
654 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
655 struct rwlock **lockp);
657 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
659 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
660 static void pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva,
662 static pdp_entry_t *pmap_pti_pdpe(vm_offset_t va);
663 static pd_entry_t *pmap_pti_pde(vm_offset_t va);
664 static void pmap_pti_wire_pte(void *pte);
665 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
666 struct spglist *free, struct rwlock **lockp);
667 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
668 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
669 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
670 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
671 struct spglist *free);
672 static bool pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
673 pd_entry_t *pde, struct spglist *free,
674 struct rwlock **lockp);
675 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
676 vm_page_t m, struct rwlock **lockp);
677 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
679 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
681 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
682 struct rwlock **lockp);
683 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
684 struct rwlock **lockp);
685 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
686 struct rwlock **lockp);
688 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
689 struct spglist *free);
690 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
692 /********************/
693 /* Inline functions */
694 /********************/
696 /* Return a non-clipped PD index for a given VA */
697 static __inline vm_pindex_t
698 pmap_pde_pindex(vm_offset_t va)
700 return (va >> PDRSHIFT);
704 /* Return a pointer to the PML4 slot that corresponds to a VA */
705 static __inline pml4_entry_t *
706 pmap_pml4e(pmap_t pmap, vm_offset_t va)
709 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
712 /* Return a pointer to the PDP slot that corresponds to a VA */
713 static __inline pdp_entry_t *
714 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
718 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
719 return (&pdpe[pmap_pdpe_index(va)]);
722 /* Return a pointer to the PDP slot that corresponds to a VA */
723 static __inline pdp_entry_t *
724 pmap_pdpe(pmap_t pmap, vm_offset_t va)
729 PG_V = pmap_valid_bit(pmap);
730 pml4e = pmap_pml4e(pmap, va);
731 if ((*pml4e & PG_V) == 0)
733 return (pmap_pml4e_to_pdpe(pml4e, va));
736 /* Return a pointer to the PD slot that corresponds to a VA */
737 static __inline pd_entry_t *
738 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
742 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
743 return (&pde[pmap_pde_index(va)]);
746 /* Return a pointer to the PD slot that corresponds to a VA */
747 static __inline pd_entry_t *
748 pmap_pde(pmap_t pmap, vm_offset_t va)
753 PG_V = pmap_valid_bit(pmap);
754 pdpe = pmap_pdpe(pmap, va);
755 if (pdpe == NULL || (*pdpe & PG_V) == 0)
757 return (pmap_pdpe_to_pde(pdpe, va));
760 /* Return a pointer to the PT slot that corresponds to a VA */
761 static __inline pt_entry_t *
762 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
766 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
767 return (&pte[pmap_pte_index(va)]);
770 /* Return a pointer to the PT slot that corresponds to a VA */
771 static __inline pt_entry_t *
772 pmap_pte(pmap_t pmap, vm_offset_t va)
777 PG_V = pmap_valid_bit(pmap);
778 pde = pmap_pde(pmap, va);
779 if (pde == NULL || (*pde & PG_V) == 0)
781 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
782 return ((pt_entry_t *)pde);
783 return (pmap_pde_to_pte(pde, va));
787 pmap_resident_count_inc(pmap_t pmap, int count)
790 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
791 pmap->pm_stats.resident_count += count;
795 pmap_resident_count_dec(pmap_t pmap, int count)
798 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
799 KASSERT(pmap->pm_stats.resident_count >= count,
800 ("pmap %p resident count underflow %ld %d", pmap,
801 pmap->pm_stats.resident_count, count));
802 pmap->pm_stats.resident_count -= count;
805 PMAP_INLINE pt_entry_t *
806 vtopte(vm_offset_t va)
808 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
810 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
812 return (PTmap + ((va >> PAGE_SHIFT) & mask));
815 static __inline pd_entry_t *
816 vtopde(vm_offset_t va)
818 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
820 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
822 return (PDmap + ((va >> PDRSHIFT) & mask));
826 allocpages(vm_paddr_t *firstaddr, int n)
831 bzero((void *)ret, n * PAGE_SIZE);
832 *firstaddr += n * PAGE_SIZE;
836 CTASSERT(powerof2(NDMPML4E));
838 /* number of kernel PDP slots */
839 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
842 nkpt_init(vm_paddr_t addr)
849 pt_pages = howmany(addr, 1 << PDRSHIFT);
850 pt_pages += NKPDPE(pt_pages);
853 * Add some slop beyond the bare minimum required for bootstrapping
856 * This is quite important when allocating KVA for kernel modules.
857 * The modules are required to be linked in the negative 2GB of
858 * the address space. If we run out of KVA in this region then
859 * pmap_growkernel() will need to allocate page table pages to map
860 * the entire 512GB of KVA space which is an unnecessary tax on
863 * Secondly, device memory mapped as part of setting up the low-
864 * level console(s) is taken from KVA, starting at virtual_avail.
865 * This is because cninit() is called after pmap_bootstrap() but
866 * before vm_init() and pmap_init(). 20MB for a frame buffer is
869 pt_pages += 32; /* 64MB additional slop. */
875 create_pagetables(vm_paddr_t *firstaddr)
877 int i, j, ndm1g, nkpdpe;
883 /* Allocate page table pages for the direct map */
884 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
885 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
887 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
888 if (ndmpdpphys > NDMPML4E) {
890 * Each NDMPML4E allows 512 GB, so limit to that,
891 * and then readjust ndmpdp and ndmpdpphys.
893 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
894 Maxmem = atop(NDMPML4E * NBPML4);
895 ndmpdpphys = NDMPML4E;
896 ndmpdp = NDMPML4E * NPDEPG;
898 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
900 if ((amd_feature & AMDID_PAGE1GB) != 0)
901 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
903 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
904 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
907 KPML4phys = allocpages(firstaddr, 1);
908 KPDPphys = allocpages(firstaddr, NKPML4E);
911 * Allocate the initial number of kernel page table pages required to
912 * bootstrap. We defer this until after all memory-size dependent
913 * allocations are done (e.g. direct map), so that we don't have to
914 * build in too much slop in our estimate.
916 * Note that when NKPML4E > 1, we have an empty page underneath
917 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
918 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
920 nkpt_init(*firstaddr);
921 nkpdpe = NKPDPE(nkpt);
923 KPTphys = allocpages(firstaddr, nkpt);
924 KPDphys = allocpages(firstaddr, nkpdpe);
926 /* Fill in the underlying page table pages */
927 /* Nominally read-only (but really R/W) from zero to physfree */
928 /* XXX not fully used, underneath 2M pages */
929 pt_p = (pt_entry_t *)KPTphys;
930 for (i = 0; ptoa(i) < *firstaddr; i++)
931 pt_p[i] = ptoa(i) | X86_PG_RW | X86_PG_V | pg_g;
933 /* Now map the page tables at their location within PTmap */
934 pd_p = (pd_entry_t *)KPDphys;
935 for (i = 0; i < nkpt; i++)
936 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
938 /* Map from zero to end of allocations under 2M pages */
939 /* This replaces some of the KPTphys entries above */
940 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
941 pd_p[i] = (i << PDRSHIFT) | X86_PG_RW | X86_PG_V | PG_PS |
945 * Because we map the physical blocks in 2M pages, adjust firstaddr
946 * to record the physical blocks we've actually mapped into kernel
947 * virtual address space.
949 *firstaddr = round_2mpage(*firstaddr);
951 /* And connect up the PD to the PDP (leaving room for L4 pages) */
952 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
953 for (i = 0; i < nkpdpe; i++)
954 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
957 * Now, set up the direct map region using 2MB and/or 1GB pages. If
958 * the end of physical memory is not aligned to a 1GB page boundary,
959 * then the residual physical memory is mapped with 2MB pages. Later,
960 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
961 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
962 * that are partially used.
964 pd_p = (pd_entry_t *)DMPDphys;
965 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
966 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
967 /* Preset PG_M and PG_A because demotion expects it. */
968 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
971 pdp_p = (pdp_entry_t *)DMPDPphys;
972 for (i = 0; i < ndm1g; i++) {
973 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
974 /* Preset PG_M and PG_A because demotion expects it. */
975 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
978 for (j = 0; i < ndmpdp; i++, j++) {
979 pdp_p[i] = DMPDphys + ptoa(j);
980 pdp_p[i] |= X86_PG_RW | X86_PG_V;
983 /* And recursively map PML4 to itself in order to get PTmap */
984 p4_p = (pml4_entry_t *)KPML4phys;
985 p4_p[PML4PML4I] = KPML4phys;
986 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | pg_nx;
988 /* Connect the Direct Map slot(s) up to the PML4. */
989 for (i = 0; i < ndmpdpphys; i++) {
990 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
991 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V;
994 /* Connect the KVA slots up to the PML4 */
995 for (i = 0; i < NKPML4E; i++) {
996 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
997 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V;
1002 * Bootstrap the system enough to run with virtual memory.
1004 * On amd64 this is called after mapping has already been enabled
1005 * and just syncs the pmap module with what has already been done.
1006 * [We can't call it easily with mapping off since the kernel is not
1007 * mapped with PA == VA, hence we would have to relocate every address
1008 * from the linked base (virtual) address "KERNBASE" to the actual
1009 * (physical) address starting relative to 0]
1012 pmap_bootstrap(vm_paddr_t *firstaddr)
1022 * Create an initial set of page tables to run the kernel in.
1024 create_pagetables(firstaddr);
1027 * Add a physical memory segment (vm_phys_seg) corresponding to the
1028 * preallocated kernel page table pages so that vm_page structures
1029 * representing these pages will be created. The vm_page structures
1030 * are required for promotion of the corresponding kernel virtual
1031 * addresses to superpage mappings.
1033 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1035 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
1037 virtual_end = VM_MAX_KERNEL_ADDRESS;
1040 /* XXX do %cr0 as well */
1041 load_cr4(rcr4() | CR4_PGE);
1042 load_cr3(KPML4phys);
1043 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1044 load_cr4(rcr4() | CR4_SMEP);
1047 * Initialize the kernel pmap (which is statically allocated).
1049 PMAP_LOCK_INIT(kernel_pmap);
1050 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1051 kernel_pmap->pm_cr3 = KPML4phys;
1052 kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
1053 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1054 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1055 kernel_pmap->pm_flags = pmap_flags;
1058 * Initialize the TLB invalidations generation number lock.
1060 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1063 * Reserve some special page table entries/VA space for temporary
1066 #define SYSMAP(c, p, v, n) \
1067 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1073 * Crashdump maps. The first page is reused as CMAP1 for the
1076 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1077 CADDR1 = crashdumpmap;
1082 * Initialize the PAT MSR.
1083 * pmap_init_pat() clears and sets CR4_PGE, which, as a
1084 * side-effect, invalidates stale PG_G TLB entries that might
1085 * have been created in our pre-boot environment.
1089 /* Initialize TLB Context Id. */
1090 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1091 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1092 /* Check for INVPCID support */
1093 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1095 for (i = 0; i < MAXCPU; i++) {
1096 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1097 kernel_pmap->pm_pcids[i].pm_gen = 1;
1099 __pcpu[0].pc_pcid_next = PMAP_PCID_KERN + 1;
1100 __pcpu[0].pc_pcid_gen = 1;
1102 * pcpu area for APs is zeroed during AP startup.
1103 * pc_pcid_next and pc_pcid_gen are initialized by AP
1104 * during pcpu setup.
1106 load_cr4(rcr4() | CR4_PCIDE);
1108 pmap_pcid_enabled = 0;
1113 * Setup the PAT MSR.
1118 int pat_table[PAT_INDEX_SIZE];
1123 /* Bail if this CPU doesn't implement PAT. */
1124 if ((cpu_feature & CPUID_PAT) == 0)
1127 /* Set default PAT index table. */
1128 for (i = 0; i < PAT_INDEX_SIZE; i++)
1130 pat_table[PAT_WRITE_BACK] = 0;
1131 pat_table[PAT_WRITE_THROUGH] = 1;
1132 pat_table[PAT_UNCACHEABLE] = 3;
1133 pat_table[PAT_WRITE_COMBINING] = 3;
1134 pat_table[PAT_WRITE_PROTECTED] = 3;
1135 pat_table[PAT_UNCACHED] = 3;
1137 /* Initialize default PAT entries. */
1138 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1139 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1140 PAT_VALUE(2, PAT_UNCACHED) |
1141 PAT_VALUE(3, PAT_UNCACHEABLE) |
1142 PAT_VALUE(4, PAT_WRITE_BACK) |
1143 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1144 PAT_VALUE(6, PAT_UNCACHED) |
1145 PAT_VALUE(7, PAT_UNCACHEABLE);
1149 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1150 * Program 5 and 6 as WP and WC.
1151 * Leave 4 and 7 as WB and UC.
1153 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1154 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1155 PAT_VALUE(6, PAT_WRITE_COMBINING);
1156 pat_table[PAT_UNCACHED] = 2;
1157 pat_table[PAT_WRITE_PROTECTED] = 5;
1158 pat_table[PAT_WRITE_COMBINING] = 6;
1161 * Just replace PAT Index 2 with WC instead of UC-.
1163 pat_msr &= ~PAT_MASK(2);
1164 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1165 pat_table[PAT_WRITE_COMBINING] = 2;
1170 load_cr4(cr4 & ~CR4_PGE);
1172 /* Disable caches (CD = 1, NW = 0). */
1174 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1176 /* Flushes caches and TLBs. */
1180 /* Update PAT and index table. */
1181 wrmsr(MSR_PAT, pat_msr);
1182 for (i = 0; i < PAT_INDEX_SIZE; i++)
1183 pat_index[i] = pat_table[i];
1185 /* Flush caches and TLBs again. */
1189 /* Restore caches and PGE. */
1195 * Initialize a vm_page's machine-dependent fields.
1198 pmap_page_init(vm_page_t m)
1201 TAILQ_INIT(&m->md.pv_list);
1202 m->md.pat_mode = PAT_WRITE_BACK;
1206 * Initialize the pmap module.
1207 * Called by vm_init, to initialize any structures that the pmap
1208 * system needs to map virtual memory.
1213 struct pmap_preinit_mapping *ppim;
1216 int error, i, pv_npg, ret, skz63;
1218 /* Detect bare-metal Skylake Server and Skylake-X. */
1219 if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
1220 CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
1222 * Skylake-X errata SKZ63. Processor May Hang When
1223 * Executing Code In an HLE Transaction Region between
1224 * 40000000H and 403FFFFFH.
1226 * Mark the pages in the range as preallocated. It
1227 * seems to be impossible to distinguish between
1228 * Skylake Server and Skylake X.
1231 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
1234 printf("SKZ63: skipping 4M RAM starting "
1235 "at physical 1G\n");
1236 for (i = 0; i < atop(0x400000); i++) {
1237 ret = vm_page_blacklist_add(0x40000000 +
1239 if (!ret && bootverbose)
1240 printf("page at %#lx already used\n",
1241 0x40000000 + ptoa(i));
1247 * Initialize the vm page array entries for the kernel pmap's
1250 for (i = 0; i < nkpt; i++) {
1251 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1252 KASSERT(mpte >= vm_page_array &&
1253 mpte < &vm_page_array[vm_page_array_size],
1254 ("pmap_init: page table page is out of range"));
1255 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1256 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1257 mpte->wire_count = 1;
1259 atomic_add_int(&vm_cnt.v_wire_count, nkpt);
1262 * If the kernel is running on a virtual machine, then it must assume
1263 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1264 * be prepared for the hypervisor changing the vendor and family that
1265 * are reported by CPUID. Consequently, the workaround for AMD Family
1266 * 10h Erratum 383 is enabled if the processor's feature set does not
1267 * include at least one feature that is only supported by older Intel
1268 * or newer AMD processors.
1270 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1271 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1272 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1274 workaround_erratum383 = 1;
1277 * Are large page mappings enabled?
1279 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1280 if (pg_ps_enabled) {
1281 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1282 ("pmap_init: can't assign to pagesizes[1]"));
1283 pagesizes[1] = NBPDR;
1287 * Initialize the pv chunk list mutex.
1289 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1292 * Initialize the pool of pv list locks.
1294 for (i = 0; i < NPV_LIST_LOCKS; i++)
1295 rw_init(&pv_list_locks[i], "pmap pv list");
1298 * Calculate the size of the pv head table for superpages.
1300 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1303 * Allocate memory for the pv head table for superpages.
1305 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1307 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1309 for (i = 0; i < pv_npg; i++)
1310 TAILQ_INIT(&pv_table[i].pv_list);
1311 TAILQ_INIT(&pv_dummy.pv_list);
1313 pmap_initialized = 1;
1314 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1315 ppim = pmap_preinit_mapping + i;
1318 /* Make the direct map consistent */
1319 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1320 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1321 ppim->sz, ppim->mode);
1325 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1326 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1329 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1330 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1331 (vmem_addr_t *)&qframe);
1333 panic("qframe allocation failed");
1336 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1337 "2MB page mapping counters");
1339 static u_long pmap_pde_demotions;
1340 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1341 &pmap_pde_demotions, 0, "2MB page demotions");
1343 static u_long pmap_pde_mappings;
1344 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1345 &pmap_pde_mappings, 0, "2MB page mappings");
1347 static u_long pmap_pde_p_failures;
1348 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1349 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1351 static u_long pmap_pde_promotions;
1352 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1353 &pmap_pde_promotions, 0, "2MB page promotions");
1355 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1356 "1GB page mapping counters");
1358 static u_long pmap_pdpe_demotions;
1359 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1360 &pmap_pdpe_demotions, 0, "1GB page demotions");
1362 /***************************************************
1363 * Low level helper routines.....
1364 ***************************************************/
1367 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1369 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1371 switch (pmap->pm_type) {
1374 /* Verify that both PAT bits are not set at the same time */
1375 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1376 ("Invalid PAT bits in entry %#lx", entry));
1378 /* Swap the PAT bits if one of them is set */
1379 if ((entry & x86_pat_bits) != 0)
1380 entry ^= x86_pat_bits;
1384 * Nothing to do - the memory attributes are represented
1385 * the same way for regular pages and superpages.
1389 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1396 * Determine the appropriate bits to set in a PTE or PDE for a specified
1400 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1402 int cache_bits, pat_flag, pat_idx;
1404 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1405 panic("Unknown caching mode %d\n", mode);
1407 switch (pmap->pm_type) {
1410 /* The PAT bit is different for PTE's and PDE's. */
1411 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1413 /* Map the caching mode to a PAT index. */
1414 pat_idx = pat_index[mode];
1416 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1419 cache_bits |= pat_flag;
1421 cache_bits |= PG_NC_PCD;
1423 cache_bits |= PG_NC_PWT;
1427 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1431 panic("unsupported pmap type %d", pmap->pm_type);
1434 return (cache_bits);
1438 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1442 switch (pmap->pm_type) {
1445 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1448 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1451 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1458 pmap_ps_enabled(pmap_t pmap)
1461 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1465 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1468 switch (pmap->pm_type) {
1475 * This is a little bogus since the generation number is
1476 * supposed to be bumped up when a region of the address
1477 * space is invalidated in the page tables.
1479 * In this case the old PDE entry is valid but yet we want
1480 * to make sure that any mappings using the old entry are
1481 * invalidated in the TLB.
1483 * The reason this works as expected is because we rendezvous
1484 * "all" host cpus and force any vcpu context to exit as a
1487 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1490 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1492 pde_store(pde, newpde);
1496 * After changing the page size for the specified virtual address in the page
1497 * table, flush the corresponding entries from the processor's TLB. Only the
1498 * calling processor's TLB is affected.
1500 * The calling thread must be pinned to a processor.
1503 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1507 if (pmap_type_guest(pmap))
1510 KASSERT(pmap->pm_type == PT_X86,
1511 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1513 PG_G = pmap_global_bit(pmap);
1515 if ((newpde & PG_PS) == 0)
1516 /* Demotion: flush a specific 2MB page mapping. */
1518 else if ((newpde & PG_G) == 0)
1520 * Promotion: flush every 4KB page mapping from the TLB
1521 * because there are too many to flush individually.
1526 * Promotion: flush every 4KB page mapping from the TLB,
1527 * including any global (PG_G) mappings.
1535 * For SMP, these functions have to use the IPI mechanism for coherence.
1537 * N.B.: Before calling any of the following TLB invalidation functions,
1538 * the calling processor must ensure that all stores updating a non-
1539 * kernel page table are globally performed. Otherwise, another
1540 * processor could cache an old, pre-update entry without being
1541 * invalidated. This can happen one of two ways: (1) The pmap becomes
1542 * active on another processor after its pm_active field is checked by
1543 * one of the following functions but before a store updating the page
1544 * table is globally performed. (2) The pmap becomes active on another
1545 * processor before its pm_active field is checked but due to
1546 * speculative loads one of the following functions stills reads the
1547 * pmap as inactive on the other processor.
1549 * The kernel page table is exempt because its pm_active field is
1550 * immutable. The kernel page table is always active on every
1555 * Interrupt the cpus that are executing in the guest context.
1556 * This will force the vcpu to exit and the cached EPT mappings
1557 * will be invalidated by the host before the next vmresume.
1559 static __inline void
1560 pmap_invalidate_ept(pmap_t pmap)
1565 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1566 ("pmap_invalidate_ept: absurd pm_active"));
1569 * The TLB mappings associated with a vcpu context are not
1570 * flushed each time a different vcpu is chosen to execute.
1572 * This is in contrast with a process's vtop mappings that
1573 * are flushed from the TLB on each context switch.
1575 * Therefore we need to do more than just a TLB shootdown on
1576 * the active cpus in 'pmap->pm_active'. To do this we keep
1577 * track of the number of invalidations performed on this pmap.
1579 * Each vcpu keeps a cache of this counter and compares it
1580 * just before a vmresume. If the counter is out-of-date an
1581 * invept will be done to flush stale mappings from the TLB.
1583 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1586 * Force the vcpu to exit and trap back into the hypervisor.
1588 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1589 ipi_selected(pmap->pm_active, ipinum);
1594 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1597 struct invpcid_descr d;
1598 uint64_t kcr3, ucr3;
1602 if (pmap_type_guest(pmap)) {
1603 pmap_invalidate_ept(pmap);
1607 KASSERT(pmap->pm_type == PT_X86,
1608 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1611 if (pmap == kernel_pmap) {
1615 cpuid = PCPU_GET(cpuid);
1616 if (pmap == PCPU_GET(curpmap)) {
1618 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1620 * Disable context switching. pm_pcid
1621 * is recalculated on switch, which
1622 * might make us use wrong pcid below.
1625 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1627 if (invpcid_works) {
1628 d.pcid = pcid | PMAP_PCID_USER_PT;
1631 invpcid(&d, INVPCID_ADDR);
1633 kcr3 = pmap->pm_cr3 | pcid |
1635 ucr3 = pmap->pm_ucr3 | pcid |
1636 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1637 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1641 } else if (pmap_pcid_enabled)
1642 pmap->pm_pcids[cpuid].pm_gen = 0;
1643 if (pmap_pcid_enabled) {
1646 pmap->pm_pcids[i].pm_gen = 0;
1650 * The fence is between stores to pm_gen and the read of
1651 * the pm_active mask. We need to ensure that it is
1652 * impossible for us to miss the bit update in pm_active
1653 * and simultaneously observe a non-zero pm_gen in
1654 * pmap_activate_sw(), otherwise TLB update is missed.
1655 * Without the fence, IA32 allows such an outcome.
1656 * Note that pm_active is updated by a locked operation,
1657 * which provides the reciprocal fence.
1659 atomic_thread_fence_seq_cst();
1661 mask = &pmap->pm_active;
1663 smp_masked_invlpg(*mask, va, pmap);
1667 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1668 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1671 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1674 struct invpcid_descr d;
1676 uint64_t kcr3, ucr3;
1680 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1681 pmap_invalidate_all(pmap);
1685 if (pmap_type_guest(pmap)) {
1686 pmap_invalidate_ept(pmap);
1690 KASSERT(pmap->pm_type == PT_X86,
1691 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1694 cpuid = PCPU_GET(cpuid);
1695 if (pmap == kernel_pmap) {
1696 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1700 if (pmap == PCPU_GET(curpmap)) {
1701 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1703 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1705 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1706 if (invpcid_works) {
1707 d.pcid = pcid | PMAP_PCID_USER_PT;
1710 for (; d.addr < eva; d.addr +=
1712 invpcid(&d, INVPCID_ADDR);
1714 kcr3 = pmap->pm_cr3 | pcid |
1716 ucr3 = pmap->pm_ucr3 | pcid |
1717 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1718 pmap_pti_pcid_invlrng(ucr3, kcr3, sva,
1723 } else if (pmap_pcid_enabled) {
1724 pmap->pm_pcids[cpuid].pm_gen = 0;
1726 if (pmap_pcid_enabled) {
1729 pmap->pm_pcids[i].pm_gen = 0;
1731 /* See the comment in pmap_invalidate_page(). */
1732 atomic_thread_fence_seq_cst();
1734 mask = &pmap->pm_active;
1736 smp_masked_invlpg_range(*mask, sva, eva, pmap);
1741 pmap_invalidate_all(pmap_t pmap)
1744 struct invpcid_descr d;
1745 uint64_t kcr3, ucr3;
1749 if (pmap_type_guest(pmap)) {
1750 pmap_invalidate_ept(pmap);
1754 KASSERT(pmap->pm_type == PT_X86,
1755 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1758 if (pmap == kernel_pmap) {
1759 if (pmap_pcid_enabled && invpcid_works) {
1760 bzero(&d, sizeof(d));
1761 invpcid(&d, INVPCID_CTXGLOB);
1767 cpuid = PCPU_GET(cpuid);
1768 if (pmap == PCPU_GET(curpmap)) {
1769 if (pmap_pcid_enabled) {
1771 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1772 if (invpcid_works) {
1776 invpcid(&d, INVPCID_CTX);
1777 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1778 d.pcid |= PMAP_PCID_USER_PT;
1779 invpcid(&d, INVPCID_CTX);
1782 kcr3 = pmap->pm_cr3 | pcid;
1783 ucr3 = pmap->pm_ucr3;
1784 if (ucr3 != PMAP_NO_CR3) {
1785 ucr3 |= pcid | PMAP_PCID_USER_PT;
1786 pmap_pti_pcid_invalidate(ucr3,
1796 } else if (pmap_pcid_enabled) {
1797 pmap->pm_pcids[cpuid].pm_gen = 0;
1799 if (pmap_pcid_enabled) {
1802 pmap->pm_pcids[i].pm_gen = 0;
1804 /* See the comment in pmap_invalidate_page(). */
1805 atomic_thread_fence_seq_cst();
1807 mask = &pmap->pm_active;
1809 smp_masked_invltlb(*mask, pmap);
1814 pmap_invalidate_cache(void)
1824 cpuset_t invalidate; /* processors that invalidate their TLB */
1829 u_int store; /* processor that updates the PDE */
1833 pmap_update_pde_action(void *arg)
1835 struct pde_action *act = arg;
1837 if (act->store == PCPU_GET(cpuid))
1838 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1842 pmap_update_pde_teardown(void *arg)
1844 struct pde_action *act = arg;
1846 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1847 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1851 * Change the page size for the specified virtual address in a way that
1852 * prevents any possibility of the TLB ever having two entries that map the
1853 * same virtual address using different page sizes. This is the recommended
1854 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1855 * machine check exception for a TLB state that is improperly diagnosed as a
1859 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1861 struct pde_action act;
1862 cpuset_t active, other_cpus;
1866 cpuid = PCPU_GET(cpuid);
1867 other_cpus = all_cpus;
1868 CPU_CLR(cpuid, &other_cpus);
1869 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1872 active = pmap->pm_active;
1874 if (CPU_OVERLAP(&active, &other_cpus)) {
1876 act.invalidate = active;
1880 act.newpde = newpde;
1881 CPU_SET(cpuid, &active);
1882 smp_rendezvous_cpus(active,
1883 smp_no_rendezvous_barrier, pmap_update_pde_action,
1884 pmap_update_pde_teardown, &act);
1886 pmap_update_pde_store(pmap, pde, newpde);
1887 if (CPU_ISSET(cpuid, &active))
1888 pmap_update_pde_invalidate(pmap, va, newpde);
1894 * Normal, non-SMP, invalidation functions.
1897 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1899 struct invpcid_descr d;
1900 uint64_t kcr3, ucr3;
1903 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1907 KASSERT(pmap->pm_type == PT_X86,
1908 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1910 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1912 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
1913 pmap->pm_ucr3 != PMAP_NO_CR3) {
1915 pcid = pmap->pm_pcids[0].pm_pcid;
1916 if (invpcid_works) {
1917 d.pcid = pcid | PMAP_PCID_USER_PT;
1920 invpcid(&d, INVPCID_ADDR);
1922 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
1923 ucr3 = pmap->pm_ucr3 | pcid |
1924 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1925 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1929 } else if (pmap_pcid_enabled)
1930 pmap->pm_pcids[0].pm_gen = 0;
1934 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1936 struct invpcid_descr d;
1938 uint64_t kcr3, ucr3;
1940 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1944 KASSERT(pmap->pm_type == PT_X86,
1945 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1947 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1948 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1950 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
1951 pmap->pm_ucr3 != PMAP_NO_CR3) {
1953 if (invpcid_works) {
1954 d.pcid = pmap->pm_pcids[0].pm_pcid |
1958 for (; d.addr < eva; d.addr += PAGE_SIZE)
1959 invpcid(&d, INVPCID_ADDR);
1961 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].
1962 pm_pcid | CR3_PCID_SAVE;
1963 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[0].
1964 pm_pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1965 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
1969 } else if (pmap_pcid_enabled) {
1970 pmap->pm_pcids[0].pm_gen = 0;
1975 pmap_invalidate_all(pmap_t pmap)
1977 struct invpcid_descr d;
1978 uint64_t kcr3, ucr3;
1980 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1984 KASSERT(pmap->pm_type == PT_X86,
1985 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
1987 if (pmap == kernel_pmap) {
1988 if (pmap_pcid_enabled && invpcid_works) {
1989 bzero(&d, sizeof(d));
1990 invpcid(&d, INVPCID_CTXGLOB);
1994 } else if (pmap == PCPU_GET(curpmap)) {
1995 if (pmap_pcid_enabled) {
1997 if (invpcid_works) {
1998 d.pcid = pmap->pm_pcids[0].pm_pcid;
2001 invpcid(&d, INVPCID_CTX);
2002 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2003 d.pcid |= PMAP_PCID_USER_PT;
2004 invpcid(&d, INVPCID_CTX);
2007 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].pm_pcid;
2008 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2009 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[
2010 0].pm_pcid | PMAP_PCID_USER_PT;
2011 pmap_pti_pcid_invalidate(ucr3, kcr3);
2019 } else if (pmap_pcid_enabled) {
2020 pmap->pm_pcids[0].pm_gen = 0;
2025 pmap_invalidate_cache(void)
2032 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
2035 pmap_update_pde_store(pmap, pde, newpde);
2036 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
2037 pmap_update_pde_invalidate(pmap, va, newpde);
2039 pmap->pm_pcids[0].pm_gen = 0;
2044 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
2048 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
2049 * by a promotion that did not invalidate the 512 4KB page mappings
2050 * that might exist in the TLB. Consequently, at this point, the TLB
2051 * may hold both 4KB and 2MB page mappings for the address range [va,
2052 * va + NBPDR). Therefore, the entire range must be invalidated here.
2053 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
2054 * 4KB page mappings for the address range [va, va + NBPDR), and so a
2055 * single INVLPG suffices to invalidate the 2MB page mapping from the
2058 if ((pde & PG_PROMOTED) != 0)
2059 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
2061 pmap_invalidate_page(pmap, va);
2064 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
2067 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
2071 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
2073 KASSERT((sva & PAGE_MASK) == 0,
2074 ("pmap_invalidate_cache_range: sva not page-aligned"));
2075 KASSERT((eva & PAGE_MASK) == 0,
2076 ("pmap_invalidate_cache_range: eva not page-aligned"));
2079 if ((cpu_feature & CPUID_SS) != 0 && !force)
2080 ; /* If "Self Snoop" is supported and allowed, do nothing. */
2081 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
2082 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2084 * XXX: Some CPUs fault, hang, or trash the local APIC
2085 * registers if we use CLFLUSH on the local APIC
2086 * range. The local APIC is always uncached, so we
2087 * don't need to flush for that range anyway.
2089 if (pmap_kextract(sva) == lapic_paddr)
2093 * Otherwise, do per-cache line flush. Use the sfence
2094 * instruction to insure that previous stores are
2095 * included in the write-back. The processor
2096 * propagates flush to other processors in the cache
2100 for (; sva < eva; sva += cpu_clflush_line_size)
2103 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
2104 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2105 if (pmap_kextract(sva) == lapic_paddr)
2108 * Writes are ordered by CLFLUSH on Intel CPUs.
2110 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2112 for (; sva < eva; sva += cpu_clflush_line_size)
2114 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2119 * No targeted cache flush methods are supported by CPU,
2120 * or the supplied range is bigger than 2MB.
2121 * Globally invalidate cache.
2123 pmap_invalidate_cache();
2128 * Remove the specified set of pages from the data and instruction caches.
2130 * In contrast to pmap_invalidate_cache_range(), this function does not
2131 * rely on the CPU's self-snoop feature, because it is intended for use
2132 * when moving pages into a different cache domain.
2135 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
2137 vm_offset_t daddr, eva;
2141 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
2142 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
2143 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
2144 pmap_invalidate_cache();
2148 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2150 for (i = 0; i < count; i++) {
2151 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
2152 eva = daddr + PAGE_SIZE;
2153 for (; daddr < eva; daddr += cpu_clflush_line_size) {
2162 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2168 * Routine: pmap_extract
2170 * Extract the physical page address associated
2171 * with the given map/virtual_address pair.
2174 pmap_extract(pmap_t pmap, vm_offset_t va)
2178 pt_entry_t *pte, PG_V;
2182 PG_V = pmap_valid_bit(pmap);
2184 pdpe = pmap_pdpe(pmap, va);
2185 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2186 if ((*pdpe & PG_PS) != 0)
2187 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
2189 pde = pmap_pdpe_to_pde(pdpe, va);
2190 if ((*pde & PG_V) != 0) {
2191 if ((*pde & PG_PS) != 0) {
2192 pa = (*pde & PG_PS_FRAME) |
2195 pte = pmap_pde_to_pte(pde, va);
2196 pa = (*pte & PG_FRAME) |
2207 * Routine: pmap_extract_and_hold
2209 * Atomically extract and hold the physical page
2210 * with the given pmap and virtual address pair
2211 * if that mapping permits the given protection.
2214 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
2216 pd_entry_t pde, *pdep;
2217 pt_entry_t pte, PG_RW, PG_V;
2223 PG_RW = pmap_rw_bit(pmap);
2224 PG_V = pmap_valid_bit(pmap);
2227 pdep = pmap_pde(pmap, va);
2228 if (pdep != NULL && (pde = *pdep)) {
2230 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2231 if (vm_page_pa_tryrelock(pmap, (pde &
2232 PG_PS_FRAME) | (va & PDRMASK), &pa))
2234 m = PHYS_TO_VM_PAGE(pa);
2237 pte = *pmap_pde_to_pte(pdep, va);
2239 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2240 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2243 m = PHYS_TO_VM_PAGE(pa);
2255 pmap_kextract(vm_offset_t va)
2260 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2261 pa = DMAP_TO_PHYS(va);
2265 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2268 * Beware of a concurrent promotion that changes the
2269 * PDE at this point! For example, vtopte() must not
2270 * be used to access the PTE because it would use the
2271 * new PDE. It is, however, safe to use the old PDE
2272 * because the page table page is preserved by the
2275 pa = *pmap_pde_to_pte(&pde, va);
2276 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2282 /***************************************************
2283 * Low level mapping routines.....
2284 ***************************************************/
2287 * Add a wired page to the kva.
2288 * Note: not SMP coherent.
2291 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2296 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g);
2299 static __inline void
2300 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2306 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2307 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | cache_bits);
2311 * Remove a page from the kernel pagetables.
2312 * Note: not SMP coherent.
2315 pmap_kremove(vm_offset_t va)
2324 * Used to map a range of physical addresses into kernel
2325 * virtual address space.
2327 * The value passed in '*virt' is a suggested virtual address for
2328 * the mapping. Architectures which can support a direct-mapped
2329 * physical to virtual region can return the appropriate address
2330 * within that region, leaving '*virt' unchanged. Other
2331 * architectures should map the pages starting at '*virt' and
2332 * update '*virt' with the first usable address after the mapped
2336 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2338 return PHYS_TO_DMAP(start);
2343 * Add a list of wired pages to the kva
2344 * this routine is only used for temporary
2345 * kernel mappings that do not need to have
2346 * page modification or references recorded.
2347 * Note that old mappings are simply written
2348 * over. The page *must* be wired.
2349 * Note: SMP coherent. Uses a ranged shootdown IPI.
2352 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2354 pt_entry_t *endpte, oldpte, pa, *pte;
2360 endpte = pte + count;
2361 while (pte < endpte) {
2363 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2364 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2365 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2367 pte_store(pte, pa | pg_g | X86_PG_RW | X86_PG_V);
2371 if (__predict_false((oldpte & X86_PG_V) != 0))
2372 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2377 * This routine tears out page mappings from the
2378 * kernel -- it is meant only for temporary mappings.
2379 * Note: SMP coherent. Uses a ranged shootdown IPI.
2382 pmap_qremove(vm_offset_t sva, int count)
2387 while (count-- > 0) {
2388 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2392 pmap_invalidate_range(kernel_pmap, sva, va);
2395 /***************************************************
2396 * Page table page management routines.....
2397 ***************************************************/
2398 static __inline void
2399 pmap_free_zero_pages(struct spglist *free)
2404 for (count = 0; (m = SLIST_FIRST(free)) != NULL; count++) {
2405 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2406 /* Preserve the page's PG_ZERO setting. */
2407 vm_page_free_toq(m);
2409 atomic_subtract_int(&vm_cnt.v_wire_count, count);
2413 * Schedule the specified unused page table page to be freed. Specifically,
2414 * add the page to the specified list of pages that will be released to the
2415 * physical memory manager after the TLB has been updated.
2417 static __inline void
2418 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2419 boolean_t set_PG_ZERO)
2423 m->flags |= PG_ZERO;
2425 m->flags &= ~PG_ZERO;
2426 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2430 * Inserts the specified page table page into the specified pmap's collection
2431 * of idle page table pages. Each of a pmap's page table pages is responsible
2432 * for mapping a distinct range of virtual addresses. The pmap's collection is
2433 * ordered by this virtual address range.
2436 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2439 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2440 return (vm_radix_insert(&pmap->pm_root, mpte));
2444 * Removes the page table page mapping the specified virtual address from the
2445 * specified pmap's collection of idle page table pages, and returns it.
2446 * Otherwise, returns NULL if there is no page table page corresponding to the
2447 * specified virtual address.
2449 static __inline vm_page_t
2450 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
2453 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2454 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
2458 * Decrements a page table page's wire count, which is used to record the
2459 * number of valid page table entries within the page. If the wire count
2460 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2461 * page table page was unmapped and FALSE otherwise.
2463 static inline boolean_t
2464 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2468 if (m->wire_count == 0) {
2469 _pmap_unwire_ptp(pmap, va, m, free);
2476 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2479 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2481 * unmap the page table page
2483 if (m->pindex >= (NUPDE + NUPDPE)) {
2486 pml4 = pmap_pml4e(pmap, va);
2488 if (pmap->pm_pml4u != NULL && va <= VM_MAXUSER_ADDRESS) {
2489 pml4 = &pmap->pm_pml4u[pmap_pml4e_index(va)];
2492 } else if (m->pindex >= NUPDE) {
2495 pdp = pmap_pdpe(pmap, va);
2500 pd = pmap_pde(pmap, va);
2503 pmap_resident_count_dec(pmap, 1);
2504 if (m->pindex < NUPDE) {
2505 /* We just released a PT, unhold the matching PD */
2508 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2509 pmap_unwire_ptp(pmap, va, pdpg, free);
2511 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2512 /* We just released a PD, unhold the matching PDP */
2515 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2516 pmap_unwire_ptp(pmap, va, pdppg, free);
2520 * Put page on a list so that it is released after
2521 * *ALL* TLB shootdown is done
2523 pmap_add_delayed_free_list(m, free, TRUE);
2527 * After removing a page table entry, this routine is used to
2528 * conditionally free the page, and manage the hold/wire counts.
2531 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2532 struct spglist *free)
2536 if (va >= VM_MAXUSER_ADDRESS)
2538 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2539 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2540 return (pmap_unwire_ptp(pmap, va, mpte, free));
2544 pmap_pinit0(pmap_t pmap)
2548 PMAP_LOCK_INIT(pmap);
2549 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2550 pmap->pm_pml4u = NULL;
2551 pmap->pm_cr3 = KPML4phys;
2552 /* hack to keep pmap_pti_pcid_invalidate() alive */
2553 pmap->pm_ucr3 = PMAP_NO_CR3;
2554 pmap->pm_root.rt_root = 0;
2555 CPU_ZERO(&pmap->pm_active);
2556 TAILQ_INIT(&pmap->pm_pvchunk);
2557 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2558 pmap->pm_flags = pmap_flags;
2560 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2561 pmap->pm_pcids[i].pm_gen = 0;
2563 __pcpu[i].pc_kcr3 = PMAP_NO_CR3;
2564 __pcpu[i].pc_ucr3 = PMAP_NO_CR3;
2567 PCPU_SET(curpmap, kernel_pmap);
2568 pmap_activate(curthread);
2569 CPU_FILL(&kernel_pmap->pm_active);
2573 pmap_pinit_pml4(vm_page_t pml4pg)
2575 pml4_entry_t *pm_pml4;
2578 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2580 /* Wire in kernel global address entries. */
2581 for (i = 0; i < NKPML4E; i++) {
2582 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2585 for (i = 0; i < ndmpdpphys; i++) {
2586 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2590 /* install self-referential address mapping entry(s) */
2591 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2592 X86_PG_A | X86_PG_M;
2596 pmap_pinit_pml4_pti(vm_page_t pml4pg)
2598 pml4_entry_t *pm_pml4;
2601 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2602 for (i = 0; i < NPML4EPG; i++)
2603 pm_pml4[i] = pti_pml4[i];
2607 * Initialize a preallocated and zeroed pmap structure,
2608 * such as one in a vmspace structure.
2611 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2613 vm_page_t pml4pg, pml4pgu;
2614 vm_paddr_t pml4phys;
2618 * allocate the page directory page
2620 pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
2621 VM_ALLOC_WIRED | VM_ALLOC_ZERO | VM_ALLOC_WAITOK);
2623 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2624 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2626 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2627 pmap->pm_pcids[i].pm_gen = 0;
2629 pmap->pm_cr3 = PMAP_NO_CR3; /* initialize to an invalid value */
2630 pmap->pm_ucr3 = PMAP_NO_CR3;
2631 pmap->pm_pml4u = NULL;
2633 pmap->pm_type = pm_type;
2634 if ((pml4pg->flags & PG_ZERO) == 0)
2635 pagezero(pmap->pm_pml4);
2638 * Do not install the host kernel mappings in the nested page
2639 * tables. These mappings are meaningless in the guest physical
2641 * Install minimal kernel mappings in PTI case.
2643 if (pm_type == PT_X86) {
2644 pmap->pm_cr3 = pml4phys;
2645 pmap_pinit_pml4(pml4pg);
2647 pml4pgu = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2648 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2649 pmap->pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(
2650 VM_PAGE_TO_PHYS(pml4pgu));
2651 pmap_pinit_pml4_pti(pml4pgu);
2652 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pml4pgu);
2656 pmap->pm_root.rt_root = 0;
2657 CPU_ZERO(&pmap->pm_active);
2658 TAILQ_INIT(&pmap->pm_pvchunk);
2659 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2660 pmap->pm_flags = flags;
2661 pmap->pm_eptgen = 0;
2667 pmap_pinit(pmap_t pmap)
2670 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2674 * This routine is called if the desired page table page does not exist.
2676 * If page table page allocation fails, this routine may sleep before
2677 * returning NULL. It sleeps only if a lock pointer was given.
2679 * Note: If a page allocation fails at page table level two or three,
2680 * one or two pages may be held during the wait, only to be released
2681 * afterwards. This conservative approach is easily argued to avoid
2685 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2687 vm_page_t m, pdppg, pdpg;
2688 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2690 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2692 PG_A = pmap_accessed_bit(pmap);
2693 PG_M = pmap_modified_bit(pmap);
2694 PG_V = pmap_valid_bit(pmap);
2695 PG_RW = pmap_rw_bit(pmap);
2698 * Allocate a page table page.
2700 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2701 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2702 if (lockp != NULL) {
2703 RELEASE_PV_LIST_LOCK(lockp);
2705 PMAP_ASSERT_NOT_IN_DI();
2711 * Indicate the need to retry. While waiting, the page table
2712 * page may have been allocated.
2716 if ((m->flags & PG_ZERO) == 0)
2720 * Map the pagetable page into the process address space, if
2721 * it isn't already there.
2724 if (ptepindex >= (NUPDE + NUPDPE)) {
2725 pml4_entry_t *pml4, *pml4u;
2726 vm_pindex_t pml4index;
2728 /* Wire up a new PDPE page */
2729 pml4index = ptepindex - (NUPDE + NUPDPE);
2730 pml4 = &pmap->pm_pml4[pml4index];
2731 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2732 if (pmap->pm_pml4u != NULL && pml4index < NUPML4E) {
2734 * PTI: Make all user-space mappings in the
2735 * kernel-mode page table no-execute so that
2736 * we detect any programming errors that leave
2737 * the kernel-mode page table active on return
2740 if (pmap->pm_ucr3 != PMAP_NO_CR3)
2743 pml4u = &pmap->pm_pml4u[pml4index];
2744 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
2748 } else if (ptepindex >= NUPDE) {
2749 vm_pindex_t pml4index;
2750 vm_pindex_t pdpindex;
2754 /* Wire up a new PDE page */
2755 pdpindex = ptepindex - NUPDE;
2756 pml4index = pdpindex >> NPML4EPGSHIFT;
2758 pml4 = &pmap->pm_pml4[pml4index];
2759 if ((*pml4 & PG_V) == 0) {
2760 /* Have to allocate a new pdp, recurse */
2761 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2764 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2765 vm_page_free_zero(m);
2769 /* Add reference to pdp page */
2770 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2771 pdppg->wire_count++;
2773 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2775 /* Now find the pdp page */
2776 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2777 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2780 vm_pindex_t pml4index;
2781 vm_pindex_t pdpindex;
2786 /* Wire up a new PTE page */
2787 pdpindex = ptepindex >> NPDPEPGSHIFT;
2788 pml4index = pdpindex >> NPML4EPGSHIFT;
2790 /* First, find the pdp and check that its valid. */
2791 pml4 = &pmap->pm_pml4[pml4index];
2792 if ((*pml4 & PG_V) == 0) {
2793 /* Have to allocate a new pd, recurse */
2794 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2797 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2798 vm_page_free_zero(m);
2801 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2802 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2804 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2805 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2806 if ((*pdp & PG_V) == 0) {
2807 /* Have to allocate a new pd, recurse */
2808 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2811 atomic_subtract_int(&vm_cnt.v_wire_count,
2813 vm_page_free_zero(m);
2817 /* Add reference to the pd page */
2818 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2822 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2824 /* Now we know where the page directory page is */
2825 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2826 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2829 pmap_resident_count_inc(pmap, 1);
2835 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2837 vm_pindex_t pdpindex, ptepindex;
2838 pdp_entry_t *pdpe, PG_V;
2841 PG_V = pmap_valid_bit(pmap);
2844 pdpe = pmap_pdpe(pmap, va);
2845 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2846 /* Add a reference to the pd page. */
2847 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2850 /* Allocate a pd page. */
2851 ptepindex = pmap_pde_pindex(va);
2852 pdpindex = ptepindex >> NPDPEPGSHIFT;
2853 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2854 if (pdpg == NULL && lockp != NULL)
2861 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2863 vm_pindex_t ptepindex;
2864 pd_entry_t *pd, PG_V;
2867 PG_V = pmap_valid_bit(pmap);
2870 * Calculate pagetable page index
2872 ptepindex = pmap_pde_pindex(va);
2875 * Get the page directory entry
2877 pd = pmap_pde(pmap, va);
2880 * This supports switching from a 2MB page to a
2883 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2884 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2886 * Invalidation of the 2MB page mapping may have caused
2887 * the deallocation of the underlying PD page.
2894 * If the page table page is mapped, we just increment the
2895 * hold count, and activate it.
2897 if (pd != NULL && (*pd & PG_V) != 0) {
2898 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2902 * Here if the pte page isn't mapped, or if it has been
2905 m = _pmap_allocpte(pmap, ptepindex, lockp);
2906 if (m == NULL && lockp != NULL)
2913 /***************************************************
2914 * Pmap allocation/deallocation routines.
2915 ***************************************************/
2918 * Release any resources held by the given physical map.
2919 * Called when a pmap initialized by pmap_pinit is being released.
2920 * Should only be called if the map contains no valid mappings.
2923 pmap_release(pmap_t pmap)
2928 KASSERT(pmap->pm_stats.resident_count == 0,
2929 ("pmap_release: pmap resident count %ld != 0",
2930 pmap->pm_stats.resident_count));
2931 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2932 ("pmap_release: pmap has reserved page table page(s)"));
2933 KASSERT(CPU_EMPTY(&pmap->pm_active),
2934 ("releasing active pmap %p", pmap));
2936 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2938 for (i = 0; i < NKPML4E; i++) /* KVA */
2939 pmap->pm_pml4[KPML4BASE + i] = 0;
2940 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
2941 pmap->pm_pml4[DMPML4I + i] = 0;
2942 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
2945 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2946 vm_page_free_zero(m);
2948 if (pmap->pm_pml4u != NULL) {
2949 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4u));
2951 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2957 kvm_size(SYSCTL_HANDLER_ARGS)
2959 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2961 return sysctl_handle_long(oidp, &ksize, 0, req);
2963 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2964 0, 0, kvm_size, "LU", "Size of KVM");
2967 kvm_free(SYSCTL_HANDLER_ARGS)
2969 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2971 return sysctl_handle_long(oidp, &kfree, 0, req);
2973 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2974 0, 0, kvm_free, "LU", "Amount of KVM free");
2977 * grow the number of kernel page table entries, if needed
2980 pmap_growkernel(vm_offset_t addr)
2984 pd_entry_t *pde, newpdir;
2987 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2990 * Return if "addr" is within the range of kernel page table pages
2991 * that were preallocated during pmap bootstrap. Moreover, leave
2992 * "kernel_vm_end" and the kernel page table as they were.
2994 * The correctness of this action is based on the following
2995 * argument: vm_map_insert() allocates contiguous ranges of the
2996 * kernel virtual address space. It calls this function if a range
2997 * ends after "kernel_vm_end". If the kernel is mapped between
2998 * "kernel_vm_end" and "addr", then the range cannot begin at
2999 * "kernel_vm_end". In fact, its beginning address cannot be less
3000 * than the kernel. Thus, there is no immediate need to allocate
3001 * any new kernel page table pages between "kernel_vm_end" and
3004 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
3007 addr = roundup2(addr, NBPDR);
3008 if (addr - 1 >= kernel_map->max_offset)
3009 addr = kernel_map->max_offset;
3010 while (kernel_vm_end < addr) {
3011 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
3012 if ((*pdpe & X86_PG_V) == 0) {
3013 /* We need a new PDP entry */
3014 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
3015 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
3016 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
3018 panic("pmap_growkernel: no memory to grow kernel");
3019 if ((nkpg->flags & PG_ZERO) == 0)
3020 pmap_zero_page(nkpg);
3021 paddr = VM_PAGE_TO_PHYS(nkpg);
3022 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
3023 X86_PG_A | X86_PG_M);
3024 continue; /* try again */
3026 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
3027 if ((*pde & X86_PG_V) != 0) {
3028 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3029 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
3030 kernel_vm_end = kernel_map->max_offset;
3036 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
3037 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
3040 panic("pmap_growkernel: no memory to grow kernel");
3041 if ((nkpg->flags & PG_ZERO) == 0)
3042 pmap_zero_page(nkpg);
3043 paddr = VM_PAGE_TO_PHYS(nkpg);
3044 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
3045 pde_store(pde, newpdir);
3047 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3048 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
3049 kernel_vm_end = kernel_map->max_offset;
3056 /***************************************************
3057 * page management routines.
3058 ***************************************************/
3060 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
3061 CTASSERT(_NPCM == 3);
3062 CTASSERT(_NPCPV == 168);
3064 static __inline struct pv_chunk *
3065 pv_to_chunk(pv_entry_t pv)
3068 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
3071 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
3073 #define PC_FREE0 0xfffffffffffffffful
3074 #define PC_FREE1 0xfffffffffffffffful
3075 #define PC_FREE2 0x000000fffffffffful
3077 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
3080 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
3082 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
3083 "Current number of pv entry chunks");
3084 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
3085 "Current number of pv entry chunks allocated");
3086 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
3087 "Current number of pv entry chunks frees");
3088 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
3089 "Number of times tried to get a chunk page but failed.");
3091 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
3092 static int pv_entry_spare;
3094 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
3095 "Current number of pv entry frees");
3096 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
3097 "Current number of pv entry allocs");
3098 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
3099 "Current number of pv entries");
3100 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
3101 "Current number of spare pv entries");
3105 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
3110 pmap_invalidate_all(pmap);
3111 if (pmap != locked_pmap)
3114 pmap_delayed_invl_finished();
3118 * We are in a serious low memory condition. Resort to
3119 * drastic measures to free some pages so we can allocate
3120 * another pv entry chunk.
3122 * Returns NULL if PV entries were reclaimed from the specified pmap.
3124 * We do not, however, unmap 2mpages because subsequent accesses will
3125 * allocate per-page pv entries until repromotion occurs, thereby
3126 * exacerbating the shortage of free pv entries.
3129 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
3131 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
3132 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
3133 struct md_page *pvh;
3135 pmap_t next_pmap, pmap;
3136 pt_entry_t *pte, tpte;
3137 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3141 struct spglist free;
3143 int bit, field, freed;
3145 static int active_reclaims = 0;
3147 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
3148 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
3151 PG_G = PG_A = PG_M = PG_RW = 0;
3153 bzero(&pc_marker_b, sizeof(pc_marker_b));
3154 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
3155 pc_marker = (struct pv_chunk *)&pc_marker_b;
3156 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
3159 * A delayed invalidation block should already be active if
3160 * pmap_advise() or pmap_remove() called this function by way
3161 * of pmap_demote_pde_locked().
3163 start_di = pmap_not_in_di();
3165 mtx_lock(&pv_chunks_mutex);
3167 TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
3168 TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
3169 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
3170 SLIST_EMPTY(&free)) {
3171 next_pmap = pc->pc_pmap;
3172 if (next_pmap == NULL) {
3174 * The next chunk is a marker. However, it is
3175 * not our marker, so active_reclaims must be
3176 * > 1. Consequently, the next_chunk code
3177 * will not rotate the pv_chunks list.
3181 mtx_unlock(&pv_chunks_mutex);
3184 * A pv_chunk can only be removed from the pc_lru list
3185 * when both pc_chunks_mutex is owned and the
3186 * corresponding pmap is locked.
3188 if (pmap != next_pmap) {
3189 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
3192 /* Avoid deadlock and lock recursion. */
3193 if (pmap > locked_pmap) {
3194 RELEASE_PV_LIST_LOCK(lockp);
3197 pmap_delayed_invl_started();
3198 mtx_lock(&pv_chunks_mutex);
3200 } else if (pmap != locked_pmap) {
3201 if (PMAP_TRYLOCK(pmap)) {
3203 pmap_delayed_invl_started();
3204 mtx_lock(&pv_chunks_mutex);
3207 pmap = NULL; /* pmap is not locked */
3208 mtx_lock(&pv_chunks_mutex);
3209 pc = TAILQ_NEXT(pc_marker, pc_lru);
3211 pc->pc_pmap != next_pmap)
3215 } else if (start_di)
3216 pmap_delayed_invl_started();
3217 PG_G = pmap_global_bit(pmap);
3218 PG_A = pmap_accessed_bit(pmap);
3219 PG_M = pmap_modified_bit(pmap);
3220 PG_RW = pmap_rw_bit(pmap);
3224 * Destroy every non-wired, 4 KB page mapping in the chunk.
3227 for (field = 0; field < _NPCM; field++) {
3228 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
3229 inuse != 0; inuse &= ~(1UL << bit)) {
3231 pv = &pc->pc_pventry[field * 64 + bit];
3233 pde = pmap_pde(pmap, va);
3234 if ((*pde & PG_PS) != 0)
3236 pte = pmap_pde_to_pte(pde, va);
3237 if ((*pte & PG_W) != 0)
3239 tpte = pte_load_clear(pte);
3240 if ((tpte & PG_G) != 0)
3241 pmap_invalidate_page(pmap, va);
3242 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3243 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3245 if ((tpte & PG_A) != 0)
3246 vm_page_aflag_set(m, PGA_REFERENCED);
3247 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3248 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3250 if (TAILQ_EMPTY(&m->md.pv_list) &&
3251 (m->flags & PG_FICTITIOUS) == 0) {
3252 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3253 if (TAILQ_EMPTY(&pvh->pv_list)) {
3254 vm_page_aflag_clear(m,
3258 pmap_delayed_invl_page(m);
3259 pc->pc_map[field] |= 1UL << bit;
3260 pmap_unuse_pt(pmap, va, *pde, &free);
3265 mtx_lock(&pv_chunks_mutex);
3268 /* Every freed mapping is for a 4 KB page. */
3269 pmap_resident_count_dec(pmap, freed);
3270 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
3271 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
3272 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
3273 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3274 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
3275 pc->pc_map[2] == PC_FREE2) {
3276 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3277 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3278 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3279 /* Entire chunk is free; return it. */
3280 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3281 dump_drop_page(m_pc->phys_addr);
3282 mtx_lock(&pv_chunks_mutex);
3283 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3286 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3287 mtx_lock(&pv_chunks_mutex);
3288 /* One freed pv entry in locked_pmap is sufficient. */
3289 if (pmap == locked_pmap)
3292 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3293 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
3294 if (active_reclaims == 1 && pmap != NULL) {
3296 * Rotate the pv chunks list so that we do not
3297 * scan the same pv chunks that could not be
3298 * freed (because they contained a wired
3299 * and/or superpage mapping) on every
3300 * invocation of reclaim_pv_chunk().
3302 while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
3303 MPASS(pc->pc_pmap != NULL);
3304 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3305 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3309 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3310 TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
3312 mtx_unlock(&pv_chunks_mutex);
3313 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
3314 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
3315 m_pc = SLIST_FIRST(&free);
3316 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3317 /* Recycle a freed page table page. */
3318 m_pc->wire_count = 1;
3320 pmap_free_zero_pages(&free);
3325 * free the pv_entry back to the free list
3328 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3330 struct pv_chunk *pc;
3331 int idx, field, bit;
3333 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3334 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3335 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3336 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3337 pc = pv_to_chunk(pv);
3338 idx = pv - &pc->pc_pventry[0];
3341 pc->pc_map[field] |= 1ul << bit;
3342 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3343 pc->pc_map[2] != PC_FREE2) {
3344 /* 98% of the time, pc is already at the head of the list. */
3345 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3346 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3347 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3351 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3356 free_pv_chunk(struct pv_chunk *pc)
3360 mtx_lock(&pv_chunks_mutex);
3361 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3362 mtx_unlock(&pv_chunks_mutex);
3363 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3364 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3365 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3366 /* entire chunk is free, return it */
3367 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3368 dump_drop_page(m->phys_addr);
3369 vm_page_unwire(m, PQ_NONE);
3374 * Returns a new PV entry, allocating a new PV chunk from the system when
3375 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3376 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3379 * The given PV list lock may be released.
3382 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3386 struct pv_chunk *pc;
3389 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3390 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3392 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3394 for (field = 0; field < _NPCM; field++) {
3395 if (pc->pc_map[field]) {
3396 bit = bsfq(pc->pc_map[field]);
3400 if (field < _NPCM) {
3401 pv = &pc->pc_pventry[field * 64 + bit];
3402 pc->pc_map[field] &= ~(1ul << bit);
3403 /* If this was the last item, move it to tail */
3404 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3405 pc->pc_map[2] == 0) {
3406 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3407 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3410 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3411 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3415 /* No free items, allocate another chunk */
3416 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3419 if (lockp == NULL) {
3420 PV_STAT(pc_chunk_tryfail++);
3423 m = reclaim_pv_chunk(pmap, lockp);
3427 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3428 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3429 dump_add_page(m->phys_addr);
3430 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3432 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3433 pc->pc_map[1] = PC_FREE1;
3434 pc->pc_map[2] = PC_FREE2;
3435 mtx_lock(&pv_chunks_mutex);
3436 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3437 mtx_unlock(&pv_chunks_mutex);
3438 pv = &pc->pc_pventry[0];
3439 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3440 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3441 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3446 * Returns the number of one bits within the given PV chunk map.
3448 * The erratas for Intel processors state that "POPCNT Instruction May
3449 * Take Longer to Execute Than Expected". It is believed that the
3450 * issue is the spurious dependency on the destination register.
3451 * Provide a hint to the register rename logic that the destination
3452 * value is overwritten, by clearing it, as suggested in the
3453 * optimization manual. It should be cheap for unaffected processors
3456 * Reference numbers for erratas are
3457 * 4th Gen Core: HSD146
3458 * 5th Gen Core: BDM85
3459 * 6th Gen Core: SKL029
3462 popcnt_pc_map_pq(uint64_t *map)
3466 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3467 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3468 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3469 : "=&r" (result), "=&r" (tmp)
3470 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3475 * Ensure that the number of spare PV entries in the specified pmap meets or
3476 * exceeds the given count, "needed".
3478 * The given PV list lock may be released.
3481 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3483 struct pch new_tail;
3484 struct pv_chunk *pc;
3489 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3490 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3493 * Newly allocated PV chunks must be stored in a private list until
3494 * the required number of PV chunks have been allocated. Otherwise,
3495 * reclaim_pv_chunk() could recycle one of these chunks. In
3496 * contrast, these chunks must be added to the pmap upon allocation.
3498 TAILQ_INIT(&new_tail);
3501 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3503 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3504 bit_count((bitstr_t *)pc->pc_map, 0,
3505 sizeof(pc->pc_map) * NBBY, &free);
3508 free = popcnt_pc_map_pq(pc->pc_map);
3512 if (avail >= needed)
3515 for (reclaimed = false; avail < needed; avail += _NPCPV) {
3516 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3519 m = reclaim_pv_chunk(pmap, lockp);
3524 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3525 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3526 dump_add_page(m->phys_addr);
3527 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3529 pc->pc_map[0] = PC_FREE0;
3530 pc->pc_map[1] = PC_FREE1;
3531 pc->pc_map[2] = PC_FREE2;
3532 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3533 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3534 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3537 * The reclaim might have freed a chunk from the current pmap.
3538 * If that chunk contained available entries, we need to
3539 * re-count the number of available entries.
3544 if (!TAILQ_EMPTY(&new_tail)) {
3545 mtx_lock(&pv_chunks_mutex);
3546 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3547 mtx_unlock(&pv_chunks_mutex);
3552 * First find and then remove the pv entry for the specified pmap and virtual
3553 * address from the specified pv list. Returns the pv entry if found and NULL
3554 * otherwise. This operation can be performed on pv lists for either 4KB or
3555 * 2MB page mappings.
3557 static __inline pv_entry_t
3558 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3562 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3563 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3564 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3573 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3574 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3575 * entries for each of the 4KB page mappings.
3578 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3579 struct rwlock **lockp)
3581 struct md_page *pvh;
3582 struct pv_chunk *pc;
3584 vm_offset_t va_last;
3588 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3589 KASSERT((pa & PDRMASK) == 0,
3590 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3591 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3594 * Transfer the 2mpage's pv entry for this mapping to the first
3595 * page's pv list. Once this transfer begins, the pv list lock
3596 * must not be released until the last pv entry is reinstantiated.
3598 pvh = pa_to_pvh(pa);
3599 va = trunc_2mpage(va);
3600 pv = pmap_pvh_remove(pvh, pmap, va);
3601 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3602 m = PHYS_TO_VM_PAGE(pa);
3603 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3605 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3606 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3607 va_last = va + NBPDR - PAGE_SIZE;
3609 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3610 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3611 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3612 for (field = 0; field < _NPCM; field++) {
3613 while (pc->pc_map[field]) {
3614 bit = bsfq(pc->pc_map[field]);
3615 pc->pc_map[field] &= ~(1ul << bit);
3616 pv = &pc->pc_pventry[field * 64 + bit];
3620 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3621 ("pmap_pv_demote_pde: page %p is not managed", m));
3622 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3628 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3629 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3632 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3633 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3634 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3636 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3637 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3640 #if VM_NRESERVLEVEL > 0
3642 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3643 * replace the many pv entries for the 4KB page mappings by a single pv entry
3644 * for the 2MB page mapping.
3647 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3648 struct rwlock **lockp)
3650 struct md_page *pvh;
3652 vm_offset_t va_last;
3655 KASSERT((pa & PDRMASK) == 0,
3656 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3657 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3660 * Transfer the first page's pv entry for this mapping to the 2mpage's
3661 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3662 * a transfer avoids the possibility that get_pv_entry() calls
3663 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3664 * mappings that is being promoted.
3666 m = PHYS_TO_VM_PAGE(pa);
3667 va = trunc_2mpage(va);
3668 pv = pmap_pvh_remove(&m->md, pmap, va);
3669 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3670 pvh = pa_to_pvh(pa);
3671 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3673 /* Free the remaining NPTEPG - 1 pv entries. */
3674 va_last = va + NBPDR - PAGE_SIZE;
3678 pmap_pvh_free(&m->md, pmap, va);
3679 } while (va < va_last);
3681 #endif /* VM_NRESERVLEVEL > 0 */
3684 * First find and then destroy the pv entry for the specified pmap and virtual
3685 * address. This operation can be performed on pv lists for either 4KB or 2MB
3689 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3693 pv = pmap_pvh_remove(pvh, pmap, va);
3694 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3695 free_pv_entry(pmap, pv);
3699 * Conditionally create the PV entry for a 4KB page mapping if the required
3700 * memory can be allocated without resorting to reclamation.
3703 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3704 struct rwlock **lockp)
3708 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3709 /* Pass NULL instead of the lock pointer to disable reclamation. */
3710 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3712 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3713 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3721 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3722 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3723 * false if the PV entry cannot be allocated without resorting to reclamation.
3726 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
3727 struct rwlock **lockp)
3729 struct md_page *pvh;
3733 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3734 /* Pass NULL instead of the lock pointer to disable reclamation. */
3735 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3736 NULL : lockp)) == NULL)
3739 pa = pde & PG_PS_FRAME;
3740 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3741 pvh = pa_to_pvh(pa);
3742 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3748 * Fills a page table page with mappings to consecutive physical pages.
3751 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3755 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3757 newpte += PAGE_SIZE;
3762 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3763 * mapping is invalidated.
3766 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3768 struct rwlock *lock;
3772 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3779 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3780 struct rwlock **lockp)
3782 pd_entry_t newpde, oldpde;
3783 pt_entry_t *firstpte, newpte;
3784 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3787 struct spglist free;
3791 PG_G = pmap_global_bit(pmap);
3792 PG_A = pmap_accessed_bit(pmap);
3793 PG_M = pmap_modified_bit(pmap);
3794 PG_RW = pmap_rw_bit(pmap);
3795 PG_V = pmap_valid_bit(pmap);
3796 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3798 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3800 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3801 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3802 if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
3804 KASSERT((oldpde & PG_W) == 0,
3805 ("pmap_demote_pde: page table page for a wired mapping"
3809 * Invalidate the 2MB page mapping and return "failure" if the
3810 * mapping was never accessed or the allocation of the new
3811 * page table page fails. If the 2MB page mapping belongs to
3812 * the direct map region of the kernel's address space, then
3813 * the page allocation request specifies the highest possible
3814 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3815 * normal. Page table pages are preallocated for every other
3816 * part of the kernel address space, so the direct map region
3817 * is the only part of the kernel address space that must be
3820 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3821 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3822 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3823 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3825 sva = trunc_2mpage(va);
3826 pmap_remove_pde(pmap, pde, sva, &free, lockp);
3827 if ((oldpde & PG_G) == 0)
3828 pmap_invalidate_pde_page(pmap, sva, oldpde);
3829 pmap_free_zero_pages(&free);
3830 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3831 " in pmap %p", va, pmap);
3834 if (va < VM_MAXUSER_ADDRESS)
3835 pmap_resident_count_inc(pmap, 1);
3837 mptepa = VM_PAGE_TO_PHYS(mpte);
3838 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3839 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3840 KASSERT((oldpde & PG_A) != 0,
3841 ("pmap_demote_pde: oldpde is missing PG_A"));
3842 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3843 ("pmap_demote_pde: oldpde is missing PG_M"));
3844 newpte = oldpde & ~PG_PS;
3845 newpte = pmap_swap_pat(pmap, newpte);
3848 * If the page table page is new, initialize it.
3850 if (mpte->wire_count == 1) {
3851 mpte->wire_count = NPTEPG;
3852 pmap_fill_ptp(firstpte, newpte);
3854 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3855 ("pmap_demote_pde: firstpte and newpte map different physical"
3859 * If the mapping has changed attributes, update the page table
3862 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3863 pmap_fill_ptp(firstpte, newpte);
3866 * The spare PV entries must be reserved prior to demoting the
3867 * mapping, that is, prior to changing the PDE. Otherwise, the state
3868 * of the PDE and the PV lists will be inconsistent, which can result
3869 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3870 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3871 * PV entry for the 2MB page mapping that is being demoted.
3873 if ((oldpde & PG_MANAGED) != 0)
3874 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3877 * Demote the mapping. This pmap is locked. The old PDE has
3878 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3879 * set. Thus, there is no danger of a race with another
3880 * processor changing the setting of PG_A and/or PG_M between
3881 * the read above and the store below.
3883 if (workaround_erratum383)
3884 pmap_update_pde(pmap, va, pde, newpde);
3886 pde_store(pde, newpde);
3889 * Invalidate a stale recursive mapping of the page table page.
3891 if (va >= VM_MAXUSER_ADDRESS)
3892 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3895 * Demote the PV entry.
3897 if ((oldpde & PG_MANAGED) != 0)
3898 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3900 atomic_add_long(&pmap_pde_demotions, 1);
3901 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3902 " in pmap %p", va, pmap);
3907 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3910 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3916 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3917 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3918 mpte = pmap_remove_pt_page(pmap, va);
3920 panic("pmap_remove_kernel_pde: Missing pt page.");
3922 mptepa = VM_PAGE_TO_PHYS(mpte);
3923 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3926 * Initialize the page table page.
3928 pagezero((void *)PHYS_TO_DMAP(mptepa));
3931 * Demote the mapping.
3933 if (workaround_erratum383)
3934 pmap_update_pde(pmap, va, pde, newpde);
3936 pde_store(pde, newpde);
3939 * Invalidate a stale recursive mapping of the page table page.
3941 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3945 * pmap_remove_pde: do the things to unmap a superpage in a process
3948 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
3949 struct spglist *free, struct rwlock **lockp)
3951 struct md_page *pvh;
3953 vm_offset_t eva, va;
3955 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3957 PG_G = pmap_global_bit(pmap);
3958 PG_A = pmap_accessed_bit(pmap);
3959 PG_M = pmap_modified_bit(pmap);
3960 PG_RW = pmap_rw_bit(pmap);
3962 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3963 KASSERT((sva & PDRMASK) == 0,
3964 ("pmap_remove_pde: sva is not 2mpage aligned"));
3965 oldpde = pte_load_clear(pdq);
3967 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
3968 if ((oldpde & PG_G) != 0)
3969 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
3970 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
3971 if (oldpde & PG_MANAGED) {
3972 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
3973 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
3974 pmap_pvh_free(pvh, pmap, sva);
3976 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3977 va < eva; va += PAGE_SIZE, m++) {
3978 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3981 vm_page_aflag_set(m, PGA_REFERENCED);
3982 if (TAILQ_EMPTY(&m->md.pv_list) &&
3983 TAILQ_EMPTY(&pvh->pv_list))
3984 vm_page_aflag_clear(m, PGA_WRITEABLE);
3985 pmap_delayed_invl_page(m);
3988 if (pmap == kernel_pmap) {
3989 pmap_remove_kernel_pde(pmap, pdq, sva);
3991 mpte = pmap_remove_pt_page(pmap, sva);
3993 pmap_resident_count_dec(pmap, 1);
3994 KASSERT(mpte->wire_count == NPTEPG,
3995 ("pmap_remove_pde: pte page wire count error"));
3996 mpte->wire_count = 0;
3997 pmap_add_delayed_free_list(mpte, free, FALSE);
4000 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
4004 * pmap_remove_pte: do the things to unmap a page in a process
4007 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
4008 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
4010 struct md_page *pvh;
4011 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
4014 PG_A = pmap_accessed_bit(pmap);
4015 PG_M = pmap_modified_bit(pmap);
4016 PG_RW = pmap_rw_bit(pmap);
4018 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4019 oldpte = pte_load_clear(ptq);
4021 pmap->pm_stats.wired_count -= 1;
4022 pmap_resident_count_dec(pmap, 1);
4023 if (oldpte & PG_MANAGED) {
4024 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
4025 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4028 vm_page_aflag_set(m, PGA_REFERENCED);
4029 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
4030 pmap_pvh_free(&m->md, pmap, va);
4031 if (TAILQ_EMPTY(&m->md.pv_list) &&
4032 (m->flags & PG_FICTITIOUS) == 0) {
4033 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4034 if (TAILQ_EMPTY(&pvh->pv_list))
4035 vm_page_aflag_clear(m, PGA_WRITEABLE);
4037 pmap_delayed_invl_page(m);
4039 return (pmap_unuse_pt(pmap, va, ptepde, free));
4043 * Remove a single page from a process address space
4046 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
4047 struct spglist *free)
4049 struct rwlock *lock;
4050 pt_entry_t *pte, PG_V;
4052 PG_V = pmap_valid_bit(pmap);
4053 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4054 if ((*pde & PG_V) == 0)
4056 pte = pmap_pde_to_pte(pde, va);
4057 if ((*pte & PG_V) == 0)
4060 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
4063 pmap_invalidate_page(pmap, va);
4067 * Removes the specified range of addresses from the page table page.
4070 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
4071 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
4073 pt_entry_t PG_G, *pte;
4077 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4078 PG_G = pmap_global_bit(pmap);
4081 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
4085 pmap_invalidate_range(pmap, va, sva);
4090 if ((*pte & PG_G) == 0)
4094 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
4100 pmap_invalidate_range(pmap, va, sva);
4105 * Remove the given range of addresses from the specified map.
4107 * It is assumed that the start and end are properly
4108 * rounded to the page size.
4111 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4113 struct rwlock *lock;
4114 vm_offset_t va_next;
4115 pml4_entry_t *pml4e;
4117 pd_entry_t ptpaddr, *pde;
4118 pt_entry_t PG_G, PG_V;
4119 struct spglist free;
4122 PG_G = pmap_global_bit(pmap);
4123 PG_V = pmap_valid_bit(pmap);
4126 * Perform an unsynchronized read. This is, however, safe.
4128 if (pmap->pm_stats.resident_count == 0)
4134 pmap_delayed_invl_started();
4138 * special handling of removing one page. a very
4139 * common operation and easy to short circuit some
4142 if (sva + PAGE_SIZE == eva) {
4143 pde = pmap_pde(pmap, sva);
4144 if (pde && (*pde & PG_PS) == 0) {
4145 pmap_remove_page(pmap, sva, pde, &free);
4151 for (; sva < eva; sva = va_next) {
4153 if (pmap->pm_stats.resident_count == 0)
4156 pml4e = pmap_pml4e(pmap, sva);
4157 if ((*pml4e & PG_V) == 0) {
4158 va_next = (sva + NBPML4) & ~PML4MASK;
4164 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4165 if ((*pdpe & PG_V) == 0) {
4166 va_next = (sva + NBPDP) & ~PDPMASK;
4173 * Calculate index for next page table.
4175 va_next = (sva + NBPDR) & ~PDRMASK;
4179 pde = pmap_pdpe_to_pde(pdpe, sva);
4183 * Weed out invalid mappings.
4189 * Check for large page.
4191 if ((ptpaddr & PG_PS) != 0) {
4193 * Are we removing the entire large page? If not,
4194 * demote the mapping and fall through.
4196 if (sva + NBPDR == va_next && eva >= va_next) {
4198 * The TLB entry for a PG_G mapping is
4199 * invalidated by pmap_remove_pde().
4201 if ((ptpaddr & PG_G) == 0)
4203 pmap_remove_pde(pmap, pde, sva, &free, &lock);
4205 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
4207 /* The large page mapping was destroyed. */
4214 * Limit our scan to either the end of the va represented
4215 * by the current page table page, or to the end of the
4216 * range being removed.
4221 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
4228 pmap_invalidate_all(pmap);
4230 pmap_delayed_invl_finished();
4231 pmap_free_zero_pages(&free);
4235 * Routine: pmap_remove_all
4237 * Removes this physical page from
4238 * all physical maps in which it resides.
4239 * Reflects back modify bits to the pager.
4242 * Original versions of this routine were very
4243 * inefficient because they iteratively called
4244 * pmap_remove (slow...)
4248 pmap_remove_all(vm_page_t m)
4250 struct md_page *pvh;
4253 struct rwlock *lock;
4254 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
4257 struct spglist free;
4258 int pvh_gen, md_gen;
4260 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4261 ("pmap_remove_all: page %p is not managed", m));
4263 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4264 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
4265 pa_to_pvh(VM_PAGE_TO_PHYS(m));
4268 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
4270 if (!PMAP_TRYLOCK(pmap)) {
4271 pvh_gen = pvh->pv_gen;
4275 if (pvh_gen != pvh->pv_gen) {
4282 pde = pmap_pde(pmap, va);
4283 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
4286 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4288 if (!PMAP_TRYLOCK(pmap)) {
4289 pvh_gen = pvh->pv_gen;
4290 md_gen = m->md.pv_gen;
4294 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
4300 PG_A = pmap_accessed_bit(pmap);
4301 PG_M = pmap_modified_bit(pmap);
4302 PG_RW = pmap_rw_bit(pmap);
4303 pmap_resident_count_dec(pmap, 1);
4304 pde = pmap_pde(pmap, pv->pv_va);
4305 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
4306 " a 2mpage in page %p's pv list", m));
4307 pte = pmap_pde_to_pte(pde, pv->pv_va);
4308 tpte = pte_load_clear(pte);
4310 pmap->pm_stats.wired_count--;
4312 vm_page_aflag_set(m, PGA_REFERENCED);
4315 * Update the vm_page_t clean and reference bits.
4317 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4319 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
4320 pmap_invalidate_page(pmap, pv->pv_va);
4321 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4323 free_pv_entry(pmap, pv);
4326 vm_page_aflag_clear(m, PGA_WRITEABLE);
4328 pmap_delayed_invl_wait(m);
4329 pmap_free_zero_pages(&free);
4333 * pmap_protect_pde: do the things to protect a 2mpage in a process
4336 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
4338 pd_entry_t newpde, oldpde;
4339 vm_offset_t eva, va;
4341 boolean_t anychanged;
4342 pt_entry_t PG_G, PG_M, PG_RW;
4344 PG_G = pmap_global_bit(pmap);
4345 PG_M = pmap_modified_bit(pmap);
4346 PG_RW = pmap_rw_bit(pmap);
4348 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4349 KASSERT((sva & PDRMASK) == 0,
4350 ("pmap_protect_pde: sva is not 2mpage aligned"));
4353 oldpde = newpde = *pde;
4354 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4355 (PG_MANAGED | PG_M | PG_RW)) {
4357 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4358 va < eva; va += PAGE_SIZE, m++)
4361 if ((prot & VM_PROT_WRITE) == 0)
4362 newpde &= ~(PG_RW | PG_M);
4363 if ((prot & VM_PROT_EXECUTE) == 0)
4365 if (newpde != oldpde) {
4367 * As an optimization to future operations on this PDE, clear
4368 * PG_PROMOTED. The impending invalidation will remove any
4369 * lingering 4KB page mappings from the TLB.
4371 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
4373 if ((oldpde & PG_G) != 0)
4374 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4378 return (anychanged);
4382 * Set the physical protection on the
4383 * specified range of this map as requested.
4386 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4388 vm_offset_t va_next;
4389 pml4_entry_t *pml4e;
4391 pd_entry_t ptpaddr, *pde;
4392 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4393 boolean_t anychanged;
4395 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4396 if (prot == VM_PROT_NONE) {
4397 pmap_remove(pmap, sva, eva);
4401 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4402 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4405 PG_G = pmap_global_bit(pmap);
4406 PG_M = pmap_modified_bit(pmap);
4407 PG_V = pmap_valid_bit(pmap);
4408 PG_RW = pmap_rw_bit(pmap);
4412 * Although this function delays and batches the invalidation
4413 * of stale TLB entries, it does not need to call
4414 * pmap_delayed_invl_started() and
4415 * pmap_delayed_invl_finished(), because it does not
4416 * ordinarily destroy mappings. Stale TLB entries from
4417 * protection-only changes need only be invalidated before the
4418 * pmap lock is released, because protection-only changes do
4419 * not destroy PV entries. Even operations that iterate over
4420 * a physical page's PV list of mappings, like
4421 * pmap_remove_write(), acquire the pmap lock for each
4422 * mapping. Consequently, for protection-only changes, the
4423 * pmap lock suffices to synchronize both page table and TLB
4426 * This function only destroys a mapping if pmap_demote_pde()
4427 * fails. In that case, stale TLB entries are immediately
4432 for (; sva < eva; sva = va_next) {
4434 pml4e = pmap_pml4e(pmap, sva);
4435 if ((*pml4e & PG_V) == 0) {
4436 va_next = (sva + NBPML4) & ~PML4MASK;
4442 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4443 if ((*pdpe & PG_V) == 0) {
4444 va_next = (sva + NBPDP) & ~PDPMASK;
4450 va_next = (sva + NBPDR) & ~PDRMASK;
4454 pde = pmap_pdpe_to_pde(pdpe, sva);
4458 * Weed out invalid mappings.
4464 * Check for large page.
4466 if ((ptpaddr & PG_PS) != 0) {
4468 * Are we protecting the entire large page? If not,
4469 * demote the mapping and fall through.
4471 if (sva + NBPDR == va_next && eva >= va_next) {
4473 * The TLB entry for a PG_G mapping is
4474 * invalidated by pmap_protect_pde().
4476 if (pmap_protect_pde(pmap, pde, sva, prot))
4479 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4481 * The large page mapping was destroyed.
4490 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4492 pt_entry_t obits, pbits;
4496 obits = pbits = *pte;
4497 if ((pbits & PG_V) == 0)
4500 if ((prot & VM_PROT_WRITE) == 0) {
4501 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4502 (PG_MANAGED | PG_M | PG_RW)) {
4503 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4506 pbits &= ~(PG_RW | PG_M);
4508 if ((prot & VM_PROT_EXECUTE) == 0)
4511 if (pbits != obits) {
4512 if (!atomic_cmpset_long(pte, obits, pbits))
4515 pmap_invalidate_page(pmap, sva);
4522 pmap_invalidate_all(pmap);
4526 #if VM_NRESERVLEVEL > 0
4528 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4529 * single page table page (PTP) to a single 2MB page mapping. For promotion
4530 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4531 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4532 * identical characteristics.
4535 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4536 struct rwlock **lockp)
4539 pt_entry_t *firstpte, oldpte, pa, *pte;
4540 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4544 PG_A = pmap_accessed_bit(pmap);
4545 PG_G = pmap_global_bit(pmap);
4546 PG_M = pmap_modified_bit(pmap);
4547 PG_V = pmap_valid_bit(pmap);
4548 PG_RW = pmap_rw_bit(pmap);
4549 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4551 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4554 * Examine the first PTE in the specified PTP. Abort if this PTE is
4555 * either invalid, unused, or does not map the first 4KB physical page
4556 * within a 2MB page.
4558 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4561 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4562 atomic_add_long(&pmap_pde_p_failures, 1);
4563 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4564 " in pmap %p", va, pmap);
4567 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4569 * When PG_M is already clear, PG_RW can be cleared without
4570 * a TLB invalidation.
4572 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4578 * Examine each of the other PTEs in the specified PTP. Abort if this
4579 * PTE maps an unexpected 4KB physical page or does not have identical
4580 * characteristics to the first PTE.
4582 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4583 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4586 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4587 atomic_add_long(&pmap_pde_p_failures, 1);
4588 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4589 " in pmap %p", va, pmap);
4592 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4594 * When PG_M is already clear, PG_RW can be cleared
4595 * without a TLB invalidation.
4597 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4600 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4601 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4602 (va & ~PDRMASK), pmap);
4604 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4605 atomic_add_long(&pmap_pde_p_failures, 1);
4606 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4607 " in pmap %p", va, pmap);
4614 * Save the page table page in its current state until the PDE
4615 * mapping the superpage is demoted by pmap_demote_pde() or
4616 * destroyed by pmap_remove_pde().
4618 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4619 KASSERT(mpte >= vm_page_array &&
4620 mpte < &vm_page_array[vm_page_array_size],
4621 ("pmap_promote_pde: page table page is out of range"));
4622 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4623 ("pmap_promote_pde: page table page's pindex is wrong"));
4624 if (pmap_insert_pt_page(pmap, mpte)) {
4625 atomic_add_long(&pmap_pde_p_failures, 1);
4627 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4633 * Promote the pv entries.
4635 if ((newpde & PG_MANAGED) != 0)
4636 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4639 * Propagate the PAT index to its proper position.
4641 newpde = pmap_swap_pat(pmap, newpde);
4644 * Map the superpage.
4646 if (workaround_erratum383)
4647 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4649 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
4651 atomic_add_long(&pmap_pde_promotions, 1);
4652 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4653 " in pmap %p", va, pmap);
4655 #endif /* VM_NRESERVLEVEL > 0 */
4658 * Insert the given physical page (p) at
4659 * the specified virtual address (v) in the
4660 * target physical map with the protection requested.
4662 * If specified, the page will be wired down, meaning
4663 * that the related pte can not be reclaimed.
4665 * NB: This is the only routine which MAY NOT lazy-evaluate
4666 * or lose information. That is, this routine must actually
4667 * insert this page into the given map NOW.
4669 * When destroying both a page table and PV entry, this function
4670 * performs the TLB invalidation before releasing the PV list
4671 * lock, so we do not need pmap_delayed_invl_page() calls here.
4674 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4675 u_int flags, int8_t psind)
4677 struct rwlock *lock;
4679 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4680 pt_entry_t newpte, origpte;
4687 PG_A = pmap_accessed_bit(pmap);
4688 PG_G = pmap_global_bit(pmap);
4689 PG_M = pmap_modified_bit(pmap);
4690 PG_V = pmap_valid_bit(pmap);
4691 PG_RW = pmap_rw_bit(pmap);
4693 va = trunc_page(va);
4694 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4695 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4696 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4698 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4699 va >= kmi.clean_eva,
4700 ("pmap_enter: managed mapping within the clean submap"));
4701 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4702 VM_OBJECT_ASSERT_LOCKED(m->object);
4703 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
4704 ("pmap_enter: flags %u has reserved bits set", flags));
4705 pa = VM_PAGE_TO_PHYS(m);
4706 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4707 if ((flags & VM_PROT_WRITE) != 0)
4709 if ((prot & VM_PROT_WRITE) != 0)
4711 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4712 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4713 if ((prot & VM_PROT_EXECUTE) == 0)
4715 if ((flags & PMAP_ENTER_WIRED) != 0)
4717 if (va < VM_MAXUSER_ADDRESS)
4719 if (pmap == kernel_pmap)
4721 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
4724 * Set modified bit gratuitously for writeable mappings if
4725 * the page is unmanaged. We do not want to take a fault
4726 * to do the dirty bit accounting for these mappings.
4728 if ((m->oflags & VPO_UNMANAGED) != 0) {
4729 if ((newpte & PG_RW) != 0)
4732 newpte |= PG_MANAGED;
4737 /* Assert the required virtual and physical alignment. */
4738 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
4739 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4740 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
4746 * In the case that a page table page is not
4747 * resident, we are creating it here.
4750 pde = pmap_pde(pmap, va);
4751 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4752 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4753 pte = pmap_pde_to_pte(pde, va);
4754 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4755 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4758 } else if (va < VM_MAXUSER_ADDRESS) {
4760 * Here if the pte page isn't mapped, or if it has been
4763 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4764 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4765 nosleep ? NULL : &lock);
4766 if (mpte == NULL && nosleep) {
4767 rv = KERN_RESOURCE_SHORTAGE;
4772 panic("pmap_enter: invalid page directory va=%#lx", va);
4778 * Is the specified virtual address already mapped?
4780 if ((origpte & PG_V) != 0) {
4782 * Wiring change, just update stats. We don't worry about
4783 * wiring PT pages as they remain resident as long as there
4784 * are valid mappings in them. Hence, if a user page is wired,
4785 * the PT page will be also.
4787 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4788 pmap->pm_stats.wired_count++;
4789 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4790 pmap->pm_stats.wired_count--;
4793 * Remove the extra PT page reference.
4797 KASSERT(mpte->wire_count > 0,
4798 ("pmap_enter: missing reference to page table page,"
4803 * Has the physical page changed?
4805 opa = origpte & PG_FRAME;
4808 * No, might be a protection or wiring change.
4810 if ((origpte & PG_MANAGED) != 0 &&
4811 (newpte & PG_RW) != 0)
4812 vm_page_aflag_set(m, PGA_WRITEABLE);
4813 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4819 * The physical page has changed. Temporarily invalidate
4820 * the mapping. This ensures that all threads sharing the
4821 * pmap keep a consistent view of the mapping, which is
4822 * necessary for the correct handling of COW faults. It
4823 * also permits reuse of the old mapping's PV entry,
4824 * avoiding an allocation.
4826 * For consistency, handle unmanaged mappings the same way.
4828 origpte = pte_load_clear(pte);
4829 KASSERT((origpte & PG_FRAME) == opa,
4830 ("pmap_enter: unexpected pa update for %#lx", va));
4831 if ((origpte & PG_MANAGED) != 0) {
4832 om = PHYS_TO_VM_PAGE(opa);
4835 * The pmap lock is sufficient to synchronize with
4836 * concurrent calls to pmap_page_test_mappings() and
4837 * pmap_ts_referenced().
4839 if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4841 if ((origpte & PG_A) != 0)
4842 vm_page_aflag_set(om, PGA_REFERENCED);
4843 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4844 pv = pmap_pvh_remove(&om->md, pmap, va);
4845 if ((newpte & PG_MANAGED) == 0)
4846 free_pv_entry(pmap, pv);
4847 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4848 TAILQ_EMPTY(&om->md.pv_list) &&
4849 ((om->flags & PG_FICTITIOUS) != 0 ||
4850 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4851 vm_page_aflag_clear(om, PGA_WRITEABLE);
4853 if ((origpte & PG_A) != 0)
4854 pmap_invalidate_page(pmap, va);
4858 * Increment the counters.
4860 if ((newpte & PG_W) != 0)
4861 pmap->pm_stats.wired_count++;
4862 pmap_resident_count_inc(pmap, 1);
4866 * Enter on the PV list if part of our managed memory.
4868 if ((newpte & PG_MANAGED) != 0) {
4870 pv = get_pv_entry(pmap, &lock);
4873 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4874 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4876 if ((newpte & PG_RW) != 0)
4877 vm_page_aflag_set(m, PGA_WRITEABLE);
4883 if ((origpte & PG_V) != 0) {
4885 origpte = pte_load_store(pte, newpte);
4886 KASSERT((origpte & PG_FRAME) == pa,
4887 ("pmap_enter: unexpected pa update for %#lx", va));
4888 if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
4890 if ((origpte & PG_MANAGED) != 0)
4894 * Although the PTE may still have PG_RW set, TLB
4895 * invalidation may nonetheless be required because
4896 * the PTE no longer has PG_M set.
4898 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4900 * This PTE change does not require TLB invalidation.
4904 if ((origpte & PG_A) != 0)
4905 pmap_invalidate_page(pmap, va);
4907 pte_store(pte, newpte);
4911 #if VM_NRESERVLEVEL > 0
4913 * If both the page table page and the reservation are fully
4914 * populated, then attempt promotion.
4916 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4917 pmap_ps_enabled(pmap) &&
4918 (m->flags & PG_FICTITIOUS) == 0 &&
4919 vm_reserv_level_iffullpop(m) == 0)
4920 pmap_promote_pde(pmap, pde, va, &lock);
4932 * Tries to create a read- and/or execute-only 2MB page mapping. Returns true
4933 * if successful. Returns false if (1) a page table page cannot be allocated
4934 * without sleeping, (2) a mapping already exists at the specified virtual
4935 * address, or (3) a PV entry cannot be allocated without reclaiming another
4939 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4940 struct rwlock **lockp)
4945 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4946 PG_V = pmap_valid_bit(pmap);
4947 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
4949 if ((m->oflags & VPO_UNMANAGED) == 0)
4950 newpde |= PG_MANAGED;
4951 if ((prot & VM_PROT_EXECUTE) == 0)
4953 if (va < VM_MAXUSER_ADDRESS)
4955 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
4956 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
4961 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
4962 * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
4963 * otherwise. Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
4964 * a mapping already exists at the specified virtual address. Returns
4965 * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
4966 * page allocation failed. Returns KERN_RESOURCE_SHORTAGE if
4967 * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
4969 * The parameter "m" is only used when creating a managed, writeable mapping.
4972 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
4973 vm_page_t m, struct rwlock **lockp)
4975 struct spglist free;
4976 pd_entry_t oldpde, *pde;
4977 pt_entry_t PG_G, PG_RW, PG_V;
4980 PG_G = pmap_global_bit(pmap);
4981 PG_RW = pmap_rw_bit(pmap);
4982 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
4983 ("pmap_enter_pde: newpde is missing PG_M"));
4984 PG_V = pmap_valid_bit(pmap);
4985 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4987 if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
4988 NULL : lockp)) == NULL) {
4989 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4990 " in pmap %p", va, pmap);
4991 return (KERN_RESOURCE_SHORTAGE);
4993 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4994 pde = &pde[pmap_pde_index(va)];
4996 if ((oldpde & PG_V) != 0) {
4997 KASSERT(pdpg->wire_count > 1,
4998 ("pmap_enter_pde: pdpg's wire count is too low"));
4999 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
5001 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5002 " in pmap %p", va, pmap);
5003 return (KERN_FAILURE);
5005 /* Break the existing mapping(s). */
5007 if ((oldpde & PG_PS) != 0) {
5009 * The reference to the PD page that was acquired by
5010 * pmap_allocpde() ensures that it won't be freed.
5011 * However, if the PDE resulted from a promotion, then
5012 * a reserved PT page could be freed.
5014 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
5015 if ((oldpde & PG_G) == 0)
5016 pmap_invalidate_pde_page(pmap, va, oldpde);
5018 pmap_delayed_invl_started();
5019 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
5021 pmap_invalidate_all(pmap);
5022 pmap_delayed_invl_finished();
5024 pmap_free_zero_pages(&free);
5025 if (va >= VM_MAXUSER_ADDRESS) {
5026 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
5027 if (pmap_insert_pt_page(pmap, mt)) {
5029 * XXX Currently, this can't happen because
5030 * we do not perform pmap_enter(psind == 1)
5031 * on the kernel pmap.
5033 panic("pmap_enter_pde: trie insert failed");
5036 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
5039 if ((newpde & PG_MANAGED) != 0) {
5041 * Abort this mapping if its PV entry could not be created.
5043 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
5045 if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
5047 * Although "va" is not mapped, paging-
5048 * structure caches could nonetheless have
5049 * entries that refer to the freed page table
5050 * pages. Invalidate those entries.
5052 pmap_invalidate_page(pmap, va);
5053 pmap_free_zero_pages(&free);
5055 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5056 " in pmap %p", va, pmap);
5057 return (KERN_RESOURCE_SHORTAGE);
5059 if ((newpde & PG_RW) != 0) {
5060 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5061 vm_page_aflag_set(mt, PGA_WRITEABLE);
5066 * Increment counters.
5068 if ((newpde & PG_W) != 0)
5069 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
5070 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5073 * Map the superpage. (This is not a promoted mapping; there will not
5074 * be any lingering 4KB page mappings in the TLB.)
5076 pde_store(pde, newpde);
5078 atomic_add_long(&pmap_pde_mappings, 1);
5079 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
5080 " in pmap %p", va, pmap);
5081 return (KERN_SUCCESS);
5085 * Maps a sequence of resident pages belonging to the same object.
5086 * The sequence begins with the given page m_start. This page is
5087 * mapped at the given virtual address start. Each subsequent page is
5088 * mapped at a virtual address that is offset from start by the same
5089 * amount as the page is offset from m_start within the object. The
5090 * last page in the sequence is the page with the largest offset from
5091 * m_start that can be mapped at a virtual address less than the given
5092 * virtual address end. Not every virtual page between start and end
5093 * is mapped; only those for which a resident page exists with the
5094 * corresponding offset from m_start are mapped.
5097 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
5098 vm_page_t m_start, vm_prot_t prot)
5100 struct rwlock *lock;
5103 vm_pindex_t diff, psize;
5105 VM_OBJECT_ASSERT_LOCKED(m_start->object);
5107 psize = atop(end - start);
5112 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
5113 va = start + ptoa(diff);
5114 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
5115 m->psind == 1 && pmap_ps_enabled(pmap) &&
5116 pmap_enter_2mpage(pmap, va, m, prot, &lock))
5117 m = &m[NBPDR / PAGE_SIZE - 1];
5119 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
5121 m = TAILQ_NEXT(m, listq);
5129 * this code makes some *MAJOR* assumptions:
5130 * 1. Current pmap & pmap exists.
5133 * 4. No page table pages.
5134 * but is *MUCH* faster than pmap_enter...
5138 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
5140 struct rwlock *lock;
5144 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
5151 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
5152 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
5154 struct spglist free;
5155 pt_entry_t *pte, PG_V;
5158 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
5159 (m->oflags & VPO_UNMANAGED) != 0,
5160 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
5161 PG_V = pmap_valid_bit(pmap);
5162 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5165 * In the case that a page table page is not
5166 * resident, we are creating it here.
5168 if (va < VM_MAXUSER_ADDRESS) {
5169 vm_pindex_t ptepindex;
5173 * Calculate pagetable page index
5175 ptepindex = pmap_pde_pindex(va);
5176 if (mpte && (mpte->pindex == ptepindex)) {
5180 * Get the page directory entry
5182 ptepa = pmap_pde(pmap, va);
5185 * If the page table page is mapped, we just increment
5186 * the hold count, and activate it. Otherwise, we
5187 * attempt to allocate a page table page. If this
5188 * attempt fails, we don't retry. Instead, we give up.
5190 if (ptepa && (*ptepa & PG_V) != 0) {
5193 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
5197 * Pass NULL instead of the PV list lock
5198 * pointer, because we don't intend to sleep.
5200 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
5205 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
5206 pte = &pte[pmap_pte_index(va)];
5220 * Enter on the PV list if part of our managed memory.
5222 if ((m->oflags & VPO_UNMANAGED) == 0 &&
5223 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
5226 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
5228 * Although "va" is not mapped, paging-
5229 * structure caches could nonetheless have
5230 * entries that refer to the freed page table
5231 * pages. Invalidate those entries.
5233 pmap_invalidate_page(pmap, va);
5234 pmap_free_zero_pages(&free);
5242 * Increment counters
5244 pmap_resident_count_inc(pmap, 1);
5246 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
5247 if ((prot & VM_PROT_EXECUTE) == 0)
5251 * Now validate mapping with RO protection
5253 if ((m->oflags & VPO_UNMANAGED) != 0)
5254 pte_store(pte, pa | PG_V | PG_U);
5256 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
5261 * Make a temporary mapping for a physical address. This is only intended
5262 * to be used for panic dumps.
5265 pmap_kenter_temporary(vm_paddr_t pa, int i)
5269 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
5270 pmap_kenter(va, pa);
5272 return ((void *)crashdumpmap);
5276 * This code maps large physical mmap regions into the
5277 * processor address space. Note that some shortcuts
5278 * are taken, but the code works.
5281 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
5282 vm_pindex_t pindex, vm_size_t size)
5285 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5286 vm_paddr_t pa, ptepa;
5290 PG_A = pmap_accessed_bit(pmap);
5291 PG_M = pmap_modified_bit(pmap);
5292 PG_V = pmap_valid_bit(pmap);
5293 PG_RW = pmap_rw_bit(pmap);
5295 VM_OBJECT_ASSERT_WLOCKED(object);
5296 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
5297 ("pmap_object_init_pt: non-device object"));
5298 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
5299 if (!pmap_ps_enabled(pmap))
5301 if (!vm_object_populate(object, pindex, pindex + atop(size)))
5303 p = vm_page_lookup(object, pindex);
5304 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5305 ("pmap_object_init_pt: invalid page %p", p));
5306 pat_mode = p->md.pat_mode;
5309 * Abort the mapping if the first page is not physically
5310 * aligned to a 2MB page boundary.
5312 ptepa = VM_PAGE_TO_PHYS(p);
5313 if (ptepa & (NBPDR - 1))
5317 * Skip the first page. Abort the mapping if the rest of
5318 * the pages are not physically contiguous or have differing
5319 * memory attributes.
5321 p = TAILQ_NEXT(p, listq);
5322 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
5324 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5325 ("pmap_object_init_pt: invalid page %p", p));
5326 if (pa != VM_PAGE_TO_PHYS(p) ||
5327 pat_mode != p->md.pat_mode)
5329 p = TAILQ_NEXT(p, listq);
5333 * Map using 2MB pages. Since "ptepa" is 2M aligned and
5334 * "size" is a multiple of 2M, adding the PAT setting to "pa"
5335 * will not affect the termination of this loop.
5338 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
5339 pa < ptepa + size; pa += NBPDR) {
5340 pdpg = pmap_allocpde(pmap, addr, NULL);
5343 * The creation of mappings below is only an
5344 * optimization. If a page directory page
5345 * cannot be allocated without blocking,
5346 * continue on to the next mapping rather than
5352 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5353 pde = &pde[pmap_pde_index(addr)];
5354 if ((*pde & PG_V) == 0) {
5355 pde_store(pde, pa | PG_PS | PG_M | PG_A |
5356 PG_U | PG_RW | PG_V);
5357 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5358 atomic_add_long(&pmap_pde_mappings, 1);
5360 /* Continue on if the PDE is already valid. */
5362 KASSERT(pdpg->wire_count > 0,
5363 ("pmap_object_init_pt: missing reference "
5364 "to page directory page, va: 0x%lx", addr));
5373 * Clear the wired attribute from the mappings for the specified range of
5374 * addresses in the given pmap. Every valid mapping within that range
5375 * must have the wired attribute set. In contrast, invalid mappings
5376 * cannot have the wired attribute set, so they are ignored.
5378 * The wired attribute of the page table entry is not a hardware
5379 * feature, so there is no need to invalidate any TLB entries.
5380 * Since pmap_demote_pde() for the wired entry must never fail,
5381 * pmap_delayed_invl_started()/finished() calls around the
5382 * function are not needed.
5385 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5387 vm_offset_t va_next;
5388 pml4_entry_t *pml4e;
5391 pt_entry_t *pte, PG_V;
5393 PG_V = pmap_valid_bit(pmap);
5395 for (; sva < eva; sva = va_next) {
5396 pml4e = pmap_pml4e(pmap, sva);
5397 if ((*pml4e & PG_V) == 0) {
5398 va_next = (sva + NBPML4) & ~PML4MASK;
5403 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5404 if ((*pdpe & PG_V) == 0) {
5405 va_next = (sva + NBPDP) & ~PDPMASK;
5410 va_next = (sva + NBPDR) & ~PDRMASK;
5413 pde = pmap_pdpe_to_pde(pdpe, sva);
5414 if ((*pde & PG_V) == 0)
5416 if ((*pde & PG_PS) != 0) {
5417 if ((*pde & PG_W) == 0)
5418 panic("pmap_unwire: pde %#jx is missing PG_W",
5422 * Are we unwiring the entire large page? If not,
5423 * demote the mapping and fall through.
5425 if (sva + NBPDR == va_next && eva >= va_next) {
5426 atomic_clear_long(pde, PG_W);
5427 pmap->pm_stats.wired_count -= NBPDR /
5430 } else if (!pmap_demote_pde(pmap, pde, sva))
5431 panic("pmap_unwire: demotion failed");
5435 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
5437 if ((*pte & PG_V) == 0)
5439 if ((*pte & PG_W) == 0)
5440 panic("pmap_unwire: pte %#jx is missing PG_W",
5444 * PG_W must be cleared atomically. Although the pmap
5445 * lock synchronizes access to PG_W, another processor
5446 * could be setting PG_M and/or PG_A concurrently.
5448 atomic_clear_long(pte, PG_W);
5449 pmap->pm_stats.wired_count--;
5456 * Copy the range specified by src_addr/len
5457 * from the source map to the range dst_addr/len
5458 * in the destination map.
5460 * This routine is only advisory and need not do anything.
5464 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5465 vm_offset_t src_addr)
5467 struct rwlock *lock;
5468 struct spglist free;
5470 vm_offset_t end_addr = src_addr + len;
5471 vm_offset_t va_next;
5472 vm_page_t dst_pdpg, dstmpte, srcmpte;
5473 pt_entry_t PG_A, PG_M, PG_V;
5475 if (dst_addr != src_addr)
5478 if (dst_pmap->pm_type != src_pmap->pm_type)
5482 * EPT page table entries that require emulation of A/D bits are
5483 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5484 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5485 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5486 * implementations flag an EPT misconfiguration for exec-only
5487 * mappings we skip this function entirely for emulated pmaps.
5489 if (pmap_emulate_ad_bits(dst_pmap))
5493 if (dst_pmap < src_pmap) {
5494 PMAP_LOCK(dst_pmap);
5495 PMAP_LOCK(src_pmap);
5497 PMAP_LOCK(src_pmap);
5498 PMAP_LOCK(dst_pmap);
5501 PG_A = pmap_accessed_bit(dst_pmap);
5502 PG_M = pmap_modified_bit(dst_pmap);
5503 PG_V = pmap_valid_bit(dst_pmap);
5505 for (addr = src_addr; addr < end_addr; addr = va_next) {
5506 pt_entry_t *src_pte, *dst_pte;
5507 pml4_entry_t *pml4e;
5509 pd_entry_t srcptepaddr, *pde;
5511 KASSERT(addr < UPT_MIN_ADDRESS,
5512 ("pmap_copy: invalid to pmap_copy page tables"));
5514 pml4e = pmap_pml4e(src_pmap, addr);
5515 if ((*pml4e & PG_V) == 0) {
5516 va_next = (addr + NBPML4) & ~PML4MASK;
5522 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5523 if ((*pdpe & PG_V) == 0) {
5524 va_next = (addr + NBPDP) & ~PDPMASK;
5530 va_next = (addr + NBPDR) & ~PDRMASK;
5534 pde = pmap_pdpe_to_pde(pdpe, addr);
5536 if (srcptepaddr == 0)
5539 if (srcptepaddr & PG_PS) {
5540 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5542 dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
5543 if (dst_pdpg == NULL)
5545 pde = (pd_entry_t *)
5546 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
5547 pde = &pde[pmap_pde_index(addr)];
5548 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5549 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
5550 PMAP_ENTER_NORECLAIM, &lock))) {
5551 *pde = srcptepaddr & ~PG_W;
5552 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5553 atomic_add_long(&pmap_pde_mappings, 1);
5555 dst_pdpg->wire_count--;
5559 srcptepaddr &= PG_FRAME;
5560 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5561 KASSERT(srcmpte->wire_count > 0,
5562 ("pmap_copy: source page table page is unused"));
5564 if (va_next > end_addr)
5567 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5568 src_pte = &src_pte[pmap_pte_index(addr)];
5570 while (addr < va_next) {
5574 * we only virtual copy managed pages
5576 if ((ptetemp & PG_MANAGED) != 0) {
5577 if (dstmpte != NULL &&
5578 dstmpte->pindex == pmap_pde_pindex(addr))
5579 dstmpte->wire_count++;
5580 else if ((dstmpte = pmap_allocpte(dst_pmap,
5581 addr, NULL)) == NULL)
5583 dst_pte = (pt_entry_t *)
5584 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5585 dst_pte = &dst_pte[pmap_pte_index(addr)];
5586 if (*dst_pte == 0 &&
5587 pmap_try_insert_pv_entry(dst_pmap, addr,
5588 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5591 * Clear the wired, modified, and
5592 * accessed (referenced) bits
5595 *dst_pte = ptetemp & ~(PG_W | PG_M |
5597 pmap_resident_count_inc(dst_pmap, 1);
5600 if (pmap_unwire_ptp(dst_pmap, addr,
5603 * Although "addr" is not
5604 * mapped, paging-structure
5605 * caches could nonetheless
5606 * have entries that refer to
5607 * the freed page table pages.
5608 * Invalidate those entries.
5610 pmap_invalidate_page(dst_pmap,
5612 pmap_free_zero_pages(&free);
5616 if (dstmpte->wire_count >= srcmpte->wire_count)
5626 PMAP_UNLOCK(src_pmap);
5627 PMAP_UNLOCK(dst_pmap);
5631 * pmap_zero_page zeros the specified hardware page by mapping
5632 * the page into KVM and using bzero to clear its contents.
5635 pmap_zero_page(vm_page_t m)
5637 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5639 pagezero((void *)va);
5643 * pmap_zero_page_area zeros the specified hardware page by mapping
5644 * the page into KVM and using bzero to clear its contents.
5646 * off and size may not cover an area beyond a single hardware page.
5649 pmap_zero_page_area(vm_page_t m, int off, int size)
5651 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5653 if (off == 0 && size == PAGE_SIZE)
5654 pagezero((void *)va);
5656 bzero((char *)va + off, size);
5660 * pmap_zero_page_idle zeros the specified hardware page by mapping
5661 * the page into KVM and using bzero to clear its contents. This
5662 * is intended to be called from the vm_pagezero process only and
5666 pmap_zero_page_idle(vm_page_t m)
5668 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5670 pagezero((void *)va);
5674 * pmap_copy_page copies the specified (machine independent)
5675 * page by mapping the page into virtual memory and using
5676 * bcopy to copy the page, one machine dependent page at a
5680 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5682 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5683 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5685 pagecopy((void *)src, (void *)dst);
5688 int unmapped_buf_allowed = 1;
5691 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5692 vm_offset_t b_offset, int xfersize)
5696 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5700 while (xfersize > 0) {
5701 a_pg_offset = a_offset & PAGE_MASK;
5702 pages[0] = ma[a_offset >> PAGE_SHIFT];
5703 b_pg_offset = b_offset & PAGE_MASK;
5704 pages[1] = mb[b_offset >> PAGE_SHIFT];
5705 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5706 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5707 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5708 a_cp = (char *)vaddr[0] + a_pg_offset;
5709 b_cp = (char *)vaddr[1] + b_pg_offset;
5710 bcopy(a_cp, b_cp, cnt);
5711 if (__predict_false(mapped))
5712 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5720 * Returns true if the pmap's pv is one of the first
5721 * 16 pvs linked to from this page. This count may
5722 * be changed upwards or downwards in the future; it
5723 * is only necessary that true be returned for a small
5724 * subset of pmaps for proper page aging.
5727 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5729 struct md_page *pvh;
5730 struct rwlock *lock;
5735 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5736 ("pmap_page_exists_quick: page %p is not managed", m));
5738 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5740 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5741 if (PV_PMAP(pv) == pmap) {
5749 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5750 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5751 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5752 if (PV_PMAP(pv) == pmap) {
5766 * pmap_page_wired_mappings:
5768 * Return the number of managed mappings to the given physical page
5772 pmap_page_wired_mappings(vm_page_t m)
5774 struct rwlock *lock;
5775 struct md_page *pvh;
5779 int count, md_gen, pvh_gen;
5781 if ((m->oflags & VPO_UNMANAGED) != 0)
5783 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5787 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5789 if (!PMAP_TRYLOCK(pmap)) {
5790 md_gen = m->md.pv_gen;
5794 if (md_gen != m->md.pv_gen) {
5799 pte = pmap_pte(pmap, pv->pv_va);
5800 if ((*pte & PG_W) != 0)
5804 if ((m->flags & PG_FICTITIOUS) == 0) {
5805 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5806 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5808 if (!PMAP_TRYLOCK(pmap)) {
5809 md_gen = m->md.pv_gen;
5810 pvh_gen = pvh->pv_gen;
5814 if (md_gen != m->md.pv_gen ||
5815 pvh_gen != pvh->pv_gen) {
5820 pte = pmap_pde(pmap, pv->pv_va);
5821 if ((*pte & PG_W) != 0)
5831 * Returns TRUE if the given page is mapped individually or as part of
5832 * a 2mpage. Otherwise, returns FALSE.
5835 pmap_page_is_mapped(vm_page_t m)
5837 struct rwlock *lock;
5840 if ((m->oflags & VPO_UNMANAGED) != 0)
5842 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5844 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5845 ((m->flags & PG_FICTITIOUS) == 0 &&
5846 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5852 * Destroy all managed, non-wired mappings in the given user-space
5853 * pmap. This pmap cannot be active on any processor besides the
5856 * This function cannot be applied to the kernel pmap. Moreover, it
5857 * is not intended for general use. It is only to be used during
5858 * process termination. Consequently, it can be implemented in ways
5859 * that make it faster than pmap_remove(). First, it can more quickly
5860 * destroy mappings by iterating over the pmap's collection of PV
5861 * entries, rather than searching the page table. Second, it doesn't
5862 * have to test and clear the page table entries atomically, because
5863 * no processor is currently accessing the user address space. In
5864 * particular, a page table entry's dirty bit won't change state once
5865 * this function starts.
5867 * Although this function destroys all of the pmap's managed,
5868 * non-wired mappings, it can delay and batch the invalidation of TLB
5869 * entries without calling pmap_delayed_invl_started() and
5870 * pmap_delayed_invl_finished(). Because the pmap is not active on
5871 * any other processor, none of these TLB entries will ever be used
5872 * before their eventual invalidation. Consequently, there is no need
5873 * for either pmap_remove_all() or pmap_remove_write() to wait for
5874 * that eventual TLB invalidation.
5877 pmap_remove_pages(pmap_t pmap)
5880 pt_entry_t *pte, tpte;
5881 pt_entry_t PG_M, PG_RW, PG_V;
5882 struct spglist free;
5883 vm_page_t m, mpte, mt;
5885 struct md_page *pvh;
5886 struct pv_chunk *pc, *npc;
5887 struct rwlock *lock;
5889 uint64_t inuse, bitmask;
5890 int allfree, field, freed, idx;
5891 boolean_t superpage;
5895 * Assert that the given pmap is only active on the current
5896 * CPU. Unfortunately, we cannot block another CPU from
5897 * activating the pmap while this function is executing.
5899 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5902 cpuset_t other_cpus;
5904 other_cpus = all_cpus;
5906 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5907 CPU_AND(&other_cpus, &pmap->pm_active);
5909 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5914 PG_M = pmap_modified_bit(pmap);
5915 PG_V = pmap_valid_bit(pmap);
5916 PG_RW = pmap_rw_bit(pmap);
5920 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5923 for (field = 0; field < _NPCM; field++) {
5924 inuse = ~pc->pc_map[field] & pc_freemask[field];
5925 while (inuse != 0) {
5927 bitmask = 1UL << bit;
5928 idx = field * 64 + bit;
5929 pv = &pc->pc_pventry[idx];
5932 pte = pmap_pdpe(pmap, pv->pv_va);
5934 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5936 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5939 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5941 pte = &pte[pmap_pte_index(pv->pv_va)];
5945 * Keep track whether 'tpte' is a
5946 * superpage explicitly instead of
5947 * relying on PG_PS being set.
5949 * This is because PG_PS is numerically
5950 * identical to PG_PTE_PAT and thus a
5951 * regular page could be mistaken for
5957 if ((tpte & PG_V) == 0) {
5958 panic("bad pte va %lx pte %lx",
5963 * We cannot remove wired pages from a process' mapping at this time
5971 pa = tpte & PG_PS_FRAME;
5973 pa = tpte & PG_FRAME;
5975 m = PHYS_TO_VM_PAGE(pa);
5976 KASSERT(m->phys_addr == pa,
5977 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5978 m, (uintmax_t)m->phys_addr,
5981 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5982 m < &vm_page_array[vm_page_array_size],
5983 ("pmap_remove_pages: bad tpte %#jx",
5989 * Update the vm_page_t clean/reference bits.
5991 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5993 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5999 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
6002 pc->pc_map[field] |= bitmask;
6004 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
6005 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
6006 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6008 if (TAILQ_EMPTY(&pvh->pv_list)) {
6009 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6010 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
6011 TAILQ_EMPTY(&mt->md.pv_list))
6012 vm_page_aflag_clear(mt, PGA_WRITEABLE);
6014 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
6016 pmap_resident_count_dec(pmap, 1);
6017 KASSERT(mpte->wire_count == NPTEPG,
6018 ("pmap_remove_pages: pte page wire count error"));
6019 mpte->wire_count = 0;
6020 pmap_add_delayed_free_list(mpte, &free, FALSE);
6023 pmap_resident_count_dec(pmap, 1);
6024 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6026 if ((m->aflags & PGA_WRITEABLE) != 0 &&
6027 TAILQ_EMPTY(&m->md.pv_list) &&
6028 (m->flags & PG_FICTITIOUS) == 0) {
6029 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6030 if (TAILQ_EMPTY(&pvh->pv_list))
6031 vm_page_aflag_clear(m, PGA_WRITEABLE);
6034 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
6038 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
6039 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
6040 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
6042 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
6048 pmap_invalidate_all(pmap);
6050 pmap_free_zero_pages(&free);
6054 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
6056 struct rwlock *lock;
6058 struct md_page *pvh;
6059 pt_entry_t *pte, mask;
6060 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6062 int md_gen, pvh_gen;
6066 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6069 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6071 if (!PMAP_TRYLOCK(pmap)) {
6072 md_gen = m->md.pv_gen;
6076 if (md_gen != m->md.pv_gen) {
6081 pte = pmap_pte(pmap, pv->pv_va);
6084 PG_M = pmap_modified_bit(pmap);
6085 PG_RW = pmap_rw_bit(pmap);
6086 mask |= PG_RW | PG_M;
6089 PG_A = pmap_accessed_bit(pmap);
6090 PG_V = pmap_valid_bit(pmap);
6091 mask |= PG_V | PG_A;
6093 rv = (*pte & mask) == mask;
6098 if ((m->flags & PG_FICTITIOUS) == 0) {
6099 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6100 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
6102 if (!PMAP_TRYLOCK(pmap)) {
6103 md_gen = m->md.pv_gen;
6104 pvh_gen = pvh->pv_gen;
6108 if (md_gen != m->md.pv_gen ||
6109 pvh_gen != pvh->pv_gen) {
6114 pte = pmap_pde(pmap, pv->pv_va);
6117 PG_M = pmap_modified_bit(pmap);
6118 PG_RW = pmap_rw_bit(pmap);
6119 mask |= PG_RW | PG_M;
6122 PG_A = pmap_accessed_bit(pmap);
6123 PG_V = pmap_valid_bit(pmap);
6124 mask |= PG_V | PG_A;
6126 rv = (*pte & mask) == mask;
6140 * Return whether or not the specified physical page was modified
6141 * in any physical maps.
6144 pmap_is_modified(vm_page_t m)
6147 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6148 ("pmap_is_modified: page %p is not managed", m));
6151 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6152 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
6153 * is clear, no PTEs can have PG_M set.
6155 VM_OBJECT_ASSERT_WLOCKED(m->object);
6156 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6158 return (pmap_page_test_mappings(m, FALSE, TRUE));
6162 * pmap_is_prefaultable:
6164 * Return whether or not the specified virtual address is eligible
6168 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
6171 pt_entry_t *pte, PG_V;
6174 PG_V = pmap_valid_bit(pmap);
6177 pde = pmap_pde(pmap, addr);
6178 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
6179 pte = pmap_pde_to_pte(pde, addr);
6180 rv = (*pte & PG_V) == 0;
6187 * pmap_is_referenced:
6189 * Return whether or not the specified physical page was referenced
6190 * in any physical maps.
6193 pmap_is_referenced(vm_page_t m)
6196 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6197 ("pmap_is_referenced: page %p is not managed", m));
6198 return (pmap_page_test_mappings(m, TRUE, FALSE));
6202 * Clear the write and modified bits in each of the given page's mappings.
6205 pmap_remove_write(vm_page_t m)
6207 struct md_page *pvh;
6209 struct rwlock *lock;
6210 pv_entry_t next_pv, pv;
6212 pt_entry_t oldpte, *pte, PG_M, PG_RW;
6214 int pvh_gen, md_gen;
6216 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6217 ("pmap_remove_write: page %p is not managed", m));
6220 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6221 * set by another thread while the object is locked. Thus,
6222 * if PGA_WRITEABLE is clear, no page table entries need updating.
6224 VM_OBJECT_ASSERT_WLOCKED(m->object);
6225 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6227 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6228 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6229 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6232 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6234 if (!PMAP_TRYLOCK(pmap)) {
6235 pvh_gen = pvh->pv_gen;
6239 if (pvh_gen != pvh->pv_gen) {
6245 PG_RW = pmap_rw_bit(pmap);
6247 pde = pmap_pde(pmap, va);
6248 if ((*pde & PG_RW) != 0)
6249 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6250 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6251 ("inconsistent pv lock %p %p for page %p",
6252 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6255 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6257 if (!PMAP_TRYLOCK(pmap)) {
6258 pvh_gen = pvh->pv_gen;
6259 md_gen = m->md.pv_gen;
6263 if (pvh_gen != pvh->pv_gen ||
6264 md_gen != m->md.pv_gen) {
6270 PG_M = pmap_modified_bit(pmap);
6271 PG_RW = pmap_rw_bit(pmap);
6272 pde = pmap_pde(pmap, pv->pv_va);
6273 KASSERT((*pde & PG_PS) == 0,
6274 ("pmap_remove_write: found a 2mpage in page %p's pv list",
6276 pte = pmap_pde_to_pte(pde, pv->pv_va);
6279 if (oldpte & PG_RW) {
6280 if (!atomic_cmpset_long(pte, oldpte, oldpte &
6283 if ((oldpte & PG_M) != 0)
6285 pmap_invalidate_page(pmap, pv->pv_va);
6290 vm_page_aflag_clear(m, PGA_WRITEABLE);
6291 pmap_delayed_invl_wait(m);
6294 static __inline boolean_t
6295 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
6298 if (!pmap_emulate_ad_bits(pmap))
6301 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
6304 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
6305 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
6306 * if the EPT_PG_WRITE bit is set.
6308 if ((pte & EPT_PG_WRITE) != 0)
6312 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
6314 if ((pte & EPT_PG_EXECUTE) == 0 ||
6315 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
6322 * pmap_ts_referenced:
6324 * Return a count of reference bits for a page, clearing those bits.
6325 * It is not necessary for every reference bit to be cleared, but it
6326 * is necessary that 0 only be returned when there are truly no
6327 * reference bits set.
6329 * As an optimization, update the page's dirty field if a modified bit is
6330 * found while counting reference bits. This opportunistic update can be
6331 * performed at low cost and can eliminate the need for some future calls
6332 * to pmap_is_modified(). However, since this function stops after
6333 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
6334 * dirty pages. Those dirty pages will only be detected by a future call
6335 * to pmap_is_modified().
6337 * A DI block is not needed within this function, because
6338 * invalidations are performed before the PV list lock is
6342 pmap_ts_referenced(vm_page_t m)
6344 struct md_page *pvh;
6347 struct rwlock *lock;
6348 pd_entry_t oldpde, *pde;
6349 pt_entry_t *pte, PG_A, PG_M, PG_RW;
6352 int cleared, md_gen, not_cleared, pvh_gen;
6353 struct spglist free;
6356 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6357 ("pmap_ts_referenced: page %p is not managed", m));
6360 pa = VM_PAGE_TO_PHYS(m);
6361 lock = PHYS_TO_PV_LIST_LOCK(pa);
6362 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
6366 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6367 goto small_mappings;
6373 if (!PMAP_TRYLOCK(pmap)) {
6374 pvh_gen = pvh->pv_gen;
6378 if (pvh_gen != pvh->pv_gen) {
6383 PG_A = pmap_accessed_bit(pmap);
6384 PG_M = pmap_modified_bit(pmap);
6385 PG_RW = pmap_rw_bit(pmap);
6387 pde = pmap_pde(pmap, pv->pv_va);
6389 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6391 * Although "oldpde" is mapping a 2MB page, because
6392 * this function is called at a 4KB page granularity,
6393 * we only update the 4KB page under test.
6397 if ((oldpde & PG_A) != 0) {
6399 * Since this reference bit is shared by 512 4KB
6400 * pages, it should not be cleared every time it is
6401 * tested. Apply a simple "hash" function on the
6402 * physical page number, the virtual superpage number,
6403 * and the pmap address to select one 4KB page out of
6404 * the 512 on which testing the reference bit will
6405 * result in clearing that reference bit. This
6406 * function is designed to avoid the selection of the
6407 * same 4KB page for every 2MB page mapping.
6409 * On demotion, a mapping that hasn't been referenced
6410 * is simply destroyed. To avoid the possibility of a
6411 * subsequent page fault on a demoted wired mapping,
6412 * always leave its reference bit set. Moreover,
6413 * since the superpage is wired, the current state of
6414 * its reference bit won't affect page replacement.
6416 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
6417 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
6418 (oldpde & PG_W) == 0) {
6419 if (safe_to_clear_referenced(pmap, oldpde)) {
6420 atomic_clear_long(pde, PG_A);
6421 pmap_invalidate_page(pmap, pv->pv_va);
6423 } else if (pmap_demote_pde_locked(pmap, pde,
6424 pv->pv_va, &lock)) {
6426 * Remove the mapping to a single page
6427 * so that a subsequent access may
6428 * repromote. Since the underlying
6429 * page table page is fully populated,
6430 * this removal never frees a page
6434 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6436 pte = pmap_pde_to_pte(pde, va);
6437 pmap_remove_pte(pmap, pte, va, *pde,
6439 pmap_invalidate_page(pmap, va);
6445 * The superpage mapping was removed
6446 * entirely and therefore 'pv' is no
6454 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6455 ("inconsistent pv lock %p %p for page %p",
6456 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6461 /* Rotate the PV list if it has more than one entry. */
6462 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6463 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6464 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6467 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6469 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6471 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6478 if (!PMAP_TRYLOCK(pmap)) {
6479 pvh_gen = pvh->pv_gen;
6480 md_gen = m->md.pv_gen;
6484 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6489 PG_A = pmap_accessed_bit(pmap);
6490 PG_M = pmap_modified_bit(pmap);
6491 PG_RW = pmap_rw_bit(pmap);
6492 pde = pmap_pde(pmap, pv->pv_va);
6493 KASSERT((*pde & PG_PS) == 0,
6494 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6496 pte = pmap_pde_to_pte(pde, pv->pv_va);
6497 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6499 if ((*pte & PG_A) != 0) {
6500 if (safe_to_clear_referenced(pmap, *pte)) {
6501 atomic_clear_long(pte, PG_A);
6502 pmap_invalidate_page(pmap, pv->pv_va);
6504 } else if ((*pte & PG_W) == 0) {
6506 * Wired pages cannot be paged out so
6507 * doing accessed bit emulation for
6508 * them is wasted effort. We do the
6509 * hard work for unwired pages only.
6511 pmap_remove_pte(pmap, pte, pv->pv_va,
6512 *pde, &free, &lock);
6513 pmap_invalidate_page(pmap, pv->pv_va);
6518 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6519 ("inconsistent pv lock %p %p for page %p",
6520 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6525 /* Rotate the PV list if it has more than one entry. */
6526 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6527 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6528 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6531 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6532 not_cleared < PMAP_TS_REFERENCED_MAX);
6535 pmap_free_zero_pages(&free);
6536 return (cleared + not_cleared);
6540 * Apply the given advice to the specified range of addresses within the
6541 * given pmap. Depending on the advice, clear the referenced and/or
6542 * modified flags in each mapping and set the mapped page's dirty field.
6545 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6547 struct rwlock *lock;
6548 pml4_entry_t *pml4e;
6550 pd_entry_t oldpde, *pde;
6551 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6552 vm_offset_t va, va_next;
6554 boolean_t anychanged;
6556 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6560 * A/D bit emulation requires an alternate code path when clearing
6561 * the modified and accessed bits below. Since this function is
6562 * advisory in nature we skip it entirely for pmaps that require
6563 * A/D bit emulation.
6565 if (pmap_emulate_ad_bits(pmap))
6568 PG_A = pmap_accessed_bit(pmap);
6569 PG_G = pmap_global_bit(pmap);
6570 PG_M = pmap_modified_bit(pmap);
6571 PG_V = pmap_valid_bit(pmap);
6572 PG_RW = pmap_rw_bit(pmap);
6574 pmap_delayed_invl_started();
6576 for (; sva < eva; sva = va_next) {
6577 pml4e = pmap_pml4e(pmap, sva);
6578 if ((*pml4e & PG_V) == 0) {
6579 va_next = (sva + NBPML4) & ~PML4MASK;
6584 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6585 if ((*pdpe & PG_V) == 0) {
6586 va_next = (sva + NBPDP) & ~PDPMASK;
6591 va_next = (sva + NBPDR) & ~PDRMASK;
6594 pde = pmap_pdpe_to_pde(pdpe, sva);
6596 if ((oldpde & PG_V) == 0)
6598 else if ((oldpde & PG_PS) != 0) {
6599 if ((oldpde & PG_MANAGED) == 0)
6602 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6607 * The large page mapping was destroyed.
6613 * Unless the page mappings are wired, remove the
6614 * mapping to a single page so that a subsequent
6615 * access may repromote. Since the underlying page
6616 * table page is fully populated, this removal never
6617 * frees a page table page.
6619 if ((oldpde & PG_W) == 0) {
6620 pte = pmap_pde_to_pte(pde, sva);
6621 KASSERT((*pte & PG_V) != 0,
6622 ("pmap_advise: invalid PTE"));
6623 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6633 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6635 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6637 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6638 if (advice == MADV_DONTNEED) {
6640 * Future calls to pmap_is_modified()
6641 * can be avoided by making the page
6644 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6647 atomic_clear_long(pte, PG_M | PG_A);
6648 } else if ((*pte & PG_A) != 0)
6649 atomic_clear_long(pte, PG_A);
6653 if ((*pte & PG_G) != 0) {
6660 if (va != va_next) {
6661 pmap_invalidate_range(pmap, va, sva);
6666 pmap_invalidate_range(pmap, va, sva);
6669 pmap_invalidate_all(pmap);
6671 pmap_delayed_invl_finished();
6675 * Clear the modify bits on the specified physical page.
6678 pmap_clear_modify(vm_page_t m)
6680 struct md_page *pvh;
6682 pv_entry_t next_pv, pv;
6683 pd_entry_t oldpde, *pde;
6684 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6685 struct rwlock *lock;
6687 int md_gen, pvh_gen;
6689 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6690 ("pmap_clear_modify: page %p is not managed", m));
6691 VM_OBJECT_ASSERT_WLOCKED(m->object);
6692 KASSERT(!vm_page_xbusied(m),
6693 ("pmap_clear_modify: page %p is exclusive busied", m));
6696 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6697 * If the object containing the page is locked and the page is not
6698 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6700 if ((m->aflags & PGA_WRITEABLE) == 0)
6702 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6703 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6704 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6707 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6709 if (!PMAP_TRYLOCK(pmap)) {
6710 pvh_gen = pvh->pv_gen;
6714 if (pvh_gen != pvh->pv_gen) {
6719 PG_M = pmap_modified_bit(pmap);
6720 PG_V = pmap_valid_bit(pmap);
6721 PG_RW = pmap_rw_bit(pmap);
6723 pde = pmap_pde(pmap, va);
6725 if ((oldpde & PG_RW) != 0) {
6726 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6727 if ((oldpde & PG_W) == 0) {
6729 * Write protect the mapping to a
6730 * single page so that a subsequent
6731 * write access may repromote.
6733 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6735 pte = pmap_pde_to_pte(pde, va);
6737 if ((oldpte & PG_V) != 0) {
6738 while (!atomic_cmpset_long(pte,
6740 oldpte & ~(PG_M | PG_RW)))
6743 pmap_invalidate_page(pmap, va);
6750 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6752 if (!PMAP_TRYLOCK(pmap)) {
6753 md_gen = m->md.pv_gen;
6754 pvh_gen = pvh->pv_gen;
6758 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6763 PG_M = pmap_modified_bit(pmap);
6764 PG_RW = pmap_rw_bit(pmap);
6765 pde = pmap_pde(pmap, pv->pv_va);
6766 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6767 " a 2mpage in page %p's pv list", m));
6768 pte = pmap_pde_to_pte(pde, pv->pv_va);
6769 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6770 atomic_clear_long(pte, PG_M);
6771 pmap_invalidate_page(pmap, pv->pv_va);
6779 * Miscellaneous support routines follow
6782 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6783 static __inline void
6784 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6789 * The cache mode bits are all in the low 32-bits of the
6790 * PTE, so we can just spin on updating the low 32-bits.
6793 opte = *(u_int *)pte;
6794 npte = opte & ~mask;
6796 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6799 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6800 static __inline void
6801 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6806 * The cache mode bits are all in the low 32-bits of the
6807 * PDE, so we can just spin on updating the low 32-bits.
6810 opde = *(u_int *)pde;
6811 npde = opde & ~mask;
6813 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6817 * Map a set of physical memory pages into the kernel virtual
6818 * address space. Return a pointer to where it is mapped. This
6819 * routine is intended to be used for mapping device memory,
6823 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6825 struct pmap_preinit_mapping *ppim;
6826 vm_offset_t va, offset;
6830 offset = pa & PAGE_MASK;
6831 size = round_page(offset + size);
6832 pa = trunc_page(pa);
6834 if (!pmap_initialized) {
6836 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6837 ppim = pmap_preinit_mapping + i;
6838 if (ppim->va == 0) {
6842 ppim->va = virtual_avail;
6843 virtual_avail += size;
6849 panic("%s: too many preinit mappings", __func__);
6852 * If we have a preinit mapping, re-use it.
6854 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6855 ppim = pmap_preinit_mapping + i;
6856 if (ppim->pa == pa && ppim->sz == size &&
6858 return ((void *)(ppim->va + offset));
6861 * If the specified range of physical addresses fits within
6862 * the direct map window, use the direct map.
6864 if (pa < dmaplimit && pa + size < dmaplimit) {
6865 va = PHYS_TO_DMAP(pa);
6866 if (!pmap_change_attr(va, size, mode))
6867 return ((void *)(va + offset));
6869 va = kva_alloc(size);
6871 panic("%s: Couldn't allocate KVA", __func__);
6873 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6874 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6875 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6876 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6877 return ((void *)(va + offset));
6881 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6884 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6888 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6891 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6895 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6897 struct pmap_preinit_mapping *ppim;
6901 /* If we gave a direct map region in pmap_mapdev, do nothing */
6902 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6904 offset = va & PAGE_MASK;
6905 size = round_page(offset + size);
6906 va = trunc_page(va);
6907 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6908 ppim = pmap_preinit_mapping + i;
6909 if (ppim->va == va && ppim->sz == size) {
6910 if (pmap_initialized)
6916 if (va + size == virtual_avail)
6921 if (pmap_initialized)
6926 * Tries to demote a 1GB page mapping.
6929 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6931 pdp_entry_t newpdpe, oldpdpe;
6932 pd_entry_t *firstpde, newpde, *pde;
6933 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6937 PG_A = pmap_accessed_bit(pmap);
6938 PG_M = pmap_modified_bit(pmap);
6939 PG_V = pmap_valid_bit(pmap);
6940 PG_RW = pmap_rw_bit(pmap);
6942 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6944 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6945 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6946 if ((pdpg = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6947 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6948 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6949 " in pmap %p", va, pmap);
6952 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
6953 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
6954 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6955 KASSERT((oldpdpe & PG_A) != 0,
6956 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6957 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6958 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
6962 * Initialize the page directory page.
6964 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
6970 * Demote the mapping.
6975 * Invalidate a stale recursive mapping of the page directory page.
6977 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
6979 pmap_pdpe_demotions++;
6980 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
6981 " in pmap %p", va, pmap);
6986 * Sets the memory attribute for the specified page.
6989 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6992 m->md.pat_mode = ma;
6995 * If "m" is a normal page, update its direct mapping. This update
6996 * can be relied upon to perform any cache operations that are
6997 * required for data coherence.
6999 if ((m->flags & PG_FICTITIOUS) == 0 &&
7000 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
7002 panic("memory attribute change on the direct map failed");
7006 * Changes the specified virtual address range's memory type to that given by
7007 * the parameter "mode". The specified virtual address range must be
7008 * completely contained within either the direct map or the kernel map. If
7009 * the virtual address range is contained within the kernel map, then the
7010 * memory type for each of the corresponding ranges of the direct map is also
7011 * changed. (The corresponding ranges of the direct map are those ranges that
7012 * map the same physical pages as the specified virtual address range.) These
7013 * changes to the direct map are necessary because Intel describes the
7014 * behavior of their processors as "undefined" if two or more mappings to the
7015 * same physical page have different memory types.
7017 * Returns zero if the change completed successfully, and either EINVAL or
7018 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
7019 * of the virtual address range was not mapped, and ENOMEM is returned if
7020 * there was insufficient memory available to complete the change. In the
7021 * latter case, the memory type may have been changed on some part of the
7022 * virtual address range or the direct map.
7025 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
7029 PMAP_LOCK(kernel_pmap);
7030 error = pmap_change_attr_locked(va, size, mode);
7031 PMAP_UNLOCK(kernel_pmap);
7036 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
7038 vm_offset_t base, offset, tmpva;
7039 vm_paddr_t pa_start, pa_end, pa_end1;
7043 int cache_bits_pte, cache_bits_pde, error;
7046 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
7047 base = trunc_page(va);
7048 offset = va & PAGE_MASK;
7049 size = round_page(offset + size);
7052 * Only supported on kernel virtual addresses, including the direct
7053 * map but excluding the recursive map.
7055 if (base < DMAP_MIN_ADDRESS)
7058 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
7059 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
7063 * Pages that aren't mapped aren't supported. Also break down 2MB pages
7064 * into 4KB pages if required.
7066 for (tmpva = base; tmpva < base + size; ) {
7067 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7068 if (pdpe == NULL || *pdpe == 0)
7070 if (*pdpe & PG_PS) {
7072 * If the current 1GB page already has the required
7073 * memory type, then we need not demote this page. Just
7074 * increment tmpva to the next 1GB page frame.
7076 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
7077 tmpva = trunc_1gpage(tmpva) + NBPDP;
7082 * If the current offset aligns with a 1GB page frame
7083 * and there is at least 1GB left within the range, then
7084 * we need not break down this page into 2MB pages.
7086 if ((tmpva & PDPMASK) == 0 &&
7087 tmpva + PDPMASK < base + size) {
7091 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
7094 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7099 * If the current 2MB page already has the required
7100 * memory type, then we need not demote this page. Just
7101 * increment tmpva to the next 2MB page frame.
7103 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
7104 tmpva = trunc_2mpage(tmpva) + NBPDR;
7109 * If the current offset aligns with a 2MB page frame
7110 * and there is at least 2MB left within the range, then
7111 * we need not break down this page into 4KB pages.
7113 if ((tmpva & PDRMASK) == 0 &&
7114 tmpva + PDRMASK < base + size) {
7118 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
7121 pte = pmap_pde_to_pte(pde, tmpva);
7129 * Ok, all the pages exist, so run through them updating their
7130 * cache mode if required.
7132 pa_start = pa_end = 0;
7133 for (tmpva = base; tmpva < base + size; ) {
7134 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7135 if (*pdpe & PG_PS) {
7136 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
7137 pmap_pde_attr(pdpe, cache_bits_pde,
7141 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7142 (*pdpe & PG_PS_FRAME) < dmaplimit) {
7143 if (pa_start == pa_end) {
7144 /* Start physical address run. */
7145 pa_start = *pdpe & PG_PS_FRAME;
7146 pa_end = pa_start + NBPDP;
7147 } else if (pa_end == (*pdpe & PG_PS_FRAME))
7150 /* Run ended, update direct map. */
7151 error = pmap_change_attr_locked(
7152 PHYS_TO_DMAP(pa_start),
7153 pa_end - pa_start, mode);
7156 /* Start physical address run. */
7157 pa_start = *pdpe & PG_PS_FRAME;
7158 pa_end = pa_start + NBPDP;
7161 tmpva = trunc_1gpage(tmpva) + NBPDP;
7164 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7166 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
7167 pmap_pde_attr(pde, cache_bits_pde,
7171 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7172 (*pde & PG_PS_FRAME) < dmaplimit) {
7173 if (pa_start == pa_end) {
7174 /* Start physical address run. */
7175 pa_start = *pde & PG_PS_FRAME;
7176 pa_end = pa_start + NBPDR;
7177 } else if (pa_end == (*pde & PG_PS_FRAME))
7180 /* Run ended, update direct map. */
7181 error = pmap_change_attr_locked(
7182 PHYS_TO_DMAP(pa_start),
7183 pa_end - pa_start, mode);
7186 /* Start physical address run. */
7187 pa_start = *pde & PG_PS_FRAME;
7188 pa_end = pa_start + NBPDR;
7191 tmpva = trunc_2mpage(tmpva) + NBPDR;
7193 pte = pmap_pde_to_pte(pde, tmpva);
7194 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
7195 pmap_pte_attr(pte, cache_bits_pte,
7199 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7200 (*pte & PG_FRAME) < dmaplimit) {
7201 if (pa_start == pa_end) {
7202 /* Start physical address run. */
7203 pa_start = *pte & PG_FRAME;
7204 pa_end = pa_start + PAGE_SIZE;
7205 } else if (pa_end == (*pte & PG_FRAME))
7206 pa_end += PAGE_SIZE;
7208 /* Run ended, update direct map. */
7209 error = pmap_change_attr_locked(
7210 PHYS_TO_DMAP(pa_start),
7211 pa_end - pa_start, mode);
7214 /* Start physical address run. */
7215 pa_start = *pte & PG_FRAME;
7216 pa_end = pa_start + PAGE_SIZE;
7222 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
7223 pa_end1 = MIN(pa_end, dmaplimit);
7224 if (pa_start != pa_end1)
7225 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
7226 pa_end1 - pa_start, mode);
7230 * Flush CPU caches if required to make sure any data isn't cached that
7231 * shouldn't be, etc.
7234 pmap_invalidate_range(kernel_pmap, base, tmpva);
7235 pmap_invalidate_cache_range(base, tmpva, FALSE);
7241 * Demotes any mapping within the direct map region that covers more than the
7242 * specified range of physical addresses. This range's size must be a power
7243 * of two and its starting address must be a multiple of its size. Since the
7244 * demotion does not change any attributes of the mapping, a TLB invalidation
7245 * is not mandatory. The caller may, however, request a TLB invalidation.
7248 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
7257 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
7258 KASSERT((base & (len - 1)) == 0,
7259 ("pmap_demote_DMAP: base is not a multiple of len"));
7260 if (len < NBPDP && base < dmaplimit) {
7261 va = PHYS_TO_DMAP(base);
7263 PMAP_LOCK(kernel_pmap);
7264 pdpe = pmap_pdpe(kernel_pmap, va);
7265 if ((*pdpe & X86_PG_V) == 0)
7266 panic("pmap_demote_DMAP: invalid PDPE");
7267 if ((*pdpe & PG_PS) != 0) {
7268 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
7269 panic("pmap_demote_DMAP: PDPE failed");
7273 pde = pmap_pdpe_to_pde(pdpe, va);
7274 if ((*pde & X86_PG_V) == 0)
7275 panic("pmap_demote_DMAP: invalid PDE");
7276 if ((*pde & PG_PS) != 0) {
7277 if (!pmap_demote_pde(kernel_pmap, pde, va))
7278 panic("pmap_demote_DMAP: PDE failed");
7282 if (changed && invalidate)
7283 pmap_invalidate_page(kernel_pmap, va);
7284 PMAP_UNLOCK(kernel_pmap);
7289 * perform the pmap work for mincore
7292 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
7295 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
7299 PG_A = pmap_accessed_bit(pmap);
7300 PG_M = pmap_modified_bit(pmap);
7301 PG_V = pmap_valid_bit(pmap);
7302 PG_RW = pmap_rw_bit(pmap);
7306 pdep = pmap_pde(pmap, addr);
7307 if (pdep != NULL && (*pdep & PG_V)) {
7308 if (*pdep & PG_PS) {
7310 /* Compute the physical address of the 4KB page. */
7311 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
7313 val = MINCORE_SUPER;
7315 pte = *pmap_pde_to_pte(pdep, addr);
7316 pa = pte & PG_FRAME;
7324 if ((pte & PG_V) != 0) {
7325 val |= MINCORE_INCORE;
7326 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7327 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
7328 if ((pte & PG_A) != 0)
7329 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
7331 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
7332 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
7333 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
7334 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
7335 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
7338 PA_UNLOCK_COND(*locked_pa);
7344 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
7346 uint32_t gen, new_gen, pcid_next;
7348 CRITICAL_ASSERT(curthread);
7349 gen = PCPU_GET(pcid_gen);
7350 if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN)
7351 return (pti ? 0 : CR3_PCID_SAVE);
7352 if (pmap->pm_pcids[cpuid].pm_gen == gen)
7353 return (CR3_PCID_SAVE);
7354 pcid_next = PCPU_GET(pcid_next);
7355 KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
7356 (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
7357 ("cpu %d pcid_next %#x", cpuid, pcid_next));
7358 if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
7359 (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
7363 PCPU_SET(pcid_gen, new_gen);
7364 pcid_next = PMAP_PCID_KERN + 1;
7368 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
7369 pmap->pm_pcids[cpuid].pm_gen = new_gen;
7370 PCPU_SET(pcid_next, pcid_next + 1);
7375 pmap_activate_sw(struct thread *td)
7377 pmap_t oldpmap, pmap;
7378 struct invpcid_descr d;
7379 uint64_t cached, cr3, kcr3, kern_pti_cached, rsp0, ucr3;
7382 struct amd64tss *tssp;
7384 oldpmap = PCPU_GET(curpmap);
7385 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7386 if (oldpmap == pmap)
7388 cpuid = PCPU_GET(cpuid);
7390 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7392 CPU_SET(cpuid, &pmap->pm_active);
7395 if (pmap_pcid_enabled) {
7396 cached = pmap_pcid_alloc(pmap, cpuid);
7397 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
7398 pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
7399 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
7400 pmap->pm_pcids[cpuid].pm_pcid));
7401 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
7402 pmap == kernel_pmap,
7403 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
7404 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
7407 * If the INVPCID instruction is not available,
7408 * invltlb_pcid_handler() is used for handle
7409 * invalidate_all IPI, which checks for curpmap ==
7410 * smp_tlb_pmap. Below operations sequence has a
7411 * window where %CR3 is loaded with the new pmap's
7412 * PML4 address, but curpmap value is not yet updated.
7413 * This causes invltlb IPI handler, called between the
7414 * updates, to execute as NOP, which leaves stale TLB
7417 * Note that the most typical use of
7418 * pmap_activate_sw(), from the context switch, is
7419 * immune to this race, because interrupts are
7420 * disabled (while the thread lock is owned), and IPI
7421 * happends after curpmap is updated. Protect other
7422 * callers in a similar way, by disabling interrupts
7423 * around the %cr3 register reload and curpmap
7427 rflags = intr_disable();
7429 kern_pti_cached = pti ? 0 : cached;
7430 if (!kern_pti_cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
7431 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
7434 PCPU_SET(curpmap, pmap);
7436 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid;
7437 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[cpuid].pm_pcid |
7440 if (!cached && pmap->pm_ucr3 != PMAP_NO_CR3) {
7442 * Manually invalidate translations cached
7443 * from the user page table. They are not
7444 * flushed by reload of cr3 with the kernel
7445 * page table pointer above.
7447 if (invpcid_works) {
7448 d.pcid = PMAP_PCID_USER_PT |
7449 pmap->pm_pcids[cpuid].pm_pcid;
7452 invpcid(&d, INVPCID_CTX);
7454 pmap_pti_pcid_invalidate(ucr3, kcr3);
7458 PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
7459 PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
7462 intr_restore(rflags);
7464 PCPU_INC(pm_save_cnt);
7465 } else if (cr3 != pmap->pm_cr3) {
7466 load_cr3(pmap->pm_cr3);
7467 PCPU_SET(curpmap, pmap);
7469 PCPU_SET(kcr3, pmap->pm_cr3);
7470 PCPU_SET(ucr3, pmap->pm_ucr3);
7473 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
7474 rsp0 = ((vm_offset_t)PCPU_PTR(pti_stack) +
7475 PC_PTI_STACK_SZ * sizeof(uint64_t)) & ~0xful;
7476 tssp = PCPU_GET(tssp);
7477 tssp->tss_rsp0 = rsp0;
7480 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
7482 CPU_CLR(cpuid, &oldpmap->pm_active);
7487 pmap_activate(struct thread *td)
7491 pmap_activate_sw(td);
7496 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
7501 * Increase the starting virtual address of the given mapping if a
7502 * different alignment might result in more superpage mappings.
7505 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7506 vm_offset_t *addr, vm_size_t size)
7508 vm_offset_t superpage_offset;
7512 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7513 offset += ptoa(object->pg_color);
7514 superpage_offset = offset & PDRMASK;
7515 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
7516 (*addr & PDRMASK) == superpage_offset)
7518 if ((*addr & PDRMASK) < superpage_offset)
7519 *addr = (*addr & ~PDRMASK) + superpage_offset;
7521 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
7525 static unsigned long num_dirty_emulations;
7526 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
7527 &num_dirty_emulations, 0, NULL);
7529 static unsigned long num_accessed_emulations;
7530 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
7531 &num_accessed_emulations, 0, NULL);
7533 static unsigned long num_superpage_accessed_emulations;
7534 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7535 &num_superpage_accessed_emulations, 0, NULL);
7537 static unsigned long ad_emulation_superpage_promotions;
7538 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7539 &ad_emulation_superpage_promotions, 0, NULL);
7540 #endif /* INVARIANTS */
7543 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7546 struct rwlock *lock;
7547 #if VM_NRESERVLEVEL > 0
7551 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7553 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7554 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7556 if (!pmap_emulate_ad_bits(pmap))
7559 PG_A = pmap_accessed_bit(pmap);
7560 PG_M = pmap_modified_bit(pmap);
7561 PG_V = pmap_valid_bit(pmap);
7562 PG_RW = pmap_rw_bit(pmap);
7568 pde = pmap_pde(pmap, va);
7569 if (pde == NULL || (*pde & PG_V) == 0)
7572 if ((*pde & PG_PS) != 0) {
7573 if (ftype == VM_PROT_READ) {
7575 atomic_add_long(&num_superpage_accessed_emulations, 1);
7583 pte = pmap_pde_to_pte(pde, va);
7584 if ((*pte & PG_V) == 0)
7587 if (ftype == VM_PROT_WRITE) {
7588 if ((*pte & PG_RW) == 0)
7591 * Set the modified and accessed bits simultaneously.
7593 * Intel EPT PTEs that do software emulation of A/D bits map
7594 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7595 * An EPT misconfiguration is triggered if the PTE is writable
7596 * but not readable (WR=10). This is avoided by setting PG_A
7597 * and PG_M simultaneously.
7599 *pte |= PG_M | PG_A;
7604 #if VM_NRESERVLEVEL > 0
7605 /* try to promote the mapping */
7606 if (va < VM_MAXUSER_ADDRESS)
7607 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7611 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7613 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7614 pmap_ps_enabled(pmap) &&
7615 (m->flags & PG_FICTITIOUS) == 0 &&
7616 vm_reserv_level_iffullpop(m) == 0) {
7617 pmap_promote_pde(pmap, pde, va, &lock);
7619 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7625 if (ftype == VM_PROT_WRITE)
7626 atomic_add_long(&num_dirty_emulations, 1);
7628 atomic_add_long(&num_accessed_emulations, 1);
7630 rv = 0; /* success */
7639 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7644 pt_entry_t *pte, PG_V;
7648 PG_V = pmap_valid_bit(pmap);
7651 pml4 = pmap_pml4e(pmap, va);
7653 if ((*pml4 & PG_V) == 0)
7656 pdp = pmap_pml4e_to_pdpe(pml4, va);
7658 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7661 pde = pmap_pdpe_to_pde(pdp, va);
7663 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7666 pte = pmap_pde_to_pte(pde, va);
7675 * Get the kernel virtual address of a set of physical pages. If there are
7676 * physical addresses not covered by the DMAP perform a transient mapping
7677 * that will be removed when calling pmap_unmap_io_transient.
7679 * \param page The pages the caller wishes to obtain the virtual
7680 * address on the kernel memory map.
7681 * \param vaddr On return contains the kernel virtual memory address
7682 * of the pages passed in the page parameter.
7683 * \param count Number of pages passed in.
7684 * \param can_fault TRUE if the thread using the mapped pages can take
7685 * page faults, FALSE otherwise.
7687 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7688 * finished or FALSE otherwise.
7692 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7693 boolean_t can_fault)
7696 boolean_t needs_mapping;
7698 int cache_bits, error, i;
7701 * Allocate any KVA space that we need, this is done in a separate
7702 * loop to prevent calling vmem_alloc while pinned.
7704 needs_mapping = FALSE;
7705 for (i = 0; i < count; i++) {
7706 paddr = VM_PAGE_TO_PHYS(page[i]);
7707 if (__predict_false(paddr >= dmaplimit)) {
7708 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7709 M_BESTFIT | M_WAITOK, &vaddr[i]);
7710 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7711 needs_mapping = TRUE;
7713 vaddr[i] = PHYS_TO_DMAP(paddr);
7717 /* Exit early if everything is covered by the DMAP */
7722 * NB: The sequence of updating a page table followed by accesses
7723 * to the corresponding pages used in the !DMAP case is subject to
7724 * the situation described in the "AMD64 Architecture Programmer's
7725 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7726 * Coherency Considerations". Therefore, issuing the INVLPG right
7727 * after modifying the PTE bits is crucial.
7731 for (i = 0; i < count; i++) {
7732 paddr = VM_PAGE_TO_PHYS(page[i]);
7733 if (paddr >= dmaplimit) {
7736 * Slow path, since we can get page faults
7737 * while mappings are active don't pin the
7738 * thread to the CPU and instead add a global
7739 * mapping visible to all CPUs.
7741 pmap_qenter(vaddr[i], &page[i], 1);
7743 pte = vtopte(vaddr[i]);
7744 cache_bits = pmap_cache_bits(kernel_pmap,
7745 page[i]->md.pat_mode, 0);
7746 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7753 return (needs_mapping);
7757 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7758 boolean_t can_fault)
7765 for (i = 0; i < count; i++) {
7766 paddr = VM_PAGE_TO_PHYS(page[i]);
7767 if (paddr >= dmaplimit) {
7769 pmap_qremove(vaddr[i], 1);
7770 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7776 pmap_quick_enter_page(vm_page_t m)
7780 paddr = VM_PAGE_TO_PHYS(m);
7781 if (paddr < dmaplimit)
7782 return (PHYS_TO_DMAP(paddr));
7783 mtx_lock_spin(&qframe_mtx);
7784 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7785 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7786 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7791 pmap_quick_remove_page(vm_offset_t addr)
7796 pte_store(vtopte(qframe), 0);
7798 mtx_unlock_spin(&qframe_mtx);
7802 pmap_pti_alloc_page(void)
7806 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7807 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_NOBUSY |
7808 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
7813 pmap_pti_free_page(vm_page_t m)
7816 KASSERT(m->wire_count > 0, ("page %p not wired", m));
7818 if (m->wire_count != 0)
7820 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
7821 vm_page_free_zero(m);
7835 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
7836 VM_OBJECT_WLOCK(pti_obj);
7837 pml4_pg = pmap_pti_alloc_page();
7838 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
7839 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
7840 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
7841 pdpe = pmap_pti_pdpe(va);
7842 pmap_pti_wire_pte(pdpe);
7844 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
7845 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
7846 pmap_pti_add_kva_locked((vm_offset_t)gdt, (vm_offset_t)gdt +
7847 sizeof(struct user_segment_descriptor) * NGDT * MAXCPU, false);
7848 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
7849 sizeof(struct gate_descriptor) * NIDT, false);
7850 pmap_pti_add_kva_locked((vm_offset_t)common_tss,
7851 (vm_offset_t)common_tss + sizeof(struct amd64tss) * MAXCPU, false);
7853 /* Doublefault stack IST 1 */
7854 va = common_tss[i].tss_ist1;
7855 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7856 /* NMI stack IST 2 */
7857 va = common_tss[i].tss_ist2 + sizeof(struct nmi_pcpu);
7858 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7859 /* MC# stack IST 3 */
7860 va = common_tss[i].tss_ist3 + sizeof(struct nmi_pcpu);
7861 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7862 /* DB# stack IST 4 */
7863 va = common_tss[i].tss_ist4 + sizeof(struct nmi_pcpu);
7864 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7866 pmap_pti_add_kva_locked((vm_offset_t)kernphys + KERNBASE,
7867 (vm_offset_t)etext, true);
7868 pti_finalized = true;
7869 VM_OBJECT_WUNLOCK(pti_obj);
7871 SYSINIT(pmap_pti, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_pti_init, NULL);
7873 static pdp_entry_t *
7874 pmap_pti_pdpe(vm_offset_t va)
7876 pml4_entry_t *pml4e;
7879 vm_pindex_t pml4_idx;
7882 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7884 pml4_idx = pmap_pml4e_index(va);
7885 pml4e = &pti_pml4[pml4_idx];
7889 panic("pml4 alloc after finalization\n");
7890 m = pmap_pti_alloc_page();
7892 pmap_pti_free_page(m);
7893 mphys = *pml4e & ~PAGE_MASK;
7895 mphys = VM_PAGE_TO_PHYS(m);
7896 *pml4e = mphys | X86_PG_RW | X86_PG_V;
7899 mphys = *pml4e & ~PAGE_MASK;
7901 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
7906 pmap_pti_wire_pte(void *pte)
7910 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7911 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7916 pmap_pti_unwire_pde(void *pde, bool only_ref)
7920 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7921 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
7922 MPASS(m->wire_count > 0);
7923 MPASS(only_ref || m->wire_count > 1);
7924 pmap_pti_free_page(m);
7928 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
7933 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7934 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7935 MPASS(m->wire_count > 0);
7936 if (pmap_pti_free_page(m)) {
7937 pde = pmap_pti_pde(va);
7938 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
7940 pmap_pti_unwire_pde(pde, false);
7945 pmap_pti_pde(vm_offset_t va)
7953 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7955 pdpe = pmap_pti_pdpe(va);
7957 m = pmap_pti_alloc_page();
7959 pmap_pti_free_page(m);
7960 MPASS((*pdpe & X86_PG_PS) == 0);
7961 mphys = *pdpe & ~PAGE_MASK;
7963 mphys = VM_PAGE_TO_PHYS(m);
7964 *pdpe = mphys | X86_PG_RW | X86_PG_V;
7967 MPASS((*pdpe & X86_PG_PS) == 0);
7968 mphys = *pdpe & ~PAGE_MASK;
7971 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
7972 pd_idx = pmap_pde_index(va);
7978 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
7985 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7987 pde = pmap_pti_pde(va);
7988 if (unwire_pde != NULL) {
7990 pmap_pti_wire_pte(pde);
7993 m = pmap_pti_alloc_page();
7995 pmap_pti_free_page(m);
7996 MPASS((*pde & X86_PG_PS) == 0);
7997 mphys = *pde & ~(PAGE_MASK | pg_nx);
7999 mphys = VM_PAGE_TO_PHYS(m);
8000 *pde = mphys | X86_PG_RW | X86_PG_V;
8001 if (unwire_pde != NULL)
8002 *unwire_pde = false;
8005 MPASS((*pde & X86_PG_PS) == 0);
8006 mphys = *pde & ~(PAGE_MASK | pg_nx);
8009 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
8010 pte += pmap_pte_index(va);
8016 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
8020 pt_entry_t *pte, ptev;
8023 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8025 sva = trunc_page(sva);
8026 MPASS(sva > VM_MAXUSER_ADDRESS);
8027 eva = round_page(eva);
8029 for (; sva < eva; sva += PAGE_SIZE) {
8030 pte = pmap_pti_pte(sva, &unwire_pde);
8031 pa = pmap_kextract(sva);
8032 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A | X86_PG_G |
8033 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
8034 VM_MEMATTR_DEFAULT, FALSE);
8036 pte_store(pte, ptev);
8037 pmap_pti_wire_pte(pte);
8039 KASSERT(!pti_finalized,
8040 ("pti overlap after fin %#lx %#lx %#lx",
8042 KASSERT(*pte == ptev,
8043 ("pti non-identical pte after fin %#lx %#lx %#lx",
8047 pde = pmap_pti_pde(sva);
8048 pmap_pti_unwire_pde(pde, true);
8054 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
8059 VM_OBJECT_WLOCK(pti_obj);
8060 pmap_pti_add_kva_locked(sva, eva, exec);
8061 VM_OBJECT_WUNLOCK(pti_obj);
8065 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
8072 sva = rounddown2(sva, PAGE_SIZE);
8073 MPASS(sva > VM_MAXUSER_ADDRESS);
8074 eva = roundup2(eva, PAGE_SIZE);
8076 VM_OBJECT_WLOCK(pti_obj);
8077 for (va = sva; va < eva; va += PAGE_SIZE) {
8078 pte = pmap_pti_pte(va, NULL);
8079 KASSERT((*pte & X86_PG_V) != 0,
8080 ("invalid pte va %#lx pte %#lx pt %#lx", va,
8081 (u_long)pte, *pte));
8083 pmap_pti_unwire_pte(pte, va);
8085 pmap_invalidate_range(kernel_pmap, sva, eva);
8086 VM_OBJECT_WUNLOCK(pti_obj);
8089 #include "opt_ddb.h"
8091 #include <ddb/ddb.h>
8093 DB_SHOW_COMMAND(pte, pmap_print_pte)
8099 pt_entry_t *pte, PG_V;
8103 va = (vm_offset_t)addr;
8104 pmap = PCPU_GET(curpmap); /* XXX */
8106 db_printf("show pte addr\n");
8109 PG_V = pmap_valid_bit(pmap);
8110 pml4 = pmap_pml4e(pmap, va);
8111 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
8112 if ((*pml4 & PG_V) == 0) {
8116 pdp = pmap_pml4e_to_pdpe(pml4, va);
8117 db_printf(" pdpe %#016lx", *pdp);
8118 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
8122 pde = pmap_pdpe_to_pde(pdp, va);
8123 db_printf(" pde %#016lx", *pde);
8124 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
8128 pte = pmap_pde_to_pte(pde, va);
8129 db_printf(" pte %#016lx\n", *pte);
8132 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
8137 a = (vm_paddr_t)addr;
8138 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
8140 db_printf("show phys2dmap addr\n");