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 |
958 * Now, set up the direct map region using 2MB and/or 1GB pages. If
959 * the end of physical memory is not aligned to a 1GB page boundary,
960 * then the residual physical memory is mapped with 2MB pages. Later,
961 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
962 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
963 * that are partially used.
965 pd_p = (pd_entry_t *)DMPDphys;
966 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
967 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
968 /* Preset PG_M and PG_A because demotion expects it. */
969 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
972 pdp_p = (pdp_entry_t *)DMPDPphys;
973 for (i = 0; i < ndm1g; i++) {
974 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
975 /* Preset PG_M and PG_A because demotion expects it. */
976 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
979 for (j = 0; i < ndmpdp; i++, j++) {
980 pdp_p[i] = DMPDphys + ptoa(j);
981 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_U;
984 /* And recursively map PML4 to itself in order to get PTmap */
985 p4_p = (pml4_entry_t *)KPML4phys;
986 p4_p[PML4PML4I] = KPML4phys;
987 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | PG_U | pg_nx;
989 /* Connect the Direct Map slot(s) up to the PML4. */
990 for (i = 0; i < ndmpdpphys; i++) {
991 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
992 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | PG_U;
995 /* Connect the KVA slots up to the PML4 */
996 for (i = 0; i < NKPML4E; i++) {
997 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
998 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V | PG_U;
1003 * Bootstrap the system enough to run with virtual memory.
1005 * On amd64 this is called after mapping has already been enabled
1006 * and just syncs the pmap module with what has already been done.
1007 * [We can't call it easily with mapping off since the kernel is not
1008 * mapped with PA == VA, hence we would have to relocate every address
1009 * from the linked base (virtual) address "KERNBASE" to the actual
1010 * (physical) address starting relative to 0]
1013 pmap_bootstrap(vm_paddr_t *firstaddr)
1023 * Create an initial set of page tables to run the kernel in.
1025 create_pagetables(firstaddr);
1028 * Add a physical memory segment (vm_phys_seg) corresponding to the
1029 * preallocated kernel page table pages so that vm_page structures
1030 * representing these pages will be created. The vm_page structures
1031 * are required for promotion of the corresponding kernel virtual
1032 * addresses to superpage mappings.
1034 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1036 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
1038 virtual_end = VM_MAX_KERNEL_ADDRESS;
1041 /* XXX do %cr0 as well */
1042 load_cr4(rcr4() | CR4_PGE);
1043 load_cr3(KPML4phys);
1044 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1045 load_cr4(rcr4() | CR4_SMEP);
1048 * Initialize the kernel pmap (which is statically allocated).
1050 PMAP_LOCK_INIT(kernel_pmap);
1051 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1052 kernel_pmap->pm_cr3 = KPML4phys;
1053 kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
1054 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1055 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1056 kernel_pmap->pm_flags = pmap_flags;
1059 * Initialize the TLB invalidations generation number lock.
1061 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1064 * Reserve some special page table entries/VA space for temporary
1067 #define SYSMAP(c, p, v, n) \
1068 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1074 * Crashdump maps. The first page is reused as CMAP1 for the
1077 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1078 CADDR1 = crashdumpmap;
1083 * Initialize the PAT MSR.
1084 * pmap_init_pat() clears and sets CR4_PGE, which, as a
1085 * side-effect, invalidates stale PG_G TLB entries that might
1086 * have been created in our pre-boot environment.
1090 /* Initialize TLB Context Id. */
1091 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1092 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1093 /* Check for INVPCID support */
1094 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1096 for (i = 0; i < MAXCPU; i++) {
1097 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1098 kernel_pmap->pm_pcids[i].pm_gen = 1;
1100 __pcpu[0].pc_pcid_next = PMAP_PCID_KERN + 1;
1101 __pcpu[0].pc_pcid_gen = 1;
1103 * pcpu area for APs is zeroed during AP startup.
1104 * pc_pcid_next and pc_pcid_gen are initialized by AP
1105 * during pcpu setup.
1107 load_cr4(rcr4() | CR4_PCIDE);
1109 pmap_pcid_enabled = 0;
1114 * Setup the PAT MSR.
1119 int pat_table[PAT_INDEX_SIZE];
1124 /* Bail if this CPU doesn't implement PAT. */
1125 if ((cpu_feature & CPUID_PAT) == 0)
1128 /* Set default PAT index table. */
1129 for (i = 0; i < PAT_INDEX_SIZE; i++)
1131 pat_table[PAT_WRITE_BACK] = 0;
1132 pat_table[PAT_WRITE_THROUGH] = 1;
1133 pat_table[PAT_UNCACHEABLE] = 3;
1134 pat_table[PAT_WRITE_COMBINING] = 3;
1135 pat_table[PAT_WRITE_PROTECTED] = 3;
1136 pat_table[PAT_UNCACHED] = 3;
1138 /* Initialize default PAT entries. */
1139 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1140 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1141 PAT_VALUE(2, PAT_UNCACHED) |
1142 PAT_VALUE(3, PAT_UNCACHEABLE) |
1143 PAT_VALUE(4, PAT_WRITE_BACK) |
1144 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1145 PAT_VALUE(6, PAT_UNCACHED) |
1146 PAT_VALUE(7, PAT_UNCACHEABLE);
1150 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1151 * Program 5 and 6 as WP and WC.
1152 * Leave 4 and 7 as WB and UC.
1154 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1155 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1156 PAT_VALUE(6, PAT_WRITE_COMBINING);
1157 pat_table[PAT_UNCACHED] = 2;
1158 pat_table[PAT_WRITE_PROTECTED] = 5;
1159 pat_table[PAT_WRITE_COMBINING] = 6;
1162 * Just replace PAT Index 2 with WC instead of UC-.
1164 pat_msr &= ~PAT_MASK(2);
1165 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1166 pat_table[PAT_WRITE_COMBINING] = 2;
1171 load_cr4(cr4 & ~CR4_PGE);
1173 /* Disable caches (CD = 1, NW = 0). */
1175 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1177 /* Flushes caches and TLBs. */
1181 /* Update PAT and index table. */
1182 wrmsr(MSR_PAT, pat_msr);
1183 for (i = 0; i < PAT_INDEX_SIZE; i++)
1184 pat_index[i] = pat_table[i];
1186 /* Flush caches and TLBs again. */
1190 /* Restore caches and PGE. */
1196 * Initialize a vm_page's machine-dependent fields.
1199 pmap_page_init(vm_page_t m)
1202 TAILQ_INIT(&m->md.pv_list);
1203 m->md.pat_mode = PAT_WRITE_BACK;
1207 * Initialize the pmap module.
1208 * Called by vm_init, to initialize any structures that the pmap
1209 * system needs to map virtual memory.
1214 struct pmap_preinit_mapping *ppim;
1217 int error, i, pv_npg, ret, skz63;
1219 /* Detect bare-metal Skylake Server and Skylake-X. */
1220 if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
1221 CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
1223 * Skylake-X errata SKZ63. Processor May Hang When
1224 * Executing Code In an HLE Transaction Region between
1225 * 40000000H and 403FFFFFH.
1227 * Mark the pages in the range as preallocated. It
1228 * seems to be impossible to distinguish between
1229 * Skylake Server and Skylake X.
1232 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
1235 printf("SKZ63: skipping 4M RAM starting "
1236 "at physical 1G\n");
1237 for (i = 0; i < atop(0x400000); i++) {
1238 ret = vm_page_blacklist_add(0x40000000 +
1240 if (!ret && bootverbose)
1241 printf("page at %#lx already used\n",
1242 0x40000000 + ptoa(i));
1248 * Initialize the vm page array entries for the kernel pmap's
1251 for (i = 0; i < nkpt; i++) {
1252 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1253 KASSERT(mpte >= vm_page_array &&
1254 mpte < &vm_page_array[vm_page_array_size],
1255 ("pmap_init: page table page is out of range"));
1256 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1257 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1258 mpte->wire_count = 1;
1260 atomic_add_int(&vm_cnt.v_wire_count, nkpt);
1263 * If the kernel is running on a virtual machine, then it must assume
1264 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1265 * be prepared for the hypervisor changing the vendor and family that
1266 * are reported by CPUID. Consequently, the workaround for AMD Family
1267 * 10h Erratum 383 is enabled if the processor's feature set does not
1268 * include at least one feature that is only supported by older Intel
1269 * or newer AMD processors.
1271 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1272 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1273 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1275 workaround_erratum383 = 1;
1278 * Are large page mappings enabled?
1280 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1281 if (pg_ps_enabled) {
1282 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1283 ("pmap_init: can't assign to pagesizes[1]"));
1284 pagesizes[1] = NBPDR;
1288 * Initialize the pv chunk list mutex.
1290 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1293 * Initialize the pool of pv list locks.
1295 for (i = 0; i < NPV_LIST_LOCKS; i++)
1296 rw_init(&pv_list_locks[i], "pmap pv list");
1299 * Calculate the size of the pv head table for superpages.
1301 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1304 * Allocate memory for the pv head table for superpages.
1306 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1308 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1310 for (i = 0; i < pv_npg; i++)
1311 TAILQ_INIT(&pv_table[i].pv_list);
1312 TAILQ_INIT(&pv_dummy.pv_list);
1314 pmap_initialized = 1;
1315 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1316 ppim = pmap_preinit_mapping + i;
1319 /* Make the direct map consistent */
1320 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1321 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1322 ppim->sz, ppim->mode);
1326 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1327 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1330 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1331 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1332 (vmem_addr_t *)&qframe);
1334 panic("qframe allocation failed");
1337 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1338 "2MB page mapping counters");
1340 static u_long pmap_pde_demotions;
1341 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1342 &pmap_pde_demotions, 0, "2MB page demotions");
1344 static u_long pmap_pde_mappings;
1345 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1346 &pmap_pde_mappings, 0, "2MB page mappings");
1348 static u_long pmap_pde_p_failures;
1349 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1350 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1352 static u_long pmap_pde_promotions;
1353 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1354 &pmap_pde_promotions, 0, "2MB page promotions");
1356 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1357 "1GB page mapping counters");
1359 static u_long pmap_pdpe_demotions;
1360 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1361 &pmap_pdpe_demotions, 0, "1GB page demotions");
1363 /***************************************************
1364 * Low level helper routines.....
1365 ***************************************************/
1368 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1370 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1372 switch (pmap->pm_type) {
1375 /* Verify that both PAT bits are not set at the same time */
1376 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1377 ("Invalid PAT bits in entry %#lx", entry));
1379 /* Swap the PAT bits if one of them is set */
1380 if ((entry & x86_pat_bits) != 0)
1381 entry ^= x86_pat_bits;
1385 * Nothing to do - the memory attributes are represented
1386 * the same way for regular pages and superpages.
1390 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1397 * Determine the appropriate bits to set in a PTE or PDE for a specified
1401 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1403 int cache_bits, pat_flag, pat_idx;
1405 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1406 panic("Unknown caching mode %d\n", mode);
1408 switch (pmap->pm_type) {
1411 /* The PAT bit is different for PTE's and PDE's. */
1412 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1414 /* Map the caching mode to a PAT index. */
1415 pat_idx = pat_index[mode];
1417 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1420 cache_bits |= pat_flag;
1422 cache_bits |= PG_NC_PCD;
1424 cache_bits |= PG_NC_PWT;
1428 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1432 panic("unsupported pmap type %d", pmap->pm_type);
1435 return (cache_bits);
1439 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1443 switch (pmap->pm_type) {
1446 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1449 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1452 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1459 pmap_ps_enabled(pmap_t pmap)
1462 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1466 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1469 switch (pmap->pm_type) {
1476 * This is a little bogus since the generation number is
1477 * supposed to be bumped up when a region of the address
1478 * space is invalidated in the page tables.
1480 * In this case the old PDE entry is valid but yet we want
1481 * to make sure that any mappings using the old entry are
1482 * invalidated in the TLB.
1484 * The reason this works as expected is because we rendezvous
1485 * "all" host cpus and force any vcpu context to exit as a
1488 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1491 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1493 pde_store(pde, newpde);
1497 * After changing the page size for the specified virtual address in the page
1498 * table, flush the corresponding entries from the processor's TLB. Only the
1499 * calling processor's TLB is affected.
1501 * The calling thread must be pinned to a processor.
1504 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1508 if (pmap_type_guest(pmap))
1511 KASSERT(pmap->pm_type == PT_X86,
1512 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1514 PG_G = pmap_global_bit(pmap);
1516 if ((newpde & PG_PS) == 0)
1517 /* Demotion: flush a specific 2MB page mapping. */
1519 else if ((newpde & PG_G) == 0)
1521 * Promotion: flush every 4KB page mapping from the TLB
1522 * because there are too many to flush individually.
1527 * Promotion: flush every 4KB page mapping from the TLB,
1528 * including any global (PG_G) mappings.
1536 * For SMP, these functions have to use the IPI mechanism for coherence.
1538 * N.B.: Before calling any of the following TLB invalidation functions,
1539 * the calling processor must ensure that all stores updating a non-
1540 * kernel page table are globally performed. Otherwise, another
1541 * processor could cache an old, pre-update entry without being
1542 * invalidated. This can happen one of two ways: (1) The pmap becomes
1543 * active on another processor after its pm_active field is checked by
1544 * one of the following functions but before a store updating the page
1545 * table is globally performed. (2) The pmap becomes active on another
1546 * processor before its pm_active field is checked but due to
1547 * speculative loads one of the following functions stills reads the
1548 * pmap as inactive on the other processor.
1550 * The kernel page table is exempt because its pm_active field is
1551 * immutable. The kernel page table is always active on every
1556 * Interrupt the cpus that are executing in the guest context.
1557 * This will force the vcpu to exit and the cached EPT mappings
1558 * will be invalidated by the host before the next vmresume.
1560 static __inline void
1561 pmap_invalidate_ept(pmap_t pmap)
1566 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1567 ("pmap_invalidate_ept: absurd pm_active"));
1570 * The TLB mappings associated with a vcpu context are not
1571 * flushed each time a different vcpu is chosen to execute.
1573 * This is in contrast with a process's vtop mappings that
1574 * are flushed from the TLB on each context switch.
1576 * Therefore we need to do more than just a TLB shootdown on
1577 * the active cpus in 'pmap->pm_active'. To do this we keep
1578 * track of the number of invalidations performed on this pmap.
1580 * Each vcpu keeps a cache of this counter and compares it
1581 * just before a vmresume. If the counter is out-of-date an
1582 * invept will be done to flush stale mappings from the TLB.
1584 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1587 * Force the vcpu to exit and trap back into the hypervisor.
1589 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1590 ipi_selected(pmap->pm_active, ipinum);
1595 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1598 struct invpcid_descr d;
1599 uint64_t kcr3, ucr3;
1603 if (pmap_type_guest(pmap)) {
1604 pmap_invalidate_ept(pmap);
1608 KASSERT(pmap->pm_type == PT_X86,
1609 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1612 if (pmap == kernel_pmap) {
1616 cpuid = PCPU_GET(cpuid);
1617 if (pmap == PCPU_GET(curpmap)) {
1619 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1621 * Disable context switching. pm_pcid
1622 * is recalculated on switch, which
1623 * might make us use wrong pcid below.
1626 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1628 if (invpcid_works) {
1629 d.pcid = pcid | PMAP_PCID_USER_PT;
1632 invpcid(&d, INVPCID_ADDR);
1634 kcr3 = pmap->pm_cr3 | pcid |
1636 ucr3 = pmap->pm_ucr3 | pcid |
1637 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1638 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1642 } else if (pmap_pcid_enabled)
1643 pmap->pm_pcids[cpuid].pm_gen = 0;
1644 if (pmap_pcid_enabled) {
1647 pmap->pm_pcids[i].pm_gen = 0;
1650 mask = &pmap->pm_active;
1652 smp_masked_invlpg(*mask, va, pmap);
1656 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1657 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1660 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1663 struct invpcid_descr d;
1665 uint64_t kcr3, ucr3;
1669 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1670 pmap_invalidate_all(pmap);
1674 if (pmap_type_guest(pmap)) {
1675 pmap_invalidate_ept(pmap);
1679 KASSERT(pmap->pm_type == PT_X86,
1680 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1683 cpuid = PCPU_GET(cpuid);
1684 if (pmap == kernel_pmap) {
1685 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1689 if (pmap == PCPU_GET(curpmap)) {
1690 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1692 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1694 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1695 if (invpcid_works) {
1696 d.pcid = pcid | PMAP_PCID_USER_PT;
1699 for (; d.addr < eva; d.addr +=
1701 invpcid(&d, INVPCID_ADDR);
1703 kcr3 = pmap->pm_cr3 | pcid |
1705 ucr3 = pmap->pm_ucr3 | pcid |
1706 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1707 pmap_pti_pcid_invlrng(ucr3, kcr3, sva,
1712 } else if (pmap_pcid_enabled) {
1713 pmap->pm_pcids[cpuid].pm_gen = 0;
1715 if (pmap_pcid_enabled) {
1718 pmap->pm_pcids[i].pm_gen = 0;
1721 mask = &pmap->pm_active;
1723 smp_masked_invlpg_range(*mask, sva, eva, pmap);
1728 pmap_invalidate_all(pmap_t pmap)
1731 struct invpcid_descr d;
1732 uint64_t kcr3, ucr3;
1736 if (pmap_type_guest(pmap)) {
1737 pmap_invalidate_ept(pmap);
1741 KASSERT(pmap->pm_type == PT_X86,
1742 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1745 if (pmap == kernel_pmap) {
1746 if (pmap_pcid_enabled && invpcid_works) {
1747 bzero(&d, sizeof(d));
1748 invpcid(&d, INVPCID_CTXGLOB);
1754 cpuid = PCPU_GET(cpuid);
1755 if (pmap == PCPU_GET(curpmap)) {
1756 if (pmap_pcid_enabled) {
1758 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1759 if (invpcid_works) {
1763 invpcid(&d, INVPCID_CTX);
1764 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1765 d.pcid |= PMAP_PCID_USER_PT;
1766 invpcid(&d, INVPCID_CTX);
1769 kcr3 = pmap->pm_cr3 | pcid;
1770 ucr3 = pmap->pm_ucr3;
1771 if (ucr3 != PMAP_NO_CR3) {
1772 ucr3 |= pcid | PMAP_PCID_USER_PT;
1773 pmap_pti_pcid_invalidate(ucr3,
1783 } else if (pmap_pcid_enabled) {
1784 pmap->pm_pcids[cpuid].pm_gen = 0;
1786 if (pmap_pcid_enabled) {
1789 pmap->pm_pcids[i].pm_gen = 0;
1792 mask = &pmap->pm_active;
1794 smp_masked_invltlb(*mask, pmap);
1799 pmap_invalidate_cache(void)
1809 cpuset_t invalidate; /* processors that invalidate their TLB */
1814 u_int store; /* processor that updates the PDE */
1818 pmap_update_pde_action(void *arg)
1820 struct pde_action *act = arg;
1822 if (act->store == PCPU_GET(cpuid))
1823 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1827 pmap_update_pde_teardown(void *arg)
1829 struct pde_action *act = arg;
1831 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1832 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1836 * Change the page size for the specified virtual address in a way that
1837 * prevents any possibility of the TLB ever having two entries that map the
1838 * same virtual address using different page sizes. This is the recommended
1839 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1840 * machine check exception for a TLB state that is improperly diagnosed as a
1844 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1846 struct pde_action act;
1847 cpuset_t active, other_cpus;
1851 cpuid = PCPU_GET(cpuid);
1852 other_cpus = all_cpus;
1853 CPU_CLR(cpuid, &other_cpus);
1854 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1857 active = pmap->pm_active;
1859 if (CPU_OVERLAP(&active, &other_cpus)) {
1861 act.invalidate = active;
1865 act.newpde = newpde;
1866 CPU_SET(cpuid, &active);
1867 smp_rendezvous_cpus(active,
1868 smp_no_rendezvous_barrier, pmap_update_pde_action,
1869 pmap_update_pde_teardown, &act);
1871 pmap_update_pde_store(pmap, pde, newpde);
1872 if (CPU_ISSET(cpuid, &active))
1873 pmap_update_pde_invalidate(pmap, va, newpde);
1879 * Normal, non-SMP, invalidation functions.
1882 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1884 struct invpcid_descr d;
1885 uint64_t kcr3, ucr3;
1888 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1892 KASSERT(pmap->pm_type == PT_X86,
1893 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1895 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1897 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
1898 pmap->pm_ucr3 != PMAP_NO_CR3) {
1900 pcid = pmap->pm_pcids[0].pm_pcid;
1901 if (invpcid_works) {
1902 d.pcid = pcid | PMAP_PCID_USER_PT;
1905 invpcid(&d, INVPCID_ADDR);
1907 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
1908 ucr3 = pmap->pm_ucr3 | pcid |
1909 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1910 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1914 } else if (pmap_pcid_enabled)
1915 pmap->pm_pcids[0].pm_gen = 0;
1919 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1921 struct invpcid_descr d;
1923 uint64_t kcr3, ucr3;
1925 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1929 KASSERT(pmap->pm_type == PT_X86,
1930 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1932 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1933 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1935 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
1936 pmap->pm_ucr3 != PMAP_NO_CR3) {
1938 if (invpcid_works) {
1939 d.pcid = pmap->pm_pcids[0].pm_pcid |
1943 for (; d.addr < eva; d.addr += PAGE_SIZE)
1944 invpcid(&d, INVPCID_ADDR);
1946 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].
1947 pm_pcid | CR3_PCID_SAVE;
1948 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[0].
1949 pm_pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1950 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
1954 } else if (pmap_pcid_enabled) {
1955 pmap->pm_pcids[0].pm_gen = 0;
1960 pmap_invalidate_all(pmap_t pmap)
1962 struct invpcid_descr d;
1963 uint64_t kcr3, ucr3;
1965 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1969 KASSERT(pmap->pm_type == PT_X86,
1970 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
1972 if (pmap == kernel_pmap) {
1973 if (pmap_pcid_enabled && invpcid_works) {
1974 bzero(&d, sizeof(d));
1975 invpcid(&d, INVPCID_CTXGLOB);
1979 } else if (pmap == PCPU_GET(curpmap)) {
1980 if (pmap_pcid_enabled) {
1982 if (invpcid_works) {
1983 d.pcid = pmap->pm_pcids[0].pm_pcid;
1986 invpcid(&d, INVPCID_CTX);
1987 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1988 d.pcid |= PMAP_PCID_USER_PT;
1989 invpcid(&d, INVPCID_CTX);
1992 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].pm_pcid;
1993 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1994 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[
1995 0].pm_pcid | PMAP_PCID_USER_PT;
1996 pmap_pti_pcid_invalidate(ucr3, kcr3);
2004 } else if (pmap_pcid_enabled) {
2005 pmap->pm_pcids[0].pm_gen = 0;
2010 pmap_invalidate_cache(void)
2017 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
2020 pmap_update_pde_store(pmap, pde, newpde);
2021 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
2022 pmap_update_pde_invalidate(pmap, va, newpde);
2024 pmap->pm_pcids[0].pm_gen = 0;
2029 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
2033 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
2034 * by a promotion that did not invalidate the 512 4KB page mappings
2035 * that might exist in the TLB. Consequently, at this point, the TLB
2036 * may hold both 4KB and 2MB page mappings for the address range [va,
2037 * va + NBPDR). Therefore, the entire range must be invalidated here.
2038 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
2039 * 4KB page mappings for the address range [va, va + NBPDR), and so a
2040 * single INVLPG suffices to invalidate the 2MB page mapping from the
2043 if ((pde & PG_PROMOTED) != 0)
2044 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
2046 pmap_invalidate_page(pmap, va);
2049 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
2052 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
2056 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
2058 KASSERT((sva & PAGE_MASK) == 0,
2059 ("pmap_invalidate_cache_range: sva not page-aligned"));
2060 KASSERT((eva & PAGE_MASK) == 0,
2061 ("pmap_invalidate_cache_range: eva not page-aligned"));
2064 if ((cpu_feature & CPUID_SS) != 0 && !force)
2065 ; /* If "Self Snoop" is supported and allowed, do nothing. */
2066 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
2067 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2069 * XXX: Some CPUs fault, hang, or trash the local APIC
2070 * registers if we use CLFLUSH on the local APIC
2071 * range. The local APIC is always uncached, so we
2072 * don't need to flush for that range anyway.
2074 if (pmap_kextract(sva) == lapic_paddr)
2078 * Otherwise, do per-cache line flush. Use the sfence
2079 * instruction to insure that previous stores are
2080 * included in the write-back. The processor
2081 * propagates flush to other processors in the cache
2085 for (; sva < eva; sva += cpu_clflush_line_size)
2088 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
2089 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2090 if (pmap_kextract(sva) == lapic_paddr)
2093 * Writes are ordered by CLFLUSH on Intel CPUs.
2095 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2097 for (; sva < eva; sva += cpu_clflush_line_size)
2099 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2104 * No targeted cache flush methods are supported by CPU,
2105 * or the supplied range is bigger than 2MB.
2106 * Globally invalidate cache.
2108 pmap_invalidate_cache();
2113 * Remove the specified set of pages from the data and instruction caches.
2115 * In contrast to pmap_invalidate_cache_range(), this function does not
2116 * rely on the CPU's self-snoop feature, because it is intended for use
2117 * when moving pages into a different cache domain.
2120 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
2122 vm_offset_t daddr, eva;
2126 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
2127 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
2128 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
2129 pmap_invalidate_cache();
2133 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2135 for (i = 0; i < count; i++) {
2136 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
2137 eva = daddr + PAGE_SIZE;
2138 for (; daddr < eva; daddr += cpu_clflush_line_size) {
2147 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2153 * Routine: pmap_extract
2155 * Extract the physical page address associated
2156 * with the given map/virtual_address pair.
2159 pmap_extract(pmap_t pmap, vm_offset_t va)
2163 pt_entry_t *pte, PG_V;
2167 PG_V = pmap_valid_bit(pmap);
2169 pdpe = pmap_pdpe(pmap, va);
2170 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2171 if ((*pdpe & PG_PS) != 0)
2172 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
2174 pde = pmap_pdpe_to_pde(pdpe, va);
2175 if ((*pde & PG_V) != 0) {
2176 if ((*pde & PG_PS) != 0) {
2177 pa = (*pde & PG_PS_FRAME) |
2180 pte = pmap_pde_to_pte(pde, va);
2181 pa = (*pte & PG_FRAME) |
2192 * Routine: pmap_extract_and_hold
2194 * Atomically extract and hold the physical page
2195 * with the given pmap and virtual address pair
2196 * if that mapping permits the given protection.
2199 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
2201 pd_entry_t pde, *pdep;
2202 pt_entry_t pte, PG_RW, PG_V;
2208 PG_RW = pmap_rw_bit(pmap);
2209 PG_V = pmap_valid_bit(pmap);
2212 pdep = pmap_pde(pmap, va);
2213 if (pdep != NULL && (pde = *pdep)) {
2215 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2216 if (vm_page_pa_tryrelock(pmap, (pde &
2217 PG_PS_FRAME) | (va & PDRMASK), &pa))
2219 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
2224 pte = *pmap_pde_to_pte(pdep, va);
2226 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2227 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2230 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
2241 pmap_kextract(vm_offset_t va)
2246 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2247 pa = DMAP_TO_PHYS(va);
2251 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2254 * Beware of a concurrent promotion that changes the
2255 * PDE at this point! For example, vtopte() must not
2256 * be used to access the PTE because it would use the
2257 * new PDE. It is, however, safe to use the old PDE
2258 * because the page table page is preserved by the
2261 pa = *pmap_pde_to_pte(&pde, va);
2262 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2268 /***************************************************
2269 * Low level mapping routines.....
2270 ***************************************************/
2273 * Add a wired page to the kva.
2274 * Note: not SMP coherent.
2277 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2282 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g);
2285 static __inline void
2286 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2292 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2293 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | cache_bits);
2297 * Remove a page from the kernel pagetables.
2298 * Note: not SMP coherent.
2301 pmap_kremove(vm_offset_t va)
2310 * Used to map a range of physical addresses into kernel
2311 * virtual address space.
2313 * The value passed in '*virt' is a suggested virtual address for
2314 * the mapping. Architectures which can support a direct-mapped
2315 * physical to virtual region can return the appropriate address
2316 * within that region, leaving '*virt' unchanged. Other
2317 * architectures should map the pages starting at '*virt' and
2318 * update '*virt' with the first usable address after the mapped
2322 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2324 return PHYS_TO_DMAP(start);
2329 * Add a list of wired pages to the kva
2330 * this routine is only used for temporary
2331 * kernel mappings that do not need to have
2332 * page modification or references recorded.
2333 * Note that old mappings are simply written
2334 * over. The page *must* be wired.
2335 * Note: SMP coherent. Uses a ranged shootdown IPI.
2338 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2340 pt_entry_t *endpte, oldpte, pa, *pte;
2346 endpte = pte + count;
2347 while (pte < endpte) {
2349 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2350 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2351 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2353 pte_store(pte, pa | pg_g | X86_PG_RW | X86_PG_V);
2357 if (__predict_false((oldpte & X86_PG_V) != 0))
2358 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2363 * This routine tears out page mappings from the
2364 * kernel -- it is meant only for temporary mappings.
2365 * Note: SMP coherent. Uses a ranged shootdown IPI.
2368 pmap_qremove(vm_offset_t sva, int count)
2373 while (count-- > 0) {
2374 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2378 pmap_invalidate_range(kernel_pmap, sva, va);
2381 /***************************************************
2382 * Page table page management routines.....
2383 ***************************************************/
2384 static __inline void
2385 pmap_free_zero_pages(struct spglist *free)
2390 for (count = 0; (m = SLIST_FIRST(free)) != NULL; count++) {
2391 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2392 /* Preserve the page's PG_ZERO setting. */
2393 vm_page_free_toq(m);
2395 atomic_subtract_int(&vm_cnt.v_wire_count, count);
2399 * Schedule the specified unused page table page to be freed. Specifically,
2400 * add the page to the specified list of pages that will be released to the
2401 * physical memory manager after the TLB has been updated.
2403 static __inline void
2404 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2405 boolean_t set_PG_ZERO)
2409 m->flags |= PG_ZERO;
2411 m->flags &= ~PG_ZERO;
2412 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2416 * Inserts the specified page table page into the specified pmap's collection
2417 * of idle page table pages. Each of a pmap's page table pages is responsible
2418 * for mapping a distinct range of virtual addresses. The pmap's collection is
2419 * ordered by this virtual address range.
2422 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2425 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2426 return (vm_radix_insert(&pmap->pm_root, mpte));
2430 * Removes the page table page mapping the specified virtual address from the
2431 * specified pmap's collection of idle page table pages, and returns it.
2432 * Otherwise, returns NULL if there is no page table page corresponding to the
2433 * specified virtual address.
2435 static __inline vm_page_t
2436 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
2439 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2440 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
2444 * Decrements a page table page's wire count, which is used to record the
2445 * number of valid page table entries within the page. If the wire count
2446 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2447 * page table page was unmapped and FALSE otherwise.
2449 static inline boolean_t
2450 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2454 if (m->wire_count == 0) {
2455 _pmap_unwire_ptp(pmap, va, m, free);
2462 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2465 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2467 * unmap the page table page
2469 if (m->pindex >= (NUPDE + NUPDPE)) {
2472 pml4 = pmap_pml4e(pmap, va);
2474 if (pmap->pm_pml4u != NULL && va <= VM_MAXUSER_ADDRESS) {
2475 pml4 = &pmap->pm_pml4u[pmap_pml4e_index(va)];
2478 } else if (m->pindex >= NUPDE) {
2481 pdp = pmap_pdpe(pmap, va);
2486 pd = pmap_pde(pmap, va);
2489 pmap_resident_count_dec(pmap, 1);
2490 if (m->pindex < NUPDE) {
2491 /* We just released a PT, unhold the matching PD */
2494 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2495 pmap_unwire_ptp(pmap, va, pdpg, free);
2497 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2498 /* We just released a PD, unhold the matching PDP */
2501 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2502 pmap_unwire_ptp(pmap, va, pdppg, free);
2506 * Put page on a list so that it is released after
2507 * *ALL* TLB shootdown is done
2509 pmap_add_delayed_free_list(m, free, TRUE);
2513 * After removing a page table entry, this routine is used to
2514 * conditionally free the page, and manage the hold/wire counts.
2517 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2518 struct spglist *free)
2522 if (va >= VM_MAXUSER_ADDRESS)
2524 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2525 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2526 return (pmap_unwire_ptp(pmap, va, mpte, free));
2530 pmap_pinit0(pmap_t pmap)
2534 PMAP_LOCK_INIT(pmap);
2535 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2536 pmap->pm_pml4u = NULL;
2537 pmap->pm_cr3 = KPML4phys;
2538 /* hack to keep pmap_pti_pcid_invalidate() alive */
2539 pmap->pm_ucr3 = PMAP_NO_CR3;
2540 pmap->pm_root.rt_root = 0;
2541 CPU_ZERO(&pmap->pm_active);
2542 TAILQ_INIT(&pmap->pm_pvchunk);
2543 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2544 pmap->pm_flags = pmap_flags;
2546 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2547 pmap->pm_pcids[i].pm_gen = 0;
2549 __pcpu[i].pc_kcr3 = PMAP_NO_CR3;
2551 PCPU_SET(curpmap, kernel_pmap);
2552 pmap_activate(curthread);
2553 CPU_FILL(&kernel_pmap->pm_active);
2557 pmap_pinit_pml4(vm_page_t pml4pg)
2559 pml4_entry_t *pm_pml4;
2562 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2564 /* Wire in kernel global address entries. */
2565 for (i = 0; i < NKPML4E; i++) {
2566 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2569 for (i = 0; i < ndmpdpphys; i++) {
2570 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2574 /* install self-referential address mapping entry(s) */
2575 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2576 X86_PG_A | X86_PG_M;
2580 pmap_pinit_pml4_pti(vm_page_t pml4pg)
2582 pml4_entry_t *pm_pml4;
2585 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2586 for (i = 0; i < NPML4EPG; i++)
2587 pm_pml4[i] = pti_pml4[i];
2591 * Initialize a preallocated and zeroed pmap structure,
2592 * such as one in a vmspace structure.
2595 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2597 vm_page_t pml4pg, pml4pgu;
2598 vm_paddr_t pml4phys;
2602 * allocate the page directory page
2604 pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
2605 VM_ALLOC_WIRED | VM_ALLOC_ZERO | VM_ALLOC_WAITOK);
2607 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2608 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2610 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2611 pmap->pm_pcids[i].pm_gen = 0;
2613 pmap->pm_cr3 = PMAP_NO_CR3; /* initialize to an invalid value */
2614 pmap->pm_ucr3 = PMAP_NO_CR3;
2615 pmap->pm_pml4u = NULL;
2617 pmap->pm_type = pm_type;
2618 if ((pml4pg->flags & PG_ZERO) == 0)
2619 pagezero(pmap->pm_pml4);
2622 * Do not install the host kernel mappings in the nested page
2623 * tables. These mappings are meaningless in the guest physical
2625 * Install minimal kernel mappings in PTI case.
2627 if (pm_type == PT_X86) {
2628 pmap->pm_cr3 = pml4phys;
2629 pmap_pinit_pml4(pml4pg);
2631 pml4pgu = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2632 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2633 pmap->pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(
2634 VM_PAGE_TO_PHYS(pml4pgu));
2635 pmap_pinit_pml4_pti(pml4pgu);
2636 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pml4pgu);
2640 pmap->pm_root.rt_root = 0;
2641 CPU_ZERO(&pmap->pm_active);
2642 TAILQ_INIT(&pmap->pm_pvchunk);
2643 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2644 pmap->pm_flags = flags;
2645 pmap->pm_eptgen = 0;
2651 pmap_pinit(pmap_t pmap)
2654 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2658 * This routine is called if the desired page table page does not exist.
2660 * If page table page allocation fails, this routine may sleep before
2661 * returning NULL. It sleeps only if a lock pointer was given.
2663 * Note: If a page allocation fails at page table level two or three,
2664 * one or two pages may be held during the wait, only to be released
2665 * afterwards. This conservative approach is easily argued to avoid
2669 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2671 vm_page_t m, pdppg, pdpg;
2672 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2674 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2676 PG_A = pmap_accessed_bit(pmap);
2677 PG_M = pmap_modified_bit(pmap);
2678 PG_V = pmap_valid_bit(pmap);
2679 PG_RW = pmap_rw_bit(pmap);
2682 * Allocate a page table page.
2684 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2685 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2686 if (lockp != NULL) {
2687 RELEASE_PV_LIST_LOCK(lockp);
2689 PMAP_ASSERT_NOT_IN_DI();
2695 * Indicate the need to retry. While waiting, the page table
2696 * page may have been allocated.
2700 if ((m->flags & PG_ZERO) == 0)
2704 * Map the pagetable page into the process address space, if
2705 * it isn't already there.
2708 if (ptepindex >= (NUPDE + NUPDPE)) {
2709 pml4_entry_t *pml4, *pml4u;
2710 vm_pindex_t pml4index;
2712 /* Wire up a new PDPE page */
2713 pml4index = ptepindex - (NUPDE + NUPDPE);
2714 pml4 = &pmap->pm_pml4[pml4index];
2715 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2716 if (pmap->pm_pml4u != NULL && pml4index < NUPML4E) {
2718 * PTI: Make all user-space mappings in the
2719 * kernel-mode page table no-execute so that
2720 * we detect any programming errors that leave
2721 * the kernel-mode page table active on return
2726 pml4u = &pmap->pm_pml4u[pml4index];
2727 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
2731 } else if (ptepindex >= NUPDE) {
2732 vm_pindex_t pml4index;
2733 vm_pindex_t pdpindex;
2737 /* Wire up a new PDE page */
2738 pdpindex = ptepindex - NUPDE;
2739 pml4index = pdpindex >> NPML4EPGSHIFT;
2741 pml4 = &pmap->pm_pml4[pml4index];
2742 if ((*pml4 & PG_V) == 0) {
2743 /* Have to allocate a new pdp, recurse */
2744 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2747 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2748 vm_page_free_zero(m);
2752 /* Add reference to pdp page */
2753 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2754 pdppg->wire_count++;
2756 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2758 /* Now find the pdp page */
2759 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2760 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2763 vm_pindex_t pml4index;
2764 vm_pindex_t pdpindex;
2769 /* Wire up a new PTE page */
2770 pdpindex = ptepindex >> NPDPEPGSHIFT;
2771 pml4index = pdpindex >> NPML4EPGSHIFT;
2773 /* First, find the pdp and check that its valid. */
2774 pml4 = &pmap->pm_pml4[pml4index];
2775 if ((*pml4 & PG_V) == 0) {
2776 /* Have to allocate a new pd, recurse */
2777 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2780 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2781 vm_page_free_zero(m);
2784 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2785 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2787 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2788 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2789 if ((*pdp & PG_V) == 0) {
2790 /* Have to allocate a new pd, recurse */
2791 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2794 atomic_subtract_int(&vm_cnt.v_wire_count,
2796 vm_page_free_zero(m);
2800 /* Add reference to the pd page */
2801 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2805 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2807 /* Now we know where the page directory page is */
2808 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2809 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2812 pmap_resident_count_inc(pmap, 1);
2818 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2820 vm_pindex_t pdpindex, ptepindex;
2821 pdp_entry_t *pdpe, PG_V;
2824 PG_V = pmap_valid_bit(pmap);
2827 pdpe = pmap_pdpe(pmap, va);
2828 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2829 /* Add a reference to the pd page. */
2830 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2833 /* Allocate a pd page. */
2834 ptepindex = pmap_pde_pindex(va);
2835 pdpindex = ptepindex >> NPDPEPGSHIFT;
2836 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2837 if (pdpg == NULL && lockp != NULL)
2844 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2846 vm_pindex_t ptepindex;
2847 pd_entry_t *pd, PG_V;
2850 PG_V = pmap_valid_bit(pmap);
2853 * Calculate pagetable page index
2855 ptepindex = pmap_pde_pindex(va);
2858 * Get the page directory entry
2860 pd = pmap_pde(pmap, va);
2863 * This supports switching from a 2MB page to a
2866 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2867 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2869 * Invalidation of the 2MB page mapping may have caused
2870 * the deallocation of the underlying PD page.
2877 * If the page table page is mapped, we just increment the
2878 * hold count, and activate it.
2880 if (pd != NULL && (*pd & PG_V) != 0) {
2881 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2885 * Here if the pte page isn't mapped, or if it has been
2888 m = _pmap_allocpte(pmap, ptepindex, lockp);
2889 if (m == NULL && lockp != NULL)
2896 /***************************************************
2897 * Pmap allocation/deallocation routines.
2898 ***************************************************/
2901 * Release any resources held by the given physical map.
2902 * Called when a pmap initialized by pmap_pinit is being released.
2903 * Should only be called if the map contains no valid mappings.
2906 pmap_release(pmap_t pmap)
2911 KASSERT(pmap->pm_stats.resident_count == 0,
2912 ("pmap_release: pmap resident count %ld != 0",
2913 pmap->pm_stats.resident_count));
2914 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2915 ("pmap_release: pmap has reserved page table page(s)"));
2916 KASSERT(CPU_EMPTY(&pmap->pm_active),
2917 ("releasing active pmap %p", pmap));
2919 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2921 for (i = 0; i < NKPML4E; i++) /* KVA */
2922 pmap->pm_pml4[KPML4BASE + i] = 0;
2923 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
2924 pmap->pm_pml4[DMPML4I + i] = 0;
2925 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
2928 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2929 vm_page_free_zero(m);
2931 if (pmap->pm_pml4u != NULL) {
2932 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4u));
2934 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2940 kvm_size(SYSCTL_HANDLER_ARGS)
2942 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2944 return sysctl_handle_long(oidp, &ksize, 0, req);
2946 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2947 0, 0, kvm_size, "LU", "Size of KVM");
2950 kvm_free(SYSCTL_HANDLER_ARGS)
2952 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2954 return sysctl_handle_long(oidp, &kfree, 0, req);
2956 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2957 0, 0, kvm_free, "LU", "Amount of KVM free");
2960 * grow the number of kernel page table entries, if needed
2963 pmap_growkernel(vm_offset_t addr)
2967 pd_entry_t *pde, newpdir;
2970 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2973 * Return if "addr" is within the range of kernel page table pages
2974 * that were preallocated during pmap bootstrap. Moreover, leave
2975 * "kernel_vm_end" and the kernel page table as they were.
2977 * The correctness of this action is based on the following
2978 * argument: vm_map_insert() allocates contiguous ranges of the
2979 * kernel virtual address space. It calls this function if a range
2980 * ends after "kernel_vm_end". If the kernel is mapped between
2981 * "kernel_vm_end" and "addr", then the range cannot begin at
2982 * "kernel_vm_end". In fact, its beginning address cannot be less
2983 * than the kernel. Thus, there is no immediate need to allocate
2984 * any new kernel page table pages between "kernel_vm_end" and
2987 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
2990 addr = roundup2(addr, NBPDR);
2991 if (addr - 1 >= kernel_map->max_offset)
2992 addr = kernel_map->max_offset;
2993 while (kernel_vm_end < addr) {
2994 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
2995 if ((*pdpe & X86_PG_V) == 0) {
2996 /* We need a new PDP entry */
2997 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
2998 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
2999 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
3001 panic("pmap_growkernel: no memory to grow kernel");
3002 if ((nkpg->flags & PG_ZERO) == 0)
3003 pmap_zero_page(nkpg);
3004 paddr = VM_PAGE_TO_PHYS(nkpg);
3005 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
3006 X86_PG_A | X86_PG_M);
3007 continue; /* try again */
3009 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
3010 if ((*pde & X86_PG_V) != 0) {
3011 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3012 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
3013 kernel_vm_end = kernel_map->max_offset;
3019 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
3020 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
3023 panic("pmap_growkernel: no memory to grow kernel");
3024 if ((nkpg->flags & PG_ZERO) == 0)
3025 pmap_zero_page(nkpg);
3026 paddr = VM_PAGE_TO_PHYS(nkpg);
3027 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
3028 pde_store(pde, newpdir);
3030 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3031 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
3032 kernel_vm_end = kernel_map->max_offset;
3039 /***************************************************
3040 * page management routines.
3041 ***************************************************/
3043 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
3044 CTASSERT(_NPCM == 3);
3045 CTASSERT(_NPCPV == 168);
3047 static __inline struct pv_chunk *
3048 pv_to_chunk(pv_entry_t pv)
3051 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
3054 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
3056 #define PC_FREE0 0xfffffffffffffffful
3057 #define PC_FREE1 0xfffffffffffffffful
3058 #define PC_FREE2 0x000000fffffffffful
3060 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
3063 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
3065 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
3066 "Current number of pv entry chunks");
3067 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
3068 "Current number of pv entry chunks allocated");
3069 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
3070 "Current number of pv entry chunks frees");
3071 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
3072 "Number of times tried to get a chunk page but failed.");
3074 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
3075 static int pv_entry_spare;
3077 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
3078 "Current number of pv entry frees");
3079 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
3080 "Current number of pv entry allocs");
3081 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
3082 "Current number of pv entries");
3083 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
3084 "Current number of spare pv entries");
3088 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
3093 pmap_invalidate_all(pmap);
3094 if (pmap != locked_pmap)
3097 pmap_delayed_invl_finished();
3101 * We are in a serious low memory condition. Resort to
3102 * drastic measures to free some pages so we can allocate
3103 * another pv entry chunk.
3105 * Returns NULL if PV entries were reclaimed from the specified pmap.
3107 * We do not, however, unmap 2mpages because subsequent accesses will
3108 * allocate per-page pv entries until repromotion occurs, thereby
3109 * exacerbating the shortage of free pv entries.
3112 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
3114 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
3115 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
3116 struct md_page *pvh;
3118 pmap_t next_pmap, pmap;
3119 pt_entry_t *pte, tpte;
3120 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3124 struct spglist free;
3126 int bit, field, freed;
3128 static int active_reclaims = 0;
3130 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
3131 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
3134 PG_G = PG_A = PG_M = PG_RW = 0;
3136 bzero(&pc_marker_b, sizeof(pc_marker_b));
3137 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
3138 pc_marker = (struct pv_chunk *)&pc_marker_b;
3139 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
3142 * A delayed invalidation block should already be active if
3143 * pmap_advise() or pmap_remove() called this function by way
3144 * of pmap_demote_pde_locked().
3146 start_di = pmap_not_in_di();
3148 mtx_lock(&pv_chunks_mutex);
3150 TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
3151 TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
3152 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
3153 SLIST_EMPTY(&free)) {
3154 next_pmap = pc->pc_pmap;
3155 if (next_pmap == NULL) {
3157 * The next chunk is a marker. However, it is
3158 * not our marker, so active_reclaims must be
3159 * > 1. Consequently, the next_chunk code
3160 * will not rotate the pv_chunks list.
3164 mtx_unlock(&pv_chunks_mutex);
3167 * A pv_chunk can only be removed from the pc_lru list
3168 * when both pc_chunks_mutex is owned and the
3169 * corresponding pmap is locked.
3171 if (pmap != next_pmap) {
3172 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
3175 /* Avoid deadlock and lock recursion. */
3176 if (pmap > locked_pmap) {
3177 RELEASE_PV_LIST_LOCK(lockp);
3180 pmap_delayed_invl_started();
3181 mtx_lock(&pv_chunks_mutex);
3183 } else if (pmap != locked_pmap) {
3184 if (PMAP_TRYLOCK(pmap)) {
3186 pmap_delayed_invl_started();
3187 mtx_lock(&pv_chunks_mutex);
3190 pmap = NULL; /* pmap is not locked */
3191 mtx_lock(&pv_chunks_mutex);
3192 pc = TAILQ_NEXT(pc_marker, pc_lru);
3194 pc->pc_pmap != next_pmap)
3198 } else if (start_di)
3199 pmap_delayed_invl_started();
3200 PG_G = pmap_global_bit(pmap);
3201 PG_A = pmap_accessed_bit(pmap);
3202 PG_M = pmap_modified_bit(pmap);
3203 PG_RW = pmap_rw_bit(pmap);
3207 * Destroy every non-wired, 4 KB page mapping in the chunk.
3210 for (field = 0; field < _NPCM; field++) {
3211 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
3212 inuse != 0; inuse &= ~(1UL << bit)) {
3214 pv = &pc->pc_pventry[field * 64 + bit];
3216 pde = pmap_pde(pmap, va);
3217 if ((*pde & PG_PS) != 0)
3219 pte = pmap_pde_to_pte(pde, va);
3220 if ((*pte & PG_W) != 0)
3222 tpte = pte_load_clear(pte);
3223 if ((tpte & PG_G) != 0)
3224 pmap_invalidate_page(pmap, va);
3225 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3226 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3228 if ((tpte & PG_A) != 0)
3229 vm_page_aflag_set(m, PGA_REFERENCED);
3230 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3231 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3233 if (TAILQ_EMPTY(&m->md.pv_list) &&
3234 (m->flags & PG_FICTITIOUS) == 0) {
3235 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3236 if (TAILQ_EMPTY(&pvh->pv_list)) {
3237 vm_page_aflag_clear(m,
3241 pmap_delayed_invl_page(m);
3242 pc->pc_map[field] |= 1UL << bit;
3243 pmap_unuse_pt(pmap, va, *pde, &free);
3248 mtx_lock(&pv_chunks_mutex);
3251 /* Every freed mapping is for a 4 KB page. */
3252 pmap_resident_count_dec(pmap, freed);
3253 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
3254 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
3255 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
3256 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3257 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
3258 pc->pc_map[2] == PC_FREE2) {
3259 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3260 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3261 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3262 /* Entire chunk is free; return it. */
3263 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3264 dump_drop_page(m_pc->phys_addr);
3265 mtx_lock(&pv_chunks_mutex);
3266 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3269 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3270 mtx_lock(&pv_chunks_mutex);
3271 /* One freed pv entry in locked_pmap is sufficient. */
3272 if (pmap == locked_pmap)
3275 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3276 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
3277 if (active_reclaims == 1 && pmap != NULL) {
3279 * Rotate the pv chunks list so that we do not
3280 * scan the same pv chunks that could not be
3281 * freed (because they contained a wired
3282 * and/or superpage mapping) on every
3283 * invocation of reclaim_pv_chunk().
3285 while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
3286 MPASS(pc->pc_pmap != NULL);
3287 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3288 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3292 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3293 TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
3295 mtx_unlock(&pv_chunks_mutex);
3296 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
3297 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
3298 m_pc = SLIST_FIRST(&free);
3299 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3300 /* Recycle a freed page table page. */
3301 m_pc->wire_count = 1;
3303 pmap_free_zero_pages(&free);
3308 * free the pv_entry back to the free list
3311 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3313 struct pv_chunk *pc;
3314 int idx, field, bit;
3316 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3317 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3318 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3319 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3320 pc = pv_to_chunk(pv);
3321 idx = pv - &pc->pc_pventry[0];
3324 pc->pc_map[field] |= 1ul << bit;
3325 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3326 pc->pc_map[2] != PC_FREE2) {
3327 /* 98% of the time, pc is already at the head of the list. */
3328 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3329 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3330 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3334 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3339 free_pv_chunk(struct pv_chunk *pc)
3343 mtx_lock(&pv_chunks_mutex);
3344 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3345 mtx_unlock(&pv_chunks_mutex);
3346 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3347 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3348 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3349 /* entire chunk is free, return it */
3350 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3351 dump_drop_page(m->phys_addr);
3352 vm_page_unwire(m, PQ_NONE);
3357 * Returns a new PV entry, allocating a new PV chunk from the system when
3358 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3359 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3362 * The given PV list lock may be released.
3365 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3369 struct pv_chunk *pc;
3372 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3373 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3375 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3377 for (field = 0; field < _NPCM; field++) {
3378 if (pc->pc_map[field]) {
3379 bit = bsfq(pc->pc_map[field]);
3383 if (field < _NPCM) {
3384 pv = &pc->pc_pventry[field * 64 + bit];
3385 pc->pc_map[field] &= ~(1ul << bit);
3386 /* If this was the last item, move it to tail */
3387 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3388 pc->pc_map[2] == 0) {
3389 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3390 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3393 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3394 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3398 /* No free items, allocate another chunk */
3399 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3402 if (lockp == NULL) {
3403 PV_STAT(pc_chunk_tryfail++);
3406 m = reclaim_pv_chunk(pmap, lockp);
3410 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3411 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3412 dump_add_page(m->phys_addr);
3413 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3415 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3416 pc->pc_map[1] = PC_FREE1;
3417 pc->pc_map[2] = PC_FREE2;
3418 mtx_lock(&pv_chunks_mutex);
3419 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3420 mtx_unlock(&pv_chunks_mutex);
3421 pv = &pc->pc_pventry[0];
3422 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3423 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3424 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3429 * Returns the number of one bits within the given PV chunk map.
3431 * The erratas for Intel processors state that "POPCNT Instruction May
3432 * Take Longer to Execute Than Expected". It is believed that the
3433 * issue is the spurious dependency on the destination register.
3434 * Provide a hint to the register rename logic that the destination
3435 * value is overwritten, by clearing it, as suggested in the
3436 * optimization manual. It should be cheap for unaffected processors
3439 * Reference numbers for erratas are
3440 * 4th Gen Core: HSD146
3441 * 5th Gen Core: BDM85
3442 * 6th Gen Core: SKL029
3445 popcnt_pc_map_pq(uint64_t *map)
3449 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3450 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3451 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3452 : "=&r" (result), "=&r" (tmp)
3453 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3458 * Ensure that the number of spare PV entries in the specified pmap meets or
3459 * exceeds the given count, "needed".
3461 * The given PV list lock may be released.
3464 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3466 struct pch new_tail;
3467 struct pv_chunk *pc;
3471 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3472 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3475 * Newly allocated PV chunks must be stored in a private list until
3476 * the required number of PV chunks have been allocated. Otherwise,
3477 * reclaim_pv_chunk() could recycle one of these chunks. In
3478 * contrast, these chunks must be added to the pmap upon allocation.
3480 TAILQ_INIT(&new_tail);
3483 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3485 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3486 bit_count((bitstr_t *)pc->pc_map, 0,
3487 sizeof(pc->pc_map) * NBBY, &free);
3490 free = popcnt_pc_map_pq(pc->pc_map);
3494 if (avail >= needed)
3497 for (; avail < needed; avail += _NPCPV) {
3498 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3501 m = reclaim_pv_chunk(pmap, lockp);
3505 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3506 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3507 dump_add_page(m->phys_addr);
3508 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3510 pc->pc_map[0] = PC_FREE0;
3511 pc->pc_map[1] = PC_FREE1;
3512 pc->pc_map[2] = PC_FREE2;
3513 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3514 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3515 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3517 if (!TAILQ_EMPTY(&new_tail)) {
3518 mtx_lock(&pv_chunks_mutex);
3519 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3520 mtx_unlock(&pv_chunks_mutex);
3525 * First find and then remove the pv entry for the specified pmap and virtual
3526 * address from the specified pv list. Returns the pv entry if found and NULL
3527 * otherwise. This operation can be performed on pv lists for either 4KB or
3528 * 2MB page mappings.
3530 static __inline pv_entry_t
3531 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3535 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3536 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3537 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3546 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3547 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3548 * entries for each of the 4KB page mappings.
3551 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3552 struct rwlock **lockp)
3554 struct md_page *pvh;
3555 struct pv_chunk *pc;
3557 vm_offset_t va_last;
3561 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3562 KASSERT((pa & PDRMASK) == 0,
3563 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3564 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3567 * Transfer the 2mpage's pv entry for this mapping to the first
3568 * page's pv list. Once this transfer begins, the pv list lock
3569 * must not be released until the last pv entry is reinstantiated.
3571 pvh = pa_to_pvh(pa);
3572 va = trunc_2mpage(va);
3573 pv = pmap_pvh_remove(pvh, pmap, va);
3574 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3575 m = PHYS_TO_VM_PAGE(pa);
3576 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3578 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3579 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3580 va_last = va + NBPDR - PAGE_SIZE;
3582 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3583 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3584 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3585 for (field = 0; field < _NPCM; field++) {
3586 while (pc->pc_map[field]) {
3587 bit = bsfq(pc->pc_map[field]);
3588 pc->pc_map[field] &= ~(1ul << bit);
3589 pv = &pc->pc_pventry[field * 64 + bit];
3593 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3594 ("pmap_pv_demote_pde: page %p is not managed", m));
3595 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3601 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3602 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3605 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3606 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3607 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3609 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3610 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3613 #if VM_NRESERVLEVEL > 0
3615 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3616 * replace the many pv entries for the 4KB page mappings by a single pv entry
3617 * for the 2MB page mapping.
3620 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3621 struct rwlock **lockp)
3623 struct md_page *pvh;
3625 vm_offset_t va_last;
3628 KASSERT((pa & PDRMASK) == 0,
3629 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3630 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3633 * Transfer the first page's pv entry for this mapping to the 2mpage's
3634 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3635 * a transfer avoids the possibility that get_pv_entry() calls
3636 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3637 * mappings that is being promoted.
3639 m = PHYS_TO_VM_PAGE(pa);
3640 va = trunc_2mpage(va);
3641 pv = pmap_pvh_remove(&m->md, pmap, va);
3642 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3643 pvh = pa_to_pvh(pa);
3644 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3646 /* Free the remaining NPTEPG - 1 pv entries. */
3647 va_last = va + NBPDR - PAGE_SIZE;
3651 pmap_pvh_free(&m->md, pmap, va);
3652 } while (va < va_last);
3654 #endif /* VM_NRESERVLEVEL > 0 */
3657 * First find and then destroy the pv entry for the specified pmap and virtual
3658 * address. This operation can be performed on pv lists for either 4KB or 2MB
3662 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3666 pv = pmap_pvh_remove(pvh, pmap, va);
3667 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3668 free_pv_entry(pmap, pv);
3672 * Conditionally create the PV entry for a 4KB page mapping if the required
3673 * memory can be allocated without resorting to reclamation.
3676 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3677 struct rwlock **lockp)
3681 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3682 /* Pass NULL instead of the lock pointer to disable reclamation. */
3683 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3685 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3686 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3694 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3695 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3696 * false if the PV entry cannot be allocated without resorting to reclamation.
3699 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
3700 struct rwlock **lockp)
3702 struct md_page *pvh;
3706 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3707 /* Pass NULL instead of the lock pointer to disable reclamation. */
3708 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3709 NULL : lockp)) == NULL)
3712 pa = pde & PG_PS_FRAME;
3713 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3714 pvh = pa_to_pvh(pa);
3715 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3721 * Fills a page table page with mappings to consecutive physical pages.
3724 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3728 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3730 newpte += PAGE_SIZE;
3735 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3736 * mapping is invalidated.
3739 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3741 struct rwlock *lock;
3745 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3752 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3753 struct rwlock **lockp)
3755 pd_entry_t newpde, oldpde;
3756 pt_entry_t *firstpte, newpte;
3757 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3760 struct spglist free;
3764 PG_G = pmap_global_bit(pmap);
3765 PG_A = pmap_accessed_bit(pmap);
3766 PG_M = pmap_modified_bit(pmap);
3767 PG_RW = pmap_rw_bit(pmap);
3768 PG_V = pmap_valid_bit(pmap);
3769 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3771 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3773 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3774 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3775 if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
3777 KASSERT((oldpde & PG_W) == 0,
3778 ("pmap_demote_pde: page table page for a wired mapping"
3782 * Invalidate the 2MB page mapping and return "failure" if the
3783 * mapping was never accessed or the allocation of the new
3784 * page table page fails. If the 2MB page mapping belongs to
3785 * the direct map region of the kernel's address space, then
3786 * the page allocation request specifies the highest possible
3787 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3788 * normal. Page table pages are preallocated for every other
3789 * part of the kernel address space, so the direct map region
3790 * is the only part of the kernel address space that must be
3793 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3794 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3795 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3796 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3798 sva = trunc_2mpage(va);
3799 pmap_remove_pde(pmap, pde, sva, &free, lockp);
3800 if ((oldpde & PG_G) == 0)
3801 pmap_invalidate_pde_page(pmap, sva, oldpde);
3802 pmap_free_zero_pages(&free);
3803 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3804 " in pmap %p", va, pmap);
3807 if (va < VM_MAXUSER_ADDRESS)
3808 pmap_resident_count_inc(pmap, 1);
3810 mptepa = VM_PAGE_TO_PHYS(mpte);
3811 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3812 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3813 KASSERT((oldpde & PG_A) != 0,
3814 ("pmap_demote_pde: oldpde is missing PG_A"));
3815 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3816 ("pmap_demote_pde: oldpde is missing PG_M"));
3817 newpte = oldpde & ~PG_PS;
3818 newpte = pmap_swap_pat(pmap, newpte);
3821 * If the page table page is new, initialize it.
3823 if (mpte->wire_count == 1) {
3824 mpte->wire_count = NPTEPG;
3825 pmap_fill_ptp(firstpte, newpte);
3827 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3828 ("pmap_demote_pde: firstpte and newpte map different physical"
3832 * If the mapping has changed attributes, update the page table
3835 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3836 pmap_fill_ptp(firstpte, newpte);
3839 * The spare PV entries must be reserved prior to demoting the
3840 * mapping, that is, prior to changing the PDE. Otherwise, the state
3841 * of the PDE and the PV lists will be inconsistent, which can result
3842 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3843 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3844 * PV entry for the 2MB page mapping that is being demoted.
3846 if ((oldpde & PG_MANAGED) != 0)
3847 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3850 * Demote the mapping. This pmap is locked. The old PDE has
3851 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3852 * set. Thus, there is no danger of a race with another
3853 * processor changing the setting of PG_A and/or PG_M between
3854 * the read above and the store below.
3856 if (workaround_erratum383)
3857 pmap_update_pde(pmap, va, pde, newpde);
3859 pde_store(pde, newpde);
3862 * Invalidate a stale recursive mapping of the page table page.
3864 if (va >= VM_MAXUSER_ADDRESS)
3865 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3868 * Demote the PV entry.
3870 if ((oldpde & PG_MANAGED) != 0)
3871 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3873 atomic_add_long(&pmap_pde_demotions, 1);
3874 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3875 " in pmap %p", va, pmap);
3880 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3883 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3889 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3890 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3891 mpte = pmap_remove_pt_page(pmap, va);
3893 panic("pmap_remove_kernel_pde: Missing pt page.");
3895 mptepa = VM_PAGE_TO_PHYS(mpte);
3896 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3899 * Initialize the page table page.
3901 pagezero((void *)PHYS_TO_DMAP(mptepa));
3904 * Demote the mapping.
3906 if (workaround_erratum383)
3907 pmap_update_pde(pmap, va, pde, newpde);
3909 pde_store(pde, newpde);
3912 * Invalidate a stale recursive mapping of the page table page.
3914 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3918 * pmap_remove_pde: do the things to unmap a superpage in a process
3921 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
3922 struct spglist *free, struct rwlock **lockp)
3924 struct md_page *pvh;
3926 vm_offset_t eva, va;
3928 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3930 PG_G = pmap_global_bit(pmap);
3931 PG_A = pmap_accessed_bit(pmap);
3932 PG_M = pmap_modified_bit(pmap);
3933 PG_RW = pmap_rw_bit(pmap);
3935 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3936 KASSERT((sva & PDRMASK) == 0,
3937 ("pmap_remove_pde: sva is not 2mpage aligned"));
3938 oldpde = pte_load_clear(pdq);
3940 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
3941 if ((oldpde & PG_G) != 0)
3942 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
3943 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
3944 if (oldpde & PG_MANAGED) {
3945 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
3946 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
3947 pmap_pvh_free(pvh, pmap, sva);
3949 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3950 va < eva; va += PAGE_SIZE, m++) {
3951 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3954 vm_page_aflag_set(m, PGA_REFERENCED);
3955 if (TAILQ_EMPTY(&m->md.pv_list) &&
3956 TAILQ_EMPTY(&pvh->pv_list))
3957 vm_page_aflag_clear(m, PGA_WRITEABLE);
3958 pmap_delayed_invl_page(m);
3961 if (pmap == kernel_pmap) {
3962 pmap_remove_kernel_pde(pmap, pdq, sva);
3964 mpte = pmap_remove_pt_page(pmap, sva);
3966 pmap_resident_count_dec(pmap, 1);
3967 KASSERT(mpte->wire_count == NPTEPG,
3968 ("pmap_remove_pde: pte page wire count error"));
3969 mpte->wire_count = 0;
3970 pmap_add_delayed_free_list(mpte, free, FALSE);
3973 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
3977 * pmap_remove_pte: do the things to unmap a page in a process
3980 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
3981 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
3983 struct md_page *pvh;
3984 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
3987 PG_A = pmap_accessed_bit(pmap);
3988 PG_M = pmap_modified_bit(pmap);
3989 PG_RW = pmap_rw_bit(pmap);
3991 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3992 oldpte = pte_load_clear(ptq);
3994 pmap->pm_stats.wired_count -= 1;
3995 pmap_resident_count_dec(pmap, 1);
3996 if (oldpte & PG_MANAGED) {
3997 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
3998 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4001 vm_page_aflag_set(m, PGA_REFERENCED);
4002 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
4003 pmap_pvh_free(&m->md, pmap, va);
4004 if (TAILQ_EMPTY(&m->md.pv_list) &&
4005 (m->flags & PG_FICTITIOUS) == 0) {
4006 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4007 if (TAILQ_EMPTY(&pvh->pv_list))
4008 vm_page_aflag_clear(m, PGA_WRITEABLE);
4010 pmap_delayed_invl_page(m);
4012 return (pmap_unuse_pt(pmap, va, ptepde, free));
4016 * Remove a single page from a process address space
4019 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
4020 struct spglist *free)
4022 struct rwlock *lock;
4023 pt_entry_t *pte, PG_V;
4025 PG_V = pmap_valid_bit(pmap);
4026 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4027 if ((*pde & PG_V) == 0)
4029 pte = pmap_pde_to_pte(pde, va);
4030 if ((*pte & PG_V) == 0)
4033 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
4036 pmap_invalidate_page(pmap, va);
4040 * Removes the specified range of addresses from the page table page.
4043 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
4044 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
4046 pt_entry_t PG_G, *pte;
4050 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4051 PG_G = pmap_global_bit(pmap);
4054 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
4058 pmap_invalidate_range(pmap, va, sva);
4063 if ((*pte & PG_G) == 0)
4067 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
4073 pmap_invalidate_range(pmap, va, sva);
4078 * Remove the given range of addresses from the specified map.
4080 * It is assumed that the start and end are properly
4081 * rounded to the page size.
4084 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4086 struct rwlock *lock;
4087 vm_offset_t va_next;
4088 pml4_entry_t *pml4e;
4090 pd_entry_t ptpaddr, *pde;
4091 pt_entry_t PG_G, PG_V;
4092 struct spglist free;
4095 PG_G = pmap_global_bit(pmap);
4096 PG_V = pmap_valid_bit(pmap);
4099 * Perform an unsynchronized read. This is, however, safe.
4101 if (pmap->pm_stats.resident_count == 0)
4107 pmap_delayed_invl_started();
4111 * special handling of removing one page. a very
4112 * common operation and easy to short circuit some
4115 if (sva + PAGE_SIZE == eva) {
4116 pde = pmap_pde(pmap, sva);
4117 if (pde && (*pde & PG_PS) == 0) {
4118 pmap_remove_page(pmap, sva, pde, &free);
4124 for (; sva < eva; sva = va_next) {
4126 if (pmap->pm_stats.resident_count == 0)
4129 pml4e = pmap_pml4e(pmap, sva);
4130 if ((*pml4e & PG_V) == 0) {
4131 va_next = (sva + NBPML4) & ~PML4MASK;
4137 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4138 if ((*pdpe & PG_V) == 0) {
4139 va_next = (sva + NBPDP) & ~PDPMASK;
4146 * Calculate index for next page table.
4148 va_next = (sva + NBPDR) & ~PDRMASK;
4152 pde = pmap_pdpe_to_pde(pdpe, sva);
4156 * Weed out invalid mappings.
4162 * Check for large page.
4164 if ((ptpaddr & PG_PS) != 0) {
4166 * Are we removing the entire large page? If not,
4167 * demote the mapping and fall through.
4169 if (sva + NBPDR == va_next && eva >= va_next) {
4171 * The TLB entry for a PG_G mapping is
4172 * invalidated by pmap_remove_pde().
4174 if ((ptpaddr & PG_G) == 0)
4176 pmap_remove_pde(pmap, pde, sva, &free, &lock);
4178 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
4180 /* The large page mapping was destroyed. */
4187 * Limit our scan to either the end of the va represented
4188 * by the current page table page, or to the end of the
4189 * range being removed.
4194 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
4201 pmap_invalidate_all(pmap);
4203 pmap_delayed_invl_finished();
4204 pmap_free_zero_pages(&free);
4208 * Routine: pmap_remove_all
4210 * Removes this physical page from
4211 * all physical maps in which it resides.
4212 * Reflects back modify bits to the pager.
4215 * Original versions of this routine were very
4216 * inefficient because they iteratively called
4217 * pmap_remove (slow...)
4221 pmap_remove_all(vm_page_t m)
4223 struct md_page *pvh;
4226 struct rwlock *lock;
4227 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
4230 struct spglist free;
4231 int pvh_gen, md_gen;
4233 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4234 ("pmap_remove_all: page %p is not managed", m));
4236 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4237 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
4238 pa_to_pvh(VM_PAGE_TO_PHYS(m));
4241 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
4243 if (!PMAP_TRYLOCK(pmap)) {
4244 pvh_gen = pvh->pv_gen;
4248 if (pvh_gen != pvh->pv_gen) {
4255 pde = pmap_pde(pmap, va);
4256 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
4259 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4261 if (!PMAP_TRYLOCK(pmap)) {
4262 pvh_gen = pvh->pv_gen;
4263 md_gen = m->md.pv_gen;
4267 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
4273 PG_A = pmap_accessed_bit(pmap);
4274 PG_M = pmap_modified_bit(pmap);
4275 PG_RW = pmap_rw_bit(pmap);
4276 pmap_resident_count_dec(pmap, 1);
4277 pde = pmap_pde(pmap, pv->pv_va);
4278 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
4279 " a 2mpage in page %p's pv list", m));
4280 pte = pmap_pde_to_pte(pde, pv->pv_va);
4281 tpte = pte_load_clear(pte);
4283 pmap->pm_stats.wired_count--;
4285 vm_page_aflag_set(m, PGA_REFERENCED);
4288 * Update the vm_page_t clean and reference bits.
4290 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4292 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
4293 pmap_invalidate_page(pmap, pv->pv_va);
4294 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4296 free_pv_entry(pmap, pv);
4299 vm_page_aflag_clear(m, PGA_WRITEABLE);
4301 pmap_delayed_invl_wait(m);
4302 pmap_free_zero_pages(&free);
4306 * pmap_protect_pde: do the things to protect a 2mpage in a process
4309 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
4311 pd_entry_t newpde, oldpde;
4312 vm_offset_t eva, va;
4314 boolean_t anychanged;
4315 pt_entry_t PG_G, PG_M, PG_RW;
4317 PG_G = pmap_global_bit(pmap);
4318 PG_M = pmap_modified_bit(pmap);
4319 PG_RW = pmap_rw_bit(pmap);
4321 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4322 KASSERT((sva & PDRMASK) == 0,
4323 ("pmap_protect_pde: sva is not 2mpage aligned"));
4326 oldpde = newpde = *pde;
4327 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4328 (PG_MANAGED | PG_M | PG_RW)) {
4330 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4331 va < eva; va += PAGE_SIZE, m++)
4334 if ((prot & VM_PROT_WRITE) == 0)
4335 newpde &= ~(PG_RW | PG_M);
4336 if ((prot & VM_PROT_EXECUTE) == 0)
4338 if (newpde != oldpde) {
4340 * As an optimization to future operations on this PDE, clear
4341 * PG_PROMOTED. The impending invalidation will remove any
4342 * lingering 4KB page mappings from the TLB.
4344 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
4346 if ((oldpde & PG_G) != 0)
4347 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4351 return (anychanged);
4355 * Set the physical protection on the
4356 * specified range of this map as requested.
4359 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4361 vm_offset_t va_next;
4362 pml4_entry_t *pml4e;
4364 pd_entry_t ptpaddr, *pde;
4365 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4366 boolean_t anychanged;
4368 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4369 if (prot == VM_PROT_NONE) {
4370 pmap_remove(pmap, sva, eva);
4374 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4375 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4378 PG_G = pmap_global_bit(pmap);
4379 PG_M = pmap_modified_bit(pmap);
4380 PG_V = pmap_valid_bit(pmap);
4381 PG_RW = pmap_rw_bit(pmap);
4385 * Although this function delays and batches the invalidation
4386 * of stale TLB entries, it does not need to call
4387 * pmap_delayed_invl_started() and
4388 * pmap_delayed_invl_finished(), because it does not
4389 * ordinarily destroy mappings. Stale TLB entries from
4390 * protection-only changes need only be invalidated before the
4391 * pmap lock is released, because protection-only changes do
4392 * not destroy PV entries. Even operations that iterate over
4393 * a physical page's PV list of mappings, like
4394 * pmap_remove_write(), acquire the pmap lock for each
4395 * mapping. Consequently, for protection-only changes, the
4396 * pmap lock suffices to synchronize both page table and TLB
4399 * This function only destroys a mapping if pmap_demote_pde()
4400 * fails. In that case, stale TLB entries are immediately
4405 for (; sva < eva; sva = va_next) {
4407 pml4e = pmap_pml4e(pmap, sva);
4408 if ((*pml4e & PG_V) == 0) {
4409 va_next = (sva + NBPML4) & ~PML4MASK;
4415 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4416 if ((*pdpe & PG_V) == 0) {
4417 va_next = (sva + NBPDP) & ~PDPMASK;
4423 va_next = (sva + NBPDR) & ~PDRMASK;
4427 pde = pmap_pdpe_to_pde(pdpe, sva);
4431 * Weed out invalid mappings.
4437 * Check for large page.
4439 if ((ptpaddr & PG_PS) != 0) {
4441 * Are we protecting the entire large page? If not,
4442 * demote the mapping and fall through.
4444 if (sva + NBPDR == va_next && eva >= va_next) {
4446 * The TLB entry for a PG_G mapping is
4447 * invalidated by pmap_protect_pde().
4449 if (pmap_protect_pde(pmap, pde, sva, prot))
4452 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4454 * The large page mapping was destroyed.
4463 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4465 pt_entry_t obits, pbits;
4469 obits = pbits = *pte;
4470 if ((pbits & PG_V) == 0)
4473 if ((prot & VM_PROT_WRITE) == 0) {
4474 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4475 (PG_MANAGED | PG_M | PG_RW)) {
4476 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4479 pbits &= ~(PG_RW | PG_M);
4481 if ((prot & VM_PROT_EXECUTE) == 0)
4484 if (pbits != obits) {
4485 if (!atomic_cmpset_long(pte, obits, pbits))
4488 pmap_invalidate_page(pmap, sva);
4495 pmap_invalidate_all(pmap);
4499 #if VM_NRESERVLEVEL > 0
4501 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4502 * single page table page (PTP) to a single 2MB page mapping. For promotion
4503 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4504 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4505 * identical characteristics.
4508 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4509 struct rwlock **lockp)
4512 pt_entry_t *firstpte, oldpte, pa, *pte;
4513 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4517 PG_A = pmap_accessed_bit(pmap);
4518 PG_G = pmap_global_bit(pmap);
4519 PG_M = pmap_modified_bit(pmap);
4520 PG_V = pmap_valid_bit(pmap);
4521 PG_RW = pmap_rw_bit(pmap);
4522 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4524 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4527 * Examine the first PTE in the specified PTP. Abort if this PTE is
4528 * either invalid, unused, or does not map the first 4KB physical page
4529 * within a 2MB page.
4531 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4534 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4535 atomic_add_long(&pmap_pde_p_failures, 1);
4536 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4537 " in pmap %p", va, pmap);
4540 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4542 * When PG_M is already clear, PG_RW can be cleared without
4543 * a TLB invalidation.
4545 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4551 * Examine each of the other PTEs in the specified PTP. Abort if this
4552 * PTE maps an unexpected 4KB physical page or does not have identical
4553 * characteristics to the first PTE.
4555 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4556 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4559 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4560 atomic_add_long(&pmap_pde_p_failures, 1);
4561 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4562 " in pmap %p", va, pmap);
4565 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4567 * When PG_M is already clear, PG_RW can be cleared
4568 * without a TLB invalidation.
4570 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4573 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4574 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4575 (va & ~PDRMASK), pmap);
4577 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4578 atomic_add_long(&pmap_pde_p_failures, 1);
4579 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4580 " in pmap %p", va, pmap);
4587 * Save the page table page in its current state until the PDE
4588 * mapping the superpage is demoted by pmap_demote_pde() or
4589 * destroyed by pmap_remove_pde().
4591 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4592 KASSERT(mpte >= vm_page_array &&
4593 mpte < &vm_page_array[vm_page_array_size],
4594 ("pmap_promote_pde: page table page is out of range"));
4595 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4596 ("pmap_promote_pde: page table page's pindex is wrong"));
4597 if (pmap_insert_pt_page(pmap, mpte)) {
4598 atomic_add_long(&pmap_pde_p_failures, 1);
4600 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4606 * Promote the pv entries.
4608 if ((newpde & PG_MANAGED) != 0)
4609 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4612 * Propagate the PAT index to its proper position.
4614 newpde = pmap_swap_pat(pmap, newpde);
4617 * Map the superpage.
4619 if (workaround_erratum383)
4620 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4622 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
4624 atomic_add_long(&pmap_pde_promotions, 1);
4625 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4626 " in pmap %p", va, pmap);
4628 #endif /* VM_NRESERVLEVEL > 0 */
4631 * Insert the given physical page (p) at
4632 * the specified virtual address (v) in the
4633 * target physical map with the protection requested.
4635 * If specified, the page will be wired down, meaning
4636 * that the related pte can not be reclaimed.
4638 * NB: This is the only routine which MAY NOT lazy-evaluate
4639 * or lose information. That is, this routine must actually
4640 * insert this page into the given map NOW.
4642 * When destroying both a page table and PV entry, this function
4643 * performs the TLB invalidation before releasing the PV list
4644 * lock, so we do not need pmap_delayed_invl_page() calls here.
4647 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4648 u_int flags, int8_t psind)
4650 struct rwlock *lock;
4652 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4653 pt_entry_t newpte, origpte;
4660 PG_A = pmap_accessed_bit(pmap);
4661 PG_G = pmap_global_bit(pmap);
4662 PG_M = pmap_modified_bit(pmap);
4663 PG_V = pmap_valid_bit(pmap);
4664 PG_RW = pmap_rw_bit(pmap);
4666 va = trunc_page(va);
4667 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4668 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4669 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4671 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4672 va >= kmi.clean_eva,
4673 ("pmap_enter: managed mapping within the clean submap"));
4674 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4675 VM_OBJECT_ASSERT_LOCKED(m->object);
4676 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
4677 ("pmap_enter: flags %u has reserved bits set", flags));
4678 pa = VM_PAGE_TO_PHYS(m);
4679 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4680 if ((flags & VM_PROT_WRITE) != 0)
4682 if ((prot & VM_PROT_WRITE) != 0)
4684 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4685 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4686 if ((prot & VM_PROT_EXECUTE) == 0)
4688 if ((flags & PMAP_ENTER_WIRED) != 0)
4690 if (va < VM_MAXUSER_ADDRESS)
4692 if (pmap == kernel_pmap)
4694 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
4697 * Set modified bit gratuitously for writeable mappings if
4698 * the page is unmanaged. We do not want to take a fault
4699 * to do the dirty bit accounting for these mappings.
4701 if ((m->oflags & VPO_UNMANAGED) != 0) {
4702 if ((newpte & PG_RW) != 0)
4705 newpte |= PG_MANAGED;
4710 /* Assert the required virtual and physical alignment. */
4711 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
4712 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4713 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
4719 * In the case that a page table page is not
4720 * resident, we are creating it here.
4723 pde = pmap_pde(pmap, va);
4724 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4725 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4726 pte = pmap_pde_to_pte(pde, va);
4727 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4728 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4731 } else if (va < VM_MAXUSER_ADDRESS) {
4733 * Here if the pte page isn't mapped, or if it has been
4736 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4737 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4738 nosleep ? NULL : &lock);
4739 if (mpte == NULL && nosleep) {
4740 rv = KERN_RESOURCE_SHORTAGE;
4745 panic("pmap_enter: invalid page directory va=%#lx", va);
4750 * Is the specified virtual address already mapped?
4752 if ((origpte & PG_V) != 0) {
4754 * Wiring change, just update stats. We don't worry about
4755 * wiring PT pages as they remain resident as long as there
4756 * are valid mappings in them. Hence, if a user page is wired,
4757 * the PT page will be also.
4759 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4760 pmap->pm_stats.wired_count++;
4761 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4762 pmap->pm_stats.wired_count--;
4765 * Remove the extra PT page reference.
4769 KASSERT(mpte->wire_count > 0,
4770 ("pmap_enter: missing reference to page table page,"
4775 * Has the physical page changed?
4777 opa = origpte & PG_FRAME;
4780 * No, might be a protection or wiring change.
4782 if ((origpte & PG_MANAGED) != 0 &&
4783 (newpte & PG_RW) != 0)
4784 vm_page_aflag_set(m, PGA_WRITEABLE);
4785 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4791 * Increment the counters.
4793 if ((newpte & PG_W) != 0)
4794 pmap->pm_stats.wired_count++;
4795 pmap_resident_count_inc(pmap, 1);
4799 * Enter on the PV list if part of our managed memory.
4801 if ((newpte & PG_MANAGED) != 0) {
4802 pv = get_pv_entry(pmap, &lock);
4804 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4805 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4807 if ((newpte & PG_RW) != 0)
4808 vm_page_aflag_set(m, PGA_WRITEABLE);
4814 if ((origpte & PG_V) != 0) {
4816 origpte = pte_load_store(pte, newpte);
4817 opa = origpte & PG_FRAME;
4819 if ((origpte & PG_MANAGED) != 0) {
4820 om = PHYS_TO_VM_PAGE(opa);
4821 if ((origpte & (PG_M | PG_RW)) == (PG_M |
4824 if ((origpte & PG_A) != 0)
4825 vm_page_aflag_set(om, PGA_REFERENCED);
4826 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4827 pmap_pvh_free(&om->md, pmap, va);
4828 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4829 TAILQ_EMPTY(&om->md.pv_list) &&
4830 ((om->flags & PG_FICTITIOUS) != 0 ||
4831 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4832 vm_page_aflag_clear(om, PGA_WRITEABLE);
4834 } else if ((newpte & PG_M) == 0 && (origpte & (PG_M |
4835 PG_RW)) == (PG_M | PG_RW)) {
4836 if ((origpte & PG_MANAGED) != 0)
4840 * Although the PTE may still have PG_RW set, TLB
4841 * invalidation may nonetheless be required because
4842 * the PTE no longer has PG_M set.
4844 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4846 * This PTE change does not require TLB invalidation.
4850 if ((origpte & PG_A) != 0)
4851 pmap_invalidate_page(pmap, va);
4853 pte_store(pte, newpte);
4857 #if VM_NRESERVLEVEL > 0
4859 * If both the page table page and the reservation are fully
4860 * populated, then attempt promotion.
4862 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4863 pmap_ps_enabled(pmap) &&
4864 (m->flags & PG_FICTITIOUS) == 0 &&
4865 vm_reserv_level_iffullpop(m) == 0)
4866 pmap_promote_pde(pmap, pde, va, &lock);
4878 * Tries to create a read- and/or execute-only 2MB page mapping. Returns true
4879 * if successful. Returns false if (1) a page table page cannot be allocated
4880 * without sleeping, (2) a mapping already exists at the specified virtual
4881 * address, or (3) a PV entry cannot be allocated without reclaiming another
4885 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4886 struct rwlock **lockp)
4891 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4892 PG_V = pmap_valid_bit(pmap);
4893 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
4895 if ((m->oflags & VPO_UNMANAGED) == 0)
4896 newpde |= PG_MANAGED;
4897 if ((prot & VM_PROT_EXECUTE) == 0)
4899 if (va < VM_MAXUSER_ADDRESS)
4901 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
4902 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
4907 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
4908 * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
4909 * otherwise. Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
4910 * a mapping already exists at the specified virtual address. Returns
4911 * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
4912 * page allocation failed. Returns KERN_RESOURCE_SHORTAGE if
4913 * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
4915 * The parameter "m" is only used when creating a managed, writeable mapping.
4918 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
4919 vm_page_t m, struct rwlock **lockp)
4921 struct spglist free;
4922 pd_entry_t oldpde, *pde;
4923 pt_entry_t PG_G, PG_RW, PG_V;
4926 PG_G = pmap_global_bit(pmap);
4927 PG_RW = pmap_rw_bit(pmap);
4928 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
4929 ("pmap_enter_pde: newpde is missing PG_M"));
4930 PG_V = pmap_valid_bit(pmap);
4931 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4933 if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
4934 NULL : lockp)) == NULL) {
4935 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4936 " in pmap %p", va, pmap);
4937 return (KERN_RESOURCE_SHORTAGE);
4939 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4940 pde = &pde[pmap_pde_index(va)];
4942 if ((oldpde & PG_V) != 0) {
4943 KASSERT(pdpg->wire_count > 1,
4944 ("pmap_enter_pde: pdpg's wire count is too low"));
4945 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
4947 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4948 " in pmap %p", va, pmap);
4949 return (KERN_FAILURE);
4951 /* Break the existing mapping(s). */
4953 if ((oldpde & PG_PS) != 0) {
4955 * The reference to the PD page that was acquired by
4956 * pmap_allocpde() ensures that it won't be freed.
4957 * However, if the PDE resulted from a promotion, then
4958 * a reserved PT page could be freed.
4960 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
4961 if ((oldpde & PG_G) == 0)
4962 pmap_invalidate_pde_page(pmap, va, oldpde);
4964 pmap_delayed_invl_started();
4965 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
4967 pmap_invalidate_all(pmap);
4968 pmap_delayed_invl_finished();
4970 pmap_free_zero_pages(&free);
4971 if (va >= VM_MAXUSER_ADDRESS) {
4972 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4973 if (pmap_insert_pt_page(pmap, mt)) {
4975 * XXX Currently, this can't happen because
4976 * we do not perform pmap_enter(psind == 1)
4977 * on the kernel pmap.
4979 panic("pmap_enter_pde: trie insert failed");
4982 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
4985 if ((newpde & PG_MANAGED) != 0) {
4987 * Abort this mapping if its PV entry could not be created.
4989 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
4991 if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
4993 * Although "va" is not mapped, paging-
4994 * structure caches could nonetheless have
4995 * entries that refer to the freed page table
4996 * pages. Invalidate those entries.
4998 pmap_invalidate_page(pmap, va);
4999 pmap_free_zero_pages(&free);
5001 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5002 " in pmap %p", va, pmap);
5003 return (KERN_RESOURCE_SHORTAGE);
5005 if ((newpde & PG_RW) != 0) {
5006 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5007 vm_page_aflag_set(mt, PGA_WRITEABLE);
5012 * Increment counters.
5014 if ((newpde & PG_W) != 0)
5015 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
5016 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5019 * Map the superpage. (This is not a promoted mapping; there will not
5020 * be any lingering 4KB page mappings in the TLB.)
5022 pde_store(pde, newpde);
5024 atomic_add_long(&pmap_pde_mappings, 1);
5025 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
5026 " in pmap %p", va, pmap);
5027 return (KERN_SUCCESS);
5031 * Maps a sequence of resident pages belonging to the same object.
5032 * The sequence begins with the given page m_start. This page is
5033 * mapped at the given virtual address start. Each subsequent page is
5034 * mapped at a virtual address that is offset from start by the same
5035 * amount as the page is offset from m_start within the object. The
5036 * last page in the sequence is the page with the largest offset from
5037 * m_start that can be mapped at a virtual address less than the given
5038 * virtual address end. Not every virtual page between start and end
5039 * is mapped; only those for which a resident page exists with the
5040 * corresponding offset from m_start are mapped.
5043 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
5044 vm_page_t m_start, vm_prot_t prot)
5046 struct rwlock *lock;
5049 vm_pindex_t diff, psize;
5051 VM_OBJECT_ASSERT_LOCKED(m_start->object);
5053 psize = atop(end - start);
5058 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
5059 va = start + ptoa(diff);
5060 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
5061 m->psind == 1 && pmap_ps_enabled(pmap) &&
5062 pmap_enter_2mpage(pmap, va, m, prot, &lock))
5063 m = &m[NBPDR / PAGE_SIZE - 1];
5065 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
5067 m = TAILQ_NEXT(m, listq);
5075 * this code makes some *MAJOR* assumptions:
5076 * 1. Current pmap & pmap exists.
5079 * 4. No page table pages.
5080 * but is *MUCH* faster than pmap_enter...
5084 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
5086 struct rwlock *lock;
5090 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
5097 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
5098 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
5100 struct spglist free;
5101 pt_entry_t *pte, PG_V;
5104 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
5105 (m->oflags & VPO_UNMANAGED) != 0,
5106 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
5107 PG_V = pmap_valid_bit(pmap);
5108 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5111 * In the case that a page table page is not
5112 * resident, we are creating it here.
5114 if (va < VM_MAXUSER_ADDRESS) {
5115 vm_pindex_t ptepindex;
5119 * Calculate pagetable page index
5121 ptepindex = pmap_pde_pindex(va);
5122 if (mpte && (mpte->pindex == ptepindex)) {
5126 * Get the page directory entry
5128 ptepa = pmap_pde(pmap, va);
5131 * If the page table page is mapped, we just increment
5132 * the hold count, and activate it. Otherwise, we
5133 * attempt to allocate a page table page. If this
5134 * attempt fails, we don't retry. Instead, we give up.
5136 if (ptepa && (*ptepa & PG_V) != 0) {
5139 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
5143 * Pass NULL instead of the PV list lock
5144 * pointer, because we don't intend to sleep.
5146 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
5151 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
5152 pte = &pte[pmap_pte_index(va)];
5166 * Enter on the PV list if part of our managed memory.
5168 if ((m->oflags & VPO_UNMANAGED) == 0 &&
5169 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
5172 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
5174 * Although "va" is not mapped, paging-
5175 * structure caches could nonetheless have
5176 * entries that refer to the freed page table
5177 * pages. Invalidate those entries.
5179 pmap_invalidate_page(pmap, va);
5180 pmap_free_zero_pages(&free);
5188 * Increment counters
5190 pmap_resident_count_inc(pmap, 1);
5192 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
5193 if ((prot & VM_PROT_EXECUTE) == 0)
5197 * Now validate mapping with RO protection
5199 if ((m->oflags & VPO_UNMANAGED) != 0)
5200 pte_store(pte, pa | PG_V | PG_U);
5202 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
5207 * Make a temporary mapping for a physical address. This is only intended
5208 * to be used for panic dumps.
5211 pmap_kenter_temporary(vm_paddr_t pa, int i)
5215 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
5216 pmap_kenter(va, pa);
5218 return ((void *)crashdumpmap);
5222 * This code maps large physical mmap regions into the
5223 * processor address space. Note that some shortcuts
5224 * are taken, but the code works.
5227 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
5228 vm_pindex_t pindex, vm_size_t size)
5231 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5232 vm_paddr_t pa, ptepa;
5236 PG_A = pmap_accessed_bit(pmap);
5237 PG_M = pmap_modified_bit(pmap);
5238 PG_V = pmap_valid_bit(pmap);
5239 PG_RW = pmap_rw_bit(pmap);
5241 VM_OBJECT_ASSERT_WLOCKED(object);
5242 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
5243 ("pmap_object_init_pt: non-device object"));
5244 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
5245 if (!pmap_ps_enabled(pmap))
5247 if (!vm_object_populate(object, pindex, pindex + atop(size)))
5249 p = vm_page_lookup(object, pindex);
5250 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5251 ("pmap_object_init_pt: invalid page %p", p));
5252 pat_mode = p->md.pat_mode;
5255 * Abort the mapping if the first page is not physically
5256 * aligned to a 2MB page boundary.
5258 ptepa = VM_PAGE_TO_PHYS(p);
5259 if (ptepa & (NBPDR - 1))
5263 * Skip the first page. Abort the mapping if the rest of
5264 * the pages are not physically contiguous or have differing
5265 * memory attributes.
5267 p = TAILQ_NEXT(p, listq);
5268 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
5270 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5271 ("pmap_object_init_pt: invalid page %p", p));
5272 if (pa != VM_PAGE_TO_PHYS(p) ||
5273 pat_mode != p->md.pat_mode)
5275 p = TAILQ_NEXT(p, listq);
5279 * Map using 2MB pages. Since "ptepa" is 2M aligned and
5280 * "size" is a multiple of 2M, adding the PAT setting to "pa"
5281 * will not affect the termination of this loop.
5284 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
5285 pa < ptepa + size; pa += NBPDR) {
5286 pdpg = pmap_allocpde(pmap, addr, NULL);
5289 * The creation of mappings below is only an
5290 * optimization. If a page directory page
5291 * cannot be allocated without blocking,
5292 * continue on to the next mapping rather than
5298 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5299 pde = &pde[pmap_pde_index(addr)];
5300 if ((*pde & PG_V) == 0) {
5301 pde_store(pde, pa | PG_PS | PG_M | PG_A |
5302 PG_U | PG_RW | PG_V);
5303 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5304 atomic_add_long(&pmap_pde_mappings, 1);
5306 /* Continue on if the PDE is already valid. */
5308 KASSERT(pdpg->wire_count > 0,
5309 ("pmap_object_init_pt: missing reference "
5310 "to page directory page, va: 0x%lx", addr));
5319 * Clear the wired attribute from the mappings for the specified range of
5320 * addresses in the given pmap. Every valid mapping within that range
5321 * must have the wired attribute set. In contrast, invalid mappings
5322 * cannot have the wired attribute set, so they are ignored.
5324 * The wired attribute of the page table entry is not a hardware
5325 * feature, so there is no need to invalidate any TLB entries.
5326 * Since pmap_demote_pde() for the wired entry must never fail,
5327 * pmap_delayed_invl_started()/finished() calls around the
5328 * function are not needed.
5331 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5333 vm_offset_t va_next;
5334 pml4_entry_t *pml4e;
5337 pt_entry_t *pte, PG_V;
5339 PG_V = pmap_valid_bit(pmap);
5341 for (; sva < eva; sva = va_next) {
5342 pml4e = pmap_pml4e(pmap, sva);
5343 if ((*pml4e & PG_V) == 0) {
5344 va_next = (sva + NBPML4) & ~PML4MASK;
5349 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5350 if ((*pdpe & PG_V) == 0) {
5351 va_next = (sva + NBPDP) & ~PDPMASK;
5356 va_next = (sva + NBPDR) & ~PDRMASK;
5359 pde = pmap_pdpe_to_pde(pdpe, sva);
5360 if ((*pde & PG_V) == 0)
5362 if ((*pde & PG_PS) != 0) {
5363 if ((*pde & PG_W) == 0)
5364 panic("pmap_unwire: pde %#jx is missing PG_W",
5368 * Are we unwiring the entire large page? If not,
5369 * demote the mapping and fall through.
5371 if (sva + NBPDR == va_next && eva >= va_next) {
5372 atomic_clear_long(pde, PG_W);
5373 pmap->pm_stats.wired_count -= NBPDR /
5376 } else if (!pmap_demote_pde(pmap, pde, sva))
5377 panic("pmap_unwire: demotion failed");
5381 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
5383 if ((*pte & PG_V) == 0)
5385 if ((*pte & PG_W) == 0)
5386 panic("pmap_unwire: pte %#jx is missing PG_W",
5390 * PG_W must be cleared atomically. Although the pmap
5391 * lock synchronizes access to PG_W, another processor
5392 * could be setting PG_M and/or PG_A concurrently.
5394 atomic_clear_long(pte, PG_W);
5395 pmap->pm_stats.wired_count--;
5402 * Copy the range specified by src_addr/len
5403 * from the source map to the range dst_addr/len
5404 * in the destination map.
5406 * This routine is only advisory and need not do anything.
5410 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5411 vm_offset_t src_addr)
5413 struct rwlock *lock;
5414 struct spglist free;
5416 vm_offset_t end_addr = src_addr + len;
5417 vm_offset_t va_next;
5418 vm_page_t dst_pdpg, dstmpte, srcmpte;
5419 pt_entry_t PG_A, PG_M, PG_V;
5421 if (dst_addr != src_addr)
5424 if (dst_pmap->pm_type != src_pmap->pm_type)
5428 * EPT page table entries that require emulation of A/D bits are
5429 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5430 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5431 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5432 * implementations flag an EPT misconfiguration for exec-only
5433 * mappings we skip this function entirely for emulated pmaps.
5435 if (pmap_emulate_ad_bits(dst_pmap))
5439 if (dst_pmap < src_pmap) {
5440 PMAP_LOCK(dst_pmap);
5441 PMAP_LOCK(src_pmap);
5443 PMAP_LOCK(src_pmap);
5444 PMAP_LOCK(dst_pmap);
5447 PG_A = pmap_accessed_bit(dst_pmap);
5448 PG_M = pmap_modified_bit(dst_pmap);
5449 PG_V = pmap_valid_bit(dst_pmap);
5451 for (addr = src_addr; addr < end_addr; addr = va_next) {
5452 pt_entry_t *src_pte, *dst_pte;
5453 pml4_entry_t *pml4e;
5455 pd_entry_t srcptepaddr, *pde;
5457 KASSERT(addr < UPT_MIN_ADDRESS,
5458 ("pmap_copy: invalid to pmap_copy page tables"));
5460 pml4e = pmap_pml4e(src_pmap, addr);
5461 if ((*pml4e & PG_V) == 0) {
5462 va_next = (addr + NBPML4) & ~PML4MASK;
5468 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5469 if ((*pdpe & PG_V) == 0) {
5470 va_next = (addr + NBPDP) & ~PDPMASK;
5476 va_next = (addr + NBPDR) & ~PDRMASK;
5480 pde = pmap_pdpe_to_pde(pdpe, addr);
5482 if (srcptepaddr == 0)
5485 if (srcptepaddr & PG_PS) {
5486 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5488 dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
5489 if (dst_pdpg == NULL)
5491 pde = (pd_entry_t *)
5492 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
5493 pde = &pde[pmap_pde_index(addr)];
5494 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5495 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
5496 PMAP_ENTER_NORECLAIM, &lock))) {
5497 *pde = srcptepaddr & ~PG_W;
5498 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5499 atomic_add_long(&pmap_pde_mappings, 1);
5501 dst_pdpg->wire_count--;
5505 srcptepaddr &= PG_FRAME;
5506 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5507 KASSERT(srcmpte->wire_count > 0,
5508 ("pmap_copy: source page table page is unused"));
5510 if (va_next > end_addr)
5513 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5514 src_pte = &src_pte[pmap_pte_index(addr)];
5516 while (addr < va_next) {
5520 * we only virtual copy managed pages
5522 if ((ptetemp & PG_MANAGED) != 0) {
5523 if (dstmpte != NULL &&
5524 dstmpte->pindex == pmap_pde_pindex(addr))
5525 dstmpte->wire_count++;
5526 else if ((dstmpte = pmap_allocpte(dst_pmap,
5527 addr, NULL)) == NULL)
5529 dst_pte = (pt_entry_t *)
5530 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5531 dst_pte = &dst_pte[pmap_pte_index(addr)];
5532 if (*dst_pte == 0 &&
5533 pmap_try_insert_pv_entry(dst_pmap, addr,
5534 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5537 * Clear the wired, modified, and
5538 * accessed (referenced) bits
5541 *dst_pte = ptetemp & ~(PG_W | PG_M |
5543 pmap_resident_count_inc(dst_pmap, 1);
5546 if (pmap_unwire_ptp(dst_pmap, addr,
5549 * Although "addr" is not
5550 * mapped, paging-structure
5551 * caches could nonetheless
5552 * have entries that refer to
5553 * the freed page table pages.
5554 * Invalidate those entries.
5556 pmap_invalidate_page(dst_pmap,
5558 pmap_free_zero_pages(&free);
5562 if (dstmpte->wire_count >= srcmpte->wire_count)
5572 PMAP_UNLOCK(src_pmap);
5573 PMAP_UNLOCK(dst_pmap);
5577 * pmap_zero_page zeros the specified hardware page by mapping
5578 * the page into KVM and using bzero to clear its contents.
5581 pmap_zero_page(vm_page_t m)
5583 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5585 pagezero((void *)va);
5589 * pmap_zero_page_area zeros the specified hardware page by mapping
5590 * the page into KVM and using bzero to clear its contents.
5592 * off and size may not cover an area beyond a single hardware page.
5595 pmap_zero_page_area(vm_page_t m, int off, int size)
5597 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5599 if (off == 0 && size == PAGE_SIZE)
5600 pagezero((void *)va);
5602 bzero((char *)va + off, size);
5606 * pmap_zero_page_idle zeros the specified hardware page by mapping
5607 * the page into KVM and using bzero to clear its contents. This
5608 * is intended to be called from the vm_pagezero process only and
5612 pmap_zero_page_idle(vm_page_t m)
5614 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5616 pagezero((void *)va);
5620 * pmap_copy_page copies the specified (machine independent)
5621 * page by mapping the page into virtual memory and using
5622 * bcopy to copy the page, one machine dependent page at a
5626 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5628 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5629 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5631 pagecopy((void *)src, (void *)dst);
5634 int unmapped_buf_allowed = 1;
5637 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5638 vm_offset_t b_offset, int xfersize)
5642 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5646 while (xfersize > 0) {
5647 a_pg_offset = a_offset & PAGE_MASK;
5648 pages[0] = ma[a_offset >> PAGE_SHIFT];
5649 b_pg_offset = b_offset & PAGE_MASK;
5650 pages[1] = mb[b_offset >> PAGE_SHIFT];
5651 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5652 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5653 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5654 a_cp = (char *)vaddr[0] + a_pg_offset;
5655 b_cp = (char *)vaddr[1] + b_pg_offset;
5656 bcopy(a_cp, b_cp, cnt);
5657 if (__predict_false(mapped))
5658 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5666 * Returns true if the pmap's pv is one of the first
5667 * 16 pvs linked to from this page. This count may
5668 * be changed upwards or downwards in the future; it
5669 * is only necessary that true be returned for a small
5670 * subset of pmaps for proper page aging.
5673 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5675 struct md_page *pvh;
5676 struct rwlock *lock;
5681 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5682 ("pmap_page_exists_quick: page %p is not managed", m));
5684 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5686 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5687 if (PV_PMAP(pv) == pmap) {
5695 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5696 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5697 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5698 if (PV_PMAP(pv) == pmap) {
5712 * pmap_page_wired_mappings:
5714 * Return the number of managed mappings to the given physical page
5718 pmap_page_wired_mappings(vm_page_t m)
5720 struct rwlock *lock;
5721 struct md_page *pvh;
5725 int count, md_gen, pvh_gen;
5727 if ((m->oflags & VPO_UNMANAGED) != 0)
5729 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5733 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5735 if (!PMAP_TRYLOCK(pmap)) {
5736 md_gen = m->md.pv_gen;
5740 if (md_gen != m->md.pv_gen) {
5745 pte = pmap_pte(pmap, pv->pv_va);
5746 if ((*pte & PG_W) != 0)
5750 if ((m->flags & PG_FICTITIOUS) == 0) {
5751 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5752 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5754 if (!PMAP_TRYLOCK(pmap)) {
5755 md_gen = m->md.pv_gen;
5756 pvh_gen = pvh->pv_gen;
5760 if (md_gen != m->md.pv_gen ||
5761 pvh_gen != pvh->pv_gen) {
5766 pte = pmap_pde(pmap, pv->pv_va);
5767 if ((*pte & PG_W) != 0)
5777 * Returns TRUE if the given page is mapped individually or as part of
5778 * a 2mpage. Otherwise, returns FALSE.
5781 pmap_page_is_mapped(vm_page_t m)
5783 struct rwlock *lock;
5786 if ((m->oflags & VPO_UNMANAGED) != 0)
5788 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5790 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5791 ((m->flags & PG_FICTITIOUS) == 0 &&
5792 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5798 * Destroy all managed, non-wired mappings in the given user-space
5799 * pmap. This pmap cannot be active on any processor besides the
5802 * This function cannot be applied to the kernel pmap. Moreover, it
5803 * is not intended for general use. It is only to be used during
5804 * process termination. Consequently, it can be implemented in ways
5805 * that make it faster than pmap_remove(). First, it can more quickly
5806 * destroy mappings by iterating over the pmap's collection of PV
5807 * entries, rather than searching the page table. Second, it doesn't
5808 * have to test and clear the page table entries atomically, because
5809 * no processor is currently accessing the user address space. In
5810 * particular, a page table entry's dirty bit won't change state once
5811 * this function starts.
5813 * Although this function destroys all of the pmap's managed,
5814 * non-wired mappings, it can delay and batch the invalidation of TLB
5815 * entries without calling pmap_delayed_invl_started() and
5816 * pmap_delayed_invl_finished(). Because the pmap is not active on
5817 * any other processor, none of these TLB entries will ever be used
5818 * before their eventual invalidation. Consequently, there is no need
5819 * for either pmap_remove_all() or pmap_remove_write() to wait for
5820 * that eventual TLB invalidation.
5823 pmap_remove_pages(pmap_t pmap)
5826 pt_entry_t *pte, tpte;
5827 pt_entry_t PG_M, PG_RW, PG_V;
5828 struct spglist free;
5829 vm_page_t m, mpte, mt;
5831 struct md_page *pvh;
5832 struct pv_chunk *pc, *npc;
5833 struct rwlock *lock;
5835 uint64_t inuse, bitmask;
5836 int allfree, field, freed, idx;
5837 boolean_t superpage;
5841 * Assert that the given pmap is only active on the current
5842 * CPU. Unfortunately, we cannot block another CPU from
5843 * activating the pmap while this function is executing.
5845 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5848 cpuset_t other_cpus;
5850 other_cpus = all_cpus;
5852 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5853 CPU_AND(&other_cpus, &pmap->pm_active);
5855 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5860 PG_M = pmap_modified_bit(pmap);
5861 PG_V = pmap_valid_bit(pmap);
5862 PG_RW = pmap_rw_bit(pmap);
5866 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5869 for (field = 0; field < _NPCM; field++) {
5870 inuse = ~pc->pc_map[field] & pc_freemask[field];
5871 while (inuse != 0) {
5873 bitmask = 1UL << bit;
5874 idx = field * 64 + bit;
5875 pv = &pc->pc_pventry[idx];
5878 pte = pmap_pdpe(pmap, pv->pv_va);
5880 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5882 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5885 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5887 pte = &pte[pmap_pte_index(pv->pv_va)];
5891 * Keep track whether 'tpte' is a
5892 * superpage explicitly instead of
5893 * relying on PG_PS being set.
5895 * This is because PG_PS is numerically
5896 * identical to PG_PTE_PAT and thus a
5897 * regular page could be mistaken for
5903 if ((tpte & PG_V) == 0) {
5904 panic("bad pte va %lx pte %lx",
5909 * We cannot remove wired pages from a process' mapping at this time
5917 pa = tpte & PG_PS_FRAME;
5919 pa = tpte & PG_FRAME;
5921 m = PHYS_TO_VM_PAGE(pa);
5922 KASSERT(m->phys_addr == pa,
5923 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5924 m, (uintmax_t)m->phys_addr,
5927 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5928 m < &vm_page_array[vm_page_array_size],
5929 ("pmap_remove_pages: bad tpte %#jx",
5935 * Update the vm_page_t clean/reference bits.
5937 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5939 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5945 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5948 pc->pc_map[field] |= bitmask;
5950 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
5951 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
5952 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5954 if (TAILQ_EMPTY(&pvh->pv_list)) {
5955 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5956 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
5957 TAILQ_EMPTY(&mt->md.pv_list))
5958 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5960 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
5962 pmap_resident_count_dec(pmap, 1);
5963 KASSERT(mpte->wire_count == NPTEPG,
5964 ("pmap_remove_pages: pte page wire count error"));
5965 mpte->wire_count = 0;
5966 pmap_add_delayed_free_list(mpte, &free, FALSE);
5969 pmap_resident_count_dec(pmap, 1);
5970 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5972 if ((m->aflags & PGA_WRITEABLE) != 0 &&
5973 TAILQ_EMPTY(&m->md.pv_list) &&
5974 (m->flags & PG_FICTITIOUS) == 0) {
5975 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5976 if (TAILQ_EMPTY(&pvh->pv_list))
5977 vm_page_aflag_clear(m, PGA_WRITEABLE);
5980 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
5984 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5985 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5986 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5988 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5994 pmap_invalidate_all(pmap);
5996 pmap_free_zero_pages(&free);
6000 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
6002 struct rwlock *lock;
6004 struct md_page *pvh;
6005 pt_entry_t *pte, mask;
6006 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6008 int md_gen, pvh_gen;
6012 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6015 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6017 if (!PMAP_TRYLOCK(pmap)) {
6018 md_gen = m->md.pv_gen;
6022 if (md_gen != m->md.pv_gen) {
6027 pte = pmap_pte(pmap, pv->pv_va);
6030 PG_M = pmap_modified_bit(pmap);
6031 PG_RW = pmap_rw_bit(pmap);
6032 mask |= PG_RW | PG_M;
6035 PG_A = pmap_accessed_bit(pmap);
6036 PG_V = pmap_valid_bit(pmap);
6037 mask |= PG_V | PG_A;
6039 rv = (*pte & mask) == mask;
6044 if ((m->flags & PG_FICTITIOUS) == 0) {
6045 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6046 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
6048 if (!PMAP_TRYLOCK(pmap)) {
6049 md_gen = m->md.pv_gen;
6050 pvh_gen = pvh->pv_gen;
6054 if (md_gen != m->md.pv_gen ||
6055 pvh_gen != pvh->pv_gen) {
6060 pte = pmap_pde(pmap, pv->pv_va);
6063 PG_M = pmap_modified_bit(pmap);
6064 PG_RW = pmap_rw_bit(pmap);
6065 mask |= PG_RW | PG_M;
6068 PG_A = pmap_accessed_bit(pmap);
6069 PG_V = pmap_valid_bit(pmap);
6070 mask |= PG_V | PG_A;
6072 rv = (*pte & mask) == mask;
6086 * Return whether or not the specified physical page was modified
6087 * in any physical maps.
6090 pmap_is_modified(vm_page_t m)
6093 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6094 ("pmap_is_modified: page %p is not managed", m));
6097 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6098 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
6099 * is clear, no PTEs can have PG_M set.
6101 VM_OBJECT_ASSERT_WLOCKED(m->object);
6102 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6104 return (pmap_page_test_mappings(m, FALSE, TRUE));
6108 * pmap_is_prefaultable:
6110 * Return whether or not the specified virtual address is eligible
6114 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
6117 pt_entry_t *pte, PG_V;
6120 PG_V = pmap_valid_bit(pmap);
6123 pde = pmap_pde(pmap, addr);
6124 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
6125 pte = pmap_pde_to_pte(pde, addr);
6126 rv = (*pte & PG_V) == 0;
6133 * pmap_is_referenced:
6135 * Return whether or not the specified physical page was referenced
6136 * in any physical maps.
6139 pmap_is_referenced(vm_page_t m)
6142 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6143 ("pmap_is_referenced: page %p is not managed", m));
6144 return (pmap_page_test_mappings(m, TRUE, FALSE));
6148 * Clear the write and modified bits in each of the given page's mappings.
6151 pmap_remove_write(vm_page_t m)
6153 struct md_page *pvh;
6155 struct rwlock *lock;
6156 pv_entry_t next_pv, pv;
6158 pt_entry_t oldpte, *pte, PG_M, PG_RW;
6160 int pvh_gen, md_gen;
6162 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6163 ("pmap_remove_write: page %p is not managed", m));
6166 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6167 * set by another thread while the object is locked. Thus,
6168 * if PGA_WRITEABLE is clear, no page table entries need updating.
6170 VM_OBJECT_ASSERT_WLOCKED(m->object);
6171 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6173 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6174 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6175 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6178 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6180 if (!PMAP_TRYLOCK(pmap)) {
6181 pvh_gen = pvh->pv_gen;
6185 if (pvh_gen != pvh->pv_gen) {
6191 PG_RW = pmap_rw_bit(pmap);
6193 pde = pmap_pde(pmap, va);
6194 if ((*pde & PG_RW) != 0)
6195 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6196 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6197 ("inconsistent pv lock %p %p for page %p",
6198 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6201 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6203 if (!PMAP_TRYLOCK(pmap)) {
6204 pvh_gen = pvh->pv_gen;
6205 md_gen = m->md.pv_gen;
6209 if (pvh_gen != pvh->pv_gen ||
6210 md_gen != m->md.pv_gen) {
6216 PG_M = pmap_modified_bit(pmap);
6217 PG_RW = pmap_rw_bit(pmap);
6218 pde = pmap_pde(pmap, pv->pv_va);
6219 KASSERT((*pde & PG_PS) == 0,
6220 ("pmap_remove_write: found a 2mpage in page %p's pv list",
6222 pte = pmap_pde_to_pte(pde, pv->pv_va);
6225 if (oldpte & PG_RW) {
6226 if (!atomic_cmpset_long(pte, oldpte, oldpte &
6229 if ((oldpte & PG_M) != 0)
6231 pmap_invalidate_page(pmap, pv->pv_va);
6236 vm_page_aflag_clear(m, PGA_WRITEABLE);
6237 pmap_delayed_invl_wait(m);
6240 static __inline boolean_t
6241 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
6244 if (!pmap_emulate_ad_bits(pmap))
6247 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
6250 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
6251 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
6252 * if the EPT_PG_WRITE bit is set.
6254 if ((pte & EPT_PG_WRITE) != 0)
6258 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
6260 if ((pte & EPT_PG_EXECUTE) == 0 ||
6261 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
6268 * pmap_ts_referenced:
6270 * Return a count of reference bits for a page, clearing those bits.
6271 * It is not necessary for every reference bit to be cleared, but it
6272 * is necessary that 0 only be returned when there are truly no
6273 * reference bits set.
6275 * As an optimization, update the page's dirty field if a modified bit is
6276 * found while counting reference bits. This opportunistic update can be
6277 * performed at low cost and can eliminate the need for some future calls
6278 * to pmap_is_modified(). However, since this function stops after
6279 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
6280 * dirty pages. Those dirty pages will only be detected by a future call
6281 * to pmap_is_modified().
6283 * A DI block is not needed within this function, because
6284 * invalidations are performed before the PV list lock is
6288 pmap_ts_referenced(vm_page_t m)
6290 struct md_page *pvh;
6293 struct rwlock *lock;
6294 pd_entry_t oldpde, *pde;
6295 pt_entry_t *pte, PG_A, PG_M, PG_RW;
6298 int cleared, md_gen, not_cleared, pvh_gen;
6299 struct spglist free;
6302 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6303 ("pmap_ts_referenced: page %p is not managed", m));
6306 pa = VM_PAGE_TO_PHYS(m);
6307 lock = PHYS_TO_PV_LIST_LOCK(pa);
6308 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
6312 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6313 goto small_mappings;
6319 if (!PMAP_TRYLOCK(pmap)) {
6320 pvh_gen = pvh->pv_gen;
6324 if (pvh_gen != pvh->pv_gen) {
6329 PG_A = pmap_accessed_bit(pmap);
6330 PG_M = pmap_modified_bit(pmap);
6331 PG_RW = pmap_rw_bit(pmap);
6333 pde = pmap_pde(pmap, pv->pv_va);
6335 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6337 * Although "oldpde" is mapping a 2MB page, because
6338 * this function is called at a 4KB page granularity,
6339 * we only update the 4KB page under test.
6343 if ((oldpde & PG_A) != 0) {
6345 * Since this reference bit is shared by 512 4KB
6346 * pages, it should not be cleared every time it is
6347 * tested. Apply a simple "hash" function on the
6348 * physical page number, the virtual superpage number,
6349 * and the pmap address to select one 4KB page out of
6350 * the 512 on which testing the reference bit will
6351 * result in clearing that reference bit. This
6352 * function is designed to avoid the selection of the
6353 * same 4KB page for every 2MB page mapping.
6355 * On demotion, a mapping that hasn't been referenced
6356 * is simply destroyed. To avoid the possibility of a
6357 * subsequent page fault on a demoted wired mapping,
6358 * always leave its reference bit set. Moreover,
6359 * since the superpage is wired, the current state of
6360 * its reference bit won't affect page replacement.
6362 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
6363 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
6364 (oldpde & PG_W) == 0) {
6365 if (safe_to_clear_referenced(pmap, oldpde)) {
6366 atomic_clear_long(pde, PG_A);
6367 pmap_invalidate_page(pmap, pv->pv_va);
6369 } else if (pmap_demote_pde_locked(pmap, pde,
6370 pv->pv_va, &lock)) {
6372 * Remove the mapping to a single page
6373 * so that a subsequent access may
6374 * repromote. Since the underlying
6375 * page table page is fully populated,
6376 * this removal never frees a page
6380 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6382 pte = pmap_pde_to_pte(pde, va);
6383 pmap_remove_pte(pmap, pte, va, *pde,
6385 pmap_invalidate_page(pmap, va);
6391 * The superpage mapping was removed
6392 * entirely and therefore 'pv' is no
6400 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6401 ("inconsistent pv lock %p %p for page %p",
6402 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6407 /* Rotate the PV list if it has more than one entry. */
6408 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6409 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6410 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6413 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6415 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6417 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6424 if (!PMAP_TRYLOCK(pmap)) {
6425 pvh_gen = pvh->pv_gen;
6426 md_gen = m->md.pv_gen;
6430 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6435 PG_A = pmap_accessed_bit(pmap);
6436 PG_M = pmap_modified_bit(pmap);
6437 PG_RW = pmap_rw_bit(pmap);
6438 pde = pmap_pde(pmap, pv->pv_va);
6439 KASSERT((*pde & PG_PS) == 0,
6440 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6442 pte = pmap_pde_to_pte(pde, pv->pv_va);
6443 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6445 if ((*pte & PG_A) != 0) {
6446 if (safe_to_clear_referenced(pmap, *pte)) {
6447 atomic_clear_long(pte, PG_A);
6448 pmap_invalidate_page(pmap, pv->pv_va);
6450 } else if ((*pte & PG_W) == 0) {
6452 * Wired pages cannot be paged out so
6453 * doing accessed bit emulation for
6454 * them is wasted effort. We do the
6455 * hard work for unwired pages only.
6457 pmap_remove_pte(pmap, pte, pv->pv_va,
6458 *pde, &free, &lock);
6459 pmap_invalidate_page(pmap, pv->pv_va);
6464 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6465 ("inconsistent pv lock %p %p for page %p",
6466 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6471 /* Rotate the PV list if it has more than one entry. */
6472 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6473 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6474 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6477 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6478 not_cleared < PMAP_TS_REFERENCED_MAX);
6481 pmap_free_zero_pages(&free);
6482 return (cleared + not_cleared);
6486 * Apply the given advice to the specified range of addresses within the
6487 * given pmap. Depending on the advice, clear the referenced and/or
6488 * modified flags in each mapping and set the mapped page's dirty field.
6491 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6493 struct rwlock *lock;
6494 pml4_entry_t *pml4e;
6496 pd_entry_t oldpde, *pde;
6497 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6498 vm_offset_t va, va_next;
6500 boolean_t anychanged;
6502 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6506 * A/D bit emulation requires an alternate code path when clearing
6507 * the modified and accessed bits below. Since this function is
6508 * advisory in nature we skip it entirely for pmaps that require
6509 * A/D bit emulation.
6511 if (pmap_emulate_ad_bits(pmap))
6514 PG_A = pmap_accessed_bit(pmap);
6515 PG_G = pmap_global_bit(pmap);
6516 PG_M = pmap_modified_bit(pmap);
6517 PG_V = pmap_valid_bit(pmap);
6518 PG_RW = pmap_rw_bit(pmap);
6520 pmap_delayed_invl_started();
6522 for (; sva < eva; sva = va_next) {
6523 pml4e = pmap_pml4e(pmap, sva);
6524 if ((*pml4e & PG_V) == 0) {
6525 va_next = (sva + NBPML4) & ~PML4MASK;
6530 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6531 if ((*pdpe & PG_V) == 0) {
6532 va_next = (sva + NBPDP) & ~PDPMASK;
6537 va_next = (sva + NBPDR) & ~PDRMASK;
6540 pde = pmap_pdpe_to_pde(pdpe, sva);
6542 if ((oldpde & PG_V) == 0)
6544 else if ((oldpde & PG_PS) != 0) {
6545 if ((oldpde & PG_MANAGED) == 0)
6548 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6553 * The large page mapping was destroyed.
6559 * Unless the page mappings are wired, remove the
6560 * mapping to a single page so that a subsequent
6561 * access may repromote. Since the underlying page
6562 * table page is fully populated, this removal never
6563 * frees a page table page.
6565 if ((oldpde & PG_W) == 0) {
6566 pte = pmap_pde_to_pte(pde, sva);
6567 KASSERT((*pte & PG_V) != 0,
6568 ("pmap_advise: invalid PTE"));
6569 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6579 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6581 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6583 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6584 if (advice == MADV_DONTNEED) {
6586 * Future calls to pmap_is_modified()
6587 * can be avoided by making the page
6590 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6593 atomic_clear_long(pte, PG_M | PG_A);
6594 } else if ((*pte & PG_A) != 0)
6595 atomic_clear_long(pte, PG_A);
6599 if ((*pte & PG_G) != 0) {
6606 if (va != va_next) {
6607 pmap_invalidate_range(pmap, va, sva);
6612 pmap_invalidate_range(pmap, va, sva);
6615 pmap_invalidate_all(pmap);
6617 pmap_delayed_invl_finished();
6621 * Clear the modify bits on the specified physical page.
6624 pmap_clear_modify(vm_page_t m)
6626 struct md_page *pvh;
6628 pv_entry_t next_pv, pv;
6629 pd_entry_t oldpde, *pde;
6630 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6631 struct rwlock *lock;
6633 int md_gen, pvh_gen;
6635 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6636 ("pmap_clear_modify: page %p is not managed", m));
6637 VM_OBJECT_ASSERT_WLOCKED(m->object);
6638 KASSERT(!vm_page_xbusied(m),
6639 ("pmap_clear_modify: page %p is exclusive busied", m));
6642 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6643 * If the object containing the page is locked and the page is not
6644 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6646 if ((m->aflags & PGA_WRITEABLE) == 0)
6648 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6649 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6650 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6653 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6655 if (!PMAP_TRYLOCK(pmap)) {
6656 pvh_gen = pvh->pv_gen;
6660 if (pvh_gen != pvh->pv_gen) {
6665 PG_M = pmap_modified_bit(pmap);
6666 PG_V = pmap_valid_bit(pmap);
6667 PG_RW = pmap_rw_bit(pmap);
6669 pde = pmap_pde(pmap, va);
6671 if ((oldpde & PG_RW) != 0) {
6672 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6673 if ((oldpde & PG_W) == 0) {
6675 * Write protect the mapping to a
6676 * single page so that a subsequent
6677 * write access may repromote.
6679 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6681 pte = pmap_pde_to_pte(pde, va);
6683 if ((oldpte & PG_V) != 0) {
6684 while (!atomic_cmpset_long(pte,
6686 oldpte & ~(PG_M | PG_RW)))
6689 pmap_invalidate_page(pmap, va);
6696 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6698 if (!PMAP_TRYLOCK(pmap)) {
6699 md_gen = m->md.pv_gen;
6700 pvh_gen = pvh->pv_gen;
6704 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6709 PG_M = pmap_modified_bit(pmap);
6710 PG_RW = pmap_rw_bit(pmap);
6711 pde = pmap_pde(pmap, pv->pv_va);
6712 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6713 " a 2mpage in page %p's pv list", m));
6714 pte = pmap_pde_to_pte(pde, pv->pv_va);
6715 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6716 atomic_clear_long(pte, PG_M);
6717 pmap_invalidate_page(pmap, pv->pv_va);
6725 * Miscellaneous support routines follow
6728 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6729 static __inline void
6730 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6735 * The cache mode bits are all in the low 32-bits of the
6736 * PTE, so we can just spin on updating the low 32-bits.
6739 opte = *(u_int *)pte;
6740 npte = opte & ~mask;
6742 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6745 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6746 static __inline void
6747 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6752 * The cache mode bits are all in the low 32-bits of the
6753 * PDE, so we can just spin on updating the low 32-bits.
6756 opde = *(u_int *)pde;
6757 npde = opde & ~mask;
6759 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6763 * Map a set of physical memory pages into the kernel virtual
6764 * address space. Return a pointer to where it is mapped. This
6765 * routine is intended to be used for mapping device memory,
6769 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6771 struct pmap_preinit_mapping *ppim;
6772 vm_offset_t va, offset;
6776 offset = pa & PAGE_MASK;
6777 size = round_page(offset + size);
6778 pa = trunc_page(pa);
6780 if (!pmap_initialized) {
6782 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6783 ppim = pmap_preinit_mapping + i;
6784 if (ppim->va == 0) {
6788 ppim->va = virtual_avail;
6789 virtual_avail += size;
6795 panic("%s: too many preinit mappings", __func__);
6798 * If we have a preinit mapping, re-use it.
6800 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6801 ppim = pmap_preinit_mapping + i;
6802 if (ppim->pa == pa && ppim->sz == size &&
6804 return ((void *)(ppim->va + offset));
6807 * If the specified range of physical addresses fits within
6808 * the direct map window, use the direct map.
6810 if (pa < dmaplimit && pa + size < dmaplimit) {
6811 va = PHYS_TO_DMAP(pa);
6812 if (!pmap_change_attr(va, size, mode))
6813 return ((void *)(va + offset));
6815 va = kva_alloc(size);
6817 panic("%s: Couldn't allocate KVA", __func__);
6819 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6820 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6821 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6822 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6823 return ((void *)(va + offset));
6827 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6830 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6834 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6837 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6841 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6843 struct pmap_preinit_mapping *ppim;
6847 /* If we gave a direct map region in pmap_mapdev, do nothing */
6848 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6850 offset = va & PAGE_MASK;
6851 size = round_page(offset + size);
6852 va = trunc_page(va);
6853 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6854 ppim = pmap_preinit_mapping + i;
6855 if (ppim->va == va && ppim->sz == size) {
6856 if (pmap_initialized)
6862 if (va + size == virtual_avail)
6867 if (pmap_initialized)
6872 * Tries to demote a 1GB page mapping.
6875 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6877 pdp_entry_t newpdpe, oldpdpe;
6878 pd_entry_t *firstpde, newpde, *pde;
6879 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6883 PG_A = pmap_accessed_bit(pmap);
6884 PG_M = pmap_modified_bit(pmap);
6885 PG_V = pmap_valid_bit(pmap);
6886 PG_RW = pmap_rw_bit(pmap);
6888 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6890 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6891 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6892 if ((pdpg = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6893 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6894 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6895 " in pmap %p", va, pmap);
6898 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
6899 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
6900 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6901 KASSERT((oldpdpe & PG_A) != 0,
6902 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6903 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6904 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
6908 * Initialize the page directory page.
6910 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
6916 * Demote the mapping.
6921 * Invalidate a stale recursive mapping of the page directory page.
6923 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
6925 pmap_pdpe_demotions++;
6926 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
6927 " in pmap %p", va, pmap);
6932 * Sets the memory attribute for the specified page.
6935 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6938 m->md.pat_mode = ma;
6941 * If "m" is a normal page, update its direct mapping. This update
6942 * can be relied upon to perform any cache operations that are
6943 * required for data coherence.
6945 if ((m->flags & PG_FICTITIOUS) == 0 &&
6946 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6948 panic("memory attribute change on the direct map failed");
6952 * Changes the specified virtual address range's memory type to that given by
6953 * the parameter "mode". The specified virtual address range must be
6954 * completely contained within either the direct map or the kernel map. If
6955 * the virtual address range is contained within the kernel map, then the
6956 * memory type for each of the corresponding ranges of the direct map is also
6957 * changed. (The corresponding ranges of the direct map are those ranges that
6958 * map the same physical pages as the specified virtual address range.) These
6959 * changes to the direct map are necessary because Intel describes the
6960 * behavior of their processors as "undefined" if two or more mappings to the
6961 * same physical page have different memory types.
6963 * Returns zero if the change completed successfully, and either EINVAL or
6964 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6965 * of the virtual address range was not mapped, and ENOMEM is returned if
6966 * there was insufficient memory available to complete the change. In the
6967 * latter case, the memory type may have been changed on some part of the
6968 * virtual address range or the direct map.
6971 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6975 PMAP_LOCK(kernel_pmap);
6976 error = pmap_change_attr_locked(va, size, mode);
6977 PMAP_UNLOCK(kernel_pmap);
6982 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
6984 vm_offset_t base, offset, tmpva;
6985 vm_paddr_t pa_start, pa_end, pa_end1;
6989 int cache_bits_pte, cache_bits_pde, error;
6992 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6993 base = trunc_page(va);
6994 offset = va & PAGE_MASK;
6995 size = round_page(offset + size);
6998 * Only supported on kernel virtual addresses, including the direct
6999 * map but excluding the recursive map.
7001 if (base < DMAP_MIN_ADDRESS)
7004 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
7005 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
7009 * Pages that aren't mapped aren't supported. Also break down 2MB pages
7010 * into 4KB pages if required.
7012 for (tmpva = base; tmpva < base + size; ) {
7013 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7014 if (pdpe == NULL || *pdpe == 0)
7016 if (*pdpe & PG_PS) {
7018 * If the current 1GB page already has the required
7019 * memory type, then we need not demote this page. Just
7020 * increment tmpva to the next 1GB page frame.
7022 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
7023 tmpva = trunc_1gpage(tmpva) + NBPDP;
7028 * If the current offset aligns with a 1GB page frame
7029 * and there is at least 1GB left within the range, then
7030 * we need not break down this page into 2MB pages.
7032 if ((tmpva & PDPMASK) == 0 &&
7033 tmpva + PDPMASK < base + size) {
7037 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
7040 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7045 * If the current 2MB page already has the required
7046 * memory type, then we need not demote this page. Just
7047 * increment tmpva to the next 2MB page frame.
7049 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
7050 tmpva = trunc_2mpage(tmpva) + NBPDR;
7055 * If the current offset aligns with a 2MB page frame
7056 * and there is at least 2MB left within the range, then
7057 * we need not break down this page into 4KB pages.
7059 if ((tmpva & PDRMASK) == 0 &&
7060 tmpva + PDRMASK < base + size) {
7064 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
7067 pte = pmap_pde_to_pte(pde, tmpva);
7075 * Ok, all the pages exist, so run through them updating their
7076 * cache mode if required.
7078 pa_start = pa_end = 0;
7079 for (tmpva = base; tmpva < base + size; ) {
7080 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7081 if (*pdpe & PG_PS) {
7082 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
7083 pmap_pde_attr(pdpe, cache_bits_pde,
7087 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7088 (*pdpe & PG_PS_FRAME) < dmaplimit) {
7089 if (pa_start == pa_end) {
7090 /* Start physical address run. */
7091 pa_start = *pdpe & PG_PS_FRAME;
7092 pa_end = pa_start + NBPDP;
7093 } else if (pa_end == (*pdpe & PG_PS_FRAME))
7096 /* Run ended, update direct map. */
7097 error = pmap_change_attr_locked(
7098 PHYS_TO_DMAP(pa_start),
7099 pa_end - pa_start, mode);
7102 /* Start physical address run. */
7103 pa_start = *pdpe & PG_PS_FRAME;
7104 pa_end = pa_start + NBPDP;
7107 tmpva = trunc_1gpage(tmpva) + NBPDP;
7110 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7112 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
7113 pmap_pde_attr(pde, cache_bits_pde,
7117 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7118 (*pde & PG_PS_FRAME) < dmaplimit) {
7119 if (pa_start == pa_end) {
7120 /* Start physical address run. */
7121 pa_start = *pde & PG_PS_FRAME;
7122 pa_end = pa_start + NBPDR;
7123 } else if (pa_end == (*pde & PG_PS_FRAME))
7126 /* Run ended, update direct map. */
7127 error = pmap_change_attr_locked(
7128 PHYS_TO_DMAP(pa_start),
7129 pa_end - pa_start, mode);
7132 /* Start physical address run. */
7133 pa_start = *pde & PG_PS_FRAME;
7134 pa_end = pa_start + NBPDR;
7137 tmpva = trunc_2mpage(tmpva) + NBPDR;
7139 pte = pmap_pde_to_pte(pde, tmpva);
7140 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
7141 pmap_pte_attr(pte, cache_bits_pte,
7145 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7146 (*pte & PG_FRAME) < dmaplimit) {
7147 if (pa_start == pa_end) {
7148 /* Start physical address run. */
7149 pa_start = *pte & PG_FRAME;
7150 pa_end = pa_start + PAGE_SIZE;
7151 } else if (pa_end == (*pte & PG_FRAME))
7152 pa_end += PAGE_SIZE;
7154 /* Run ended, update direct map. */
7155 error = pmap_change_attr_locked(
7156 PHYS_TO_DMAP(pa_start),
7157 pa_end - pa_start, mode);
7160 /* Start physical address run. */
7161 pa_start = *pte & PG_FRAME;
7162 pa_end = pa_start + PAGE_SIZE;
7168 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
7169 pa_end1 = MIN(pa_end, dmaplimit);
7170 if (pa_start != pa_end1)
7171 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
7172 pa_end1 - pa_start, mode);
7176 * Flush CPU caches if required to make sure any data isn't cached that
7177 * shouldn't be, etc.
7180 pmap_invalidate_range(kernel_pmap, base, tmpva);
7181 pmap_invalidate_cache_range(base, tmpva, FALSE);
7187 * Demotes any mapping within the direct map region that covers more than the
7188 * specified range of physical addresses. This range's size must be a power
7189 * of two and its starting address must be a multiple of its size. Since the
7190 * demotion does not change any attributes of the mapping, a TLB invalidation
7191 * is not mandatory. The caller may, however, request a TLB invalidation.
7194 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
7203 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
7204 KASSERT((base & (len - 1)) == 0,
7205 ("pmap_demote_DMAP: base is not a multiple of len"));
7206 if (len < NBPDP && base < dmaplimit) {
7207 va = PHYS_TO_DMAP(base);
7209 PMAP_LOCK(kernel_pmap);
7210 pdpe = pmap_pdpe(kernel_pmap, va);
7211 if ((*pdpe & X86_PG_V) == 0)
7212 panic("pmap_demote_DMAP: invalid PDPE");
7213 if ((*pdpe & PG_PS) != 0) {
7214 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
7215 panic("pmap_demote_DMAP: PDPE failed");
7219 pde = pmap_pdpe_to_pde(pdpe, va);
7220 if ((*pde & X86_PG_V) == 0)
7221 panic("pmap_demote_DMAP: invalid PDE");
7222 if ((*pde & PG_PS) != 0) {
7223 if (!pmap_demote_pde(kernel_pmap, pde, va))
7224 panic("pmap_demote_DMAP: PDE failed");
7228 if (changed && invalidate)
7229 pmap_invalidate_page(kernel_pmap, va);
7230 PMAP_UNLOCK(kernel_pmap);
7235 * perform the pmap work for mincore
7238 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
7241 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
7245 PG_A = pmap_accessed_bit(pmap);
7246 PG_M = pmap_modified_bit(pmap);
7247 PG_V = pmap_valid_bit(pmap);
7248 PG_RW = pmap_rw_bit(pmap);
7252 pdep = pmap_pde(pmap, addr);
7253 if (pdep != NULL && (*pdep & PG_V)) {
7254 if (*pdep & PG_PS) {
7256 /* Compute the physical address of the 4KB page. */
7257 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
7259 val = MINCORE_SUPER;
7261 pte = *pmap_pde_to_pte(pdep, addr);
7262 pa = pte & PG_FRAME;
7270 if ((pte & PG_V) != 0) {
7271 val |= MINCORE_INCORE;
7272 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7273 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
7274 if ((pte & PG_A) != 0)
7275 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
7277 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
7278 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
7279 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
7280 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
7281 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
7284 PA_UNLOCK_COND(*locked_pa);
7290 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
7292 uint32_t gen, new_gen, pcid_next;
7294 CRITICAL_ASSERT(curthread);
7295 gen = PCPU_GET(pcid_gen);
7296 if (!pti && (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN ||
7297 pmap->pm_pcids[cpuid].pm_gen == gen))
7298 return (CR3_PCID_SAVE);
7299 pcid_next = PCPU_GET(pcid_next);
7300 KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
7301 (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
7302 ("cpu %d pcid_next %#x", cpuid, pcid_next));
7303 if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
7304 (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
7308 PCPU_SET(pcid_gen, new_gen);
7309 pcid_next = PMAP_PCID_KERN + 1;
7313 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
7314 pmap->pm_pcids[cpuid].pm_gen = new_gen;
7315 PCPU_SET(pcid_next, pcid_next + 1);
7320 pmap_activate_sw(struct thread *td)
7322 pmap_t oldpmap, pmap;
7323 struct invpcid_descr d;
7324 uint64_t cached, cr3, kcr3, ucr3;
7328 oldpmap = PCPU_GET(curpmap);
7329 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7330 if (oldpmap == pmap)
7332 cpuid = PCPU_GET(cpuid);
7334 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7336 CPU_SET(cpuid, &pmap->pm_active);
7339 if (pmap_pcid_enabled) {
7340 cached = pmap_pcid_alloc(pmap, cpuid);
7341 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
7342 pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
7343 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
7344 pmap->pm_pcids[cpuid].pm_pcid));
7345 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
7346 pmap == kernel_pmap,
7347 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
7348 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
7351 * If the INVPCID instruction is not available,
7352 * invltlb_pcid_handler() is used for handle
7353 * invalidate_all IPI, which checks for curpmap ==
7354 * smp_tlb_pmap. Below operations sequence has a
7355 * window where %CR3 is loaded with the new pmap's
7356 * PML4 address, but curpmap value is not yet updated.
7357 * This causes invltlb IPI handler, called between the
7358 * updates, to execute as NOP, which leaves stale TLB
7361 * Note that the most typical use of
7362 * pmap_activate_sw(), from the context switch, is
7363 * immune to this race, because interrupts are
7364 * disabled (while the thread lock is owned), and IPI
7365 * happends after curpmap is updated. Protect other
7366 * callers in a similar way, by disabling interrupts
7367 * around the %cr3 register reload and curpmap
7371 rflags = intr_disable();
7373 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
7374 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
7377 PCPU_INC(pm_save_cnt);
7379 PCPU_SET(curpmap, pmap);
7381 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid;
7382 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[cpuid].pm_pcid |
7386 * Manually invalidate translations cached
7387 * from the user page table, which are not
7388 * flushed by reload of cr3 with the kernel
7389 * page table pointer above.
7391 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
7392 if (invpcid_works) {
7393 d.pcid = PMAP_PCID_USER_PT |
7394 pmap->pm_pcids[cpuid].pm_pcid;
7397 invpcid(&d, INVPCID_CTX);
7399 pmap_pti_pcid_invalidate(ucr3, kcr3);
7403 PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
7404 PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
7407 intr_restore(rflags);
7408 } else if (cr3 != pmap->pm_cr3) {
7409 load_cr3(pmap->pm_cr3);
7410 PCPU_SET(curpmap, pmap);
7412 PCPU_SET(kcr3, pmap->pm_cr3);
7413 PCPU_SET(ucr3, pmap->pm_ucr3);
7417 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
7419 CPU_CLR(cpuid, &oldpmap->pm_active);
7424 pmap_activate(struct thread *td)
7428 pmap_activate_sw(td);
7433 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
7438 * Increase the starting virtual address of the given mapping if a
7439 * different alignment might result in more superpage mappings.
7442 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7443 vm_offset_t *addr, vm_size_t size)
7445 vm_offset_t superpage_offset;
7449 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7450 offset += ptoa(object->pg_color);
7451 superpage_offset = offset & PDRMASK;
7452 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
7453 (*addr & PDRMASK) == superpage_offset)
7455 if ((*addr & PDRMASK) < superpage_offset)
7456 *addr = (*addr & ~PDRMASK) + superpage_offset;
7458 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
7462 static unsigned long num_dirty_emulations;
7463 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
7464 &num_dirty_emulations, 0, NULL);
7466 static unsigned long num_accessed_emulations;
7467 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
7468 &num_accessed_emulations, 0, NULL);
7470 static unsigned long num_superpage_accessed_emulations;
7471 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7472 &num_superpage_accessed_emulations, 0, NULL);
7474 static unsigned long ad_emulation_superpage_promotions;
7475 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7476 &ad_emulation_superpage_promotions, 0, NULL);
7477 #endif /* INVARIANTS */
7480 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7483 struct rwlock *lock;
7484 #if VM_NRESERVLEVEL > 0
7488 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7490 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7491 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7493 if (!pmap_emulate_ad_bits(pmap))
7496 PG_A = pmap_accessed_bit(pmap);
7497 PG_M = pmap_modified_bit(pmap);
7498 PG_V = pmap_valid_bit(pmap);
7499 PG_RW = pmap_rw_bit(pmap);
7505 pde = pmap_pde(pmap, va);
7506 if (pde == NULL || (*pde & PG_V) == 0)
7509 if ((*pde & PG_PS) != 0) {
7510 if (ftype == VM_PROT_READ) {
7512 atomic_add_long(&num_superpage_accessed_emulations, 1);
7520 pte = pmap_pde_to_pte(pde, va);
7521 if ((*pte & PG_V) == 0)
7524 if (ftype == VM_PROT_WRITE) {
7525 if ((*pte & PG_RW) == 0)
7528 * Set the modified and accessed bits simultaneously.
7530 * Intel EPT PTEs that do software emulation of A/D bits map
7531 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7532 * An EPT misconfiguration is triggered if the PTE is writable
7533 * but not readable (WR=10). This is avoided by setting PG_A
7534 * and PG_M simultaneously.
7536 *pte |= PG_M | PG_A;
7541 #if VM_NRESERVLEVEL > 0
7542 /* try to promote the mapping */
7543 if (va < VM_MAXUSER_ADDRESS)
7544 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7548 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7550 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7551 pmap_ps_enabled(pmap) &&
7552 (m->flags & PG_FICTITIOUS) == 0 &&
7553 vm_reserv_level_iffullpop(m) == 0) {
7554 pmap_promote_pde(pmap, pde, va, &lock);
7556 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7562 if (ftype == VM_PROT_WRITE)
7563 atomic_add_long(&num_dirty_emulations, 1);
7565 atomic_add_long(&num_accessed_emulations, 1);
7567 rv = 0; /* success */
7576 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7581 pt_entry_t *pte, PG_V;
7585 PG_V = pmap_valid_bit(pmap);
7588 pml4 = pmap_pml4e(pmap, va);
7590 if ((*pml4 & PG_V) == 0)
7593 pdp = pmap_pml4e_to_pdpe(pml4, va);
7595 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7598 pde = pmap_pdpe_to_pde(pdp, va);
7600 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7603 pte = pmap_pde_to_pte(pde, va);
7612 * Get the kernel virtual address of a set of physical pages. If there are
7613 * physical addresses not covered by the DMAP perform a transient mapping
7614 * that will be removed when calling pmap_unmap_io_transient.
7616 * \param page The pages the caller wishes to obtain the virtual
7617 * address on the kernel memory map.
7618 * \param vaddr On return contains the kernel virtual memory address
7619 * of the pages passed in the page parameter.
7620 * \param count Number of pages passed in.
7621 * \param can_fault TRUE if the thread using the mapped pages can take
7622 * page faults, FALSE otherwise.
7624 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7625 * finished or FALSE otherwise.
7629 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7630 boolean_t can_fault)
7633 boolean_t needs_mapping;
7635 int cache_bits, error, i;
7638 * Allocate any KVA space that we need, this is done in a separate
7639 * loop to prevent calling vmem_alloc while pinned.
7641 needs_mapping = FALSE;
7642 for (i = 0; i < count; i++) {
7643 paddr = VM_PAGE_TO_PHYS(page[i]);
7644 if (__predict_false(paddr >= dmaplimit)) {
7645 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7646 M_BESTFIT | M_WAITOK, &vaddr[i]);
7647 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7648 needs_mapping = TRUE;
7650 vaddr[i] = PHYS_TO_DMAP(paddr);
7654 /* Exit early if everything is covered by the DMAP */
7659 * NB: The sequence of updating a page table followed by accesses
7660 * to the corresponding pages used in the !DMAP case is subject to
7661 * the situation described in the "AMD64 Architecture Programmer's
7662 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7663 * Coherency Considerations". Therefore, issuing the INVLPG right
7664 * after modifying the PTE bits is crucial.
7668 for (i = 0; i < count; i++) {
7669 paddr = VM_PAGE_TO_PHYS(page[i]);
7670 if (paddr >= dmaplimit) {
7673 * Slow path, since we can get page faults
7674 * while mappings are active don't pin the
7675 * thread to the CPU and instead add a global
7676 * mapping visible to all CPUs.
7678 pmap_qenter(vaddr[i], &page[i], 1);
7680 pte = vtopte(vaddr[i]);
7681 cache_bits = pmap_cache_bits(kernel_pmap,
7682 page[i]->md.pat_mode, 0);
7683 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7690 return (needs_mapping);
7694 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7695 boolean_t can_fault)
7702 for (i = 0; i < count; i++) {
7703 paddr = VM_PAGE_TO_PHYS(page[i]);
7704 if (paddr >= dmaplimit) {
7706 pmap_qremove(vaddr[i], 1);
7707 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7713 pmap_quick_enter_page(vm_page_t m)
7717 paddr = VM_PAGE_TO_PHYS(m);
7718 if (paddr < dmaplimit)
7719 return (PHYS_TO_DMAP(paddr));
7720 mtx_lock_spin(&qframe_mtx);
7721 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7722 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7723 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7728 pmap_quick_remove_page(vm_offset_t addr)
7733 pte_store(vtopte(qframe), 0);
7735 mtx_unlock_spin(&qframe_mtx);
7739 pmap_pti_alloc_page(void)
7743 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7744 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_NOBUSY |
7745 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
7750 pmap_pti_free_page(vm_page_t m)
7753 KASSERT(m->wire_count > 0, ("page %p not wired", m));
7755 if (m->wire_count != 0)
7757 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
7758 vm_page_free_zero(m);
7772 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
7773 VM_OBJECT_WLOCK(pti_obj);
7774 pml4_pg = pmap_pti_alloc_page();
7775 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
7776 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
7777 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
7778 pdpe = pmap_pti_pdpe(va);
7779 pmap_pti_wire_pte(pdpe);
7781 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
7782 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
7783 pmap_pti_add_kva_locked((vm_offset_t)gdt, (vm_offset_t)gdt +
7784 sizeof(struct user_segment_descriptor) * NGDT * MAXCPU, false);
7785 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
7786 sizeof(struct gate_descriptor) * NIDT, false);
7787 pmap_pti_add_kva_locked((vm_offset_t)common_tss,
7788 (vm_offset_t)common_tss + sizeof(struct amd64tss) * MAXCPU, false);
7790 /* Doublefault stack IST 1 */
7791 va = common_tss[i].tss_ist1;
7792 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7793 /* NMI stack IST 2 */
7794 va = common_tss[i].tss_ist2 + sizeof(struct nmi_pcpu);
7795 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7796 /* MC# stack IST 3 */
7797 va = common_tss[i].tss_ist3 + sizeof(struct nmi_pcpu);
7798 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7800 pmap_pti_add_kva_locked((vm_offset_t)kernphys + KERNBASE,
7801 (vm_offset_t)etext, true);
7802 pti_finalized = true;
7803 VM_OBJECT_WUNLOCK(pti_obj);
7805 SYSINIT(pmap_pti, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_pti_init, NULL);
7807 static pdp_entry_t *
7808 pmap_pti_pdpe(vm_offset_t va)
7810 pml4_entry_t *pml4e;
7813 vm_pindex_t pml4_idx;
7816 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7818 pml4_idx = pmap_pml4e_index(va);
7819 pml4e = &pti_pml4[pml4_idx];
7823 panic("pml4 alloc after finalization\n");
7824 m = pmap_pti_alloc_page();
7826 pmap_pti_free_page(m);
7827 mphys = *pml4e & ~PAGE_MASK;
7829 mphys = VM_PAGE_TO_PHYS(m);
7830 *pml4e = mphys | X86_PG_RW | X86_PG_V;
7833 mphys = *pml4e & ~PAGE_MASK;
7835 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
7840 pmap_pti_wire_pte(void *pte)
7844 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7845 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7850 pmap_pti_unwire_pde(void *pde, bool only_ref)
7854 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7855 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
7856 MPASS(m->wire_count > 0);
7857 MPASS(only_ref || m->wire_count > 1);
7858 pmap_pti_free_page(m);
7862 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
7867 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7868 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7869 MPASS(m->wire_count > 0);
7870 if (pmap_pti_free_page(m)) {
7871 pde = pmap_pti_pde(va);
7872 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
7874 pmap_pti_unwire_pde(pde, false);
7879 pmap_pti_pde(vm_offset_t va)
7887 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7889 pdpe = pmap_pti_pdpe(va);
7891 m = pmap_pti_alloc_page();
7893 pmap_pti_free_page(m);
7894 MPASS((*pdpe & X86_PG_PS) == 0);
7895 mphys = *pdpe & ~PAGE_MASK;
7897 mphys = VM_PAGE_TO_PHYS(m);
7898 *pdpe = mphys | X86_PG_RW | X86_PG_V;
7901 MPASS((*pdpe & X86_PG_PS) == 0);
7902 mphys = *pdpe & ~PAGE_MASK;
7905 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
7906 pd_idx = pmap_pde_index(va);
7912 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
7919 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7921 pde = pmap_pti_pde(va);
7922 if (unwire_pde != NULL) {
7924 pmap_pti_wire_pte(pde);
7927 m = pmap_pti_alloc_page();
7929 pmap_pti_free_page(m);
7930 MPASS((*pde & X86_PG_PS) == 0);
7931 mphys = *pde & ~(PAGE_MASK | pg_nx);
7933 mphys = VM_PAGE_TO_PHYS(m);
7934 *pde = mphys | X86_PG_RW | X86_PG_V;
7935 if (unwire_pde != NULL)
7936 *unwire_pde = false;
7939 MPASS((*pde & X86_PG_PS) == 0);
7940 mphys = *pde & ~(PAGE_MASK | pg_nx);
7943 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
7944 pte += pmap_pte_index(va);
7950 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
7954 pt_entry_t *pte, ptev;
7957 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7959 sva = trunc_page(sva);
7960 MPASS(sva > VM_MAXUSER_ADDRESS);
7961 eva = round_page(eva);
7963 for (; sva < eva; sva += PAGE_SIZE) {
7964 pte = pmap_pti_pte(sva, &unwire_pde);
7965 pa = pmap_kextract(sva);
7966 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A |
7967 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
7968 VM_MEMATTR_DEFAULT, FALSE);
7970 pte_store(pte, ptev);
7971 pmap_pti_wire_pte(pte);
7973 KASSERT(!pti_finalized,
7974 ("pti overlap after fin %#lx %#lx %#lx",
7976 KASSERT(*pte == ptev,
7977 ("pti non-identical pte after fin %#lx %#lx %#lx",
7981 pde = pmap_pti_pde(sva);
7982 pmap_pti_unwire_pde(pde, true);
7988 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
7993 VM_OBJECT_WLOCK(pti_obj);
7994 pmap_pti_add_kva_locked(sva, eva, exec);
7995 VM_OBJECT_WUNLOCK(pti_obj);
7999 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
8006 sva = rounddown2(sva, PAGE_SIZE);
8007 MPASS(sva > VM_MAXUSER_ADDRESS);
8008 eva = roundup2(eva, PAGE_SIZE);
8010 VM_OBJECT_WLOCK(pti_obj);
8011 for (va = sva; va < eva; va += PAGE_SIZE) {
8012 pte = pmap_pti_pte(va, NULL);
8013 KASSERT((*pte & X86_PG_V) != 0,
8014 ("invalid pte va %#lx pte %#lx pt %#lx", va,
8015 (u_long)pte, *pte));
8017 pmap_pti_unwire_pte(pte, va);
8019 pmap_invalidate_range(kernel_pmap, sva, eva);
8020 VM_OBJECT_WUNLOCK(pti_obj);
8023 #include "opt_ddb.h"
8025 #include <ddb/ddb.h>
8027 DB_SHOW_COMMAND(pte, pmap_print_pte)
8033 pt_entry_t *pte, PG_V;
8037 va = (vm_offset_t)addr;
8038 pmap = PCPU_GET(curpmap); /* XXX */
8040 db_printf("show pte addr\n");
8043 PG_V = pmap_valid_bit(pmap);
8044 pml4 = pmap_pml4e(pmap, va);
8045 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
8046 if ((*pml4 & PG_V) == 0) {
8050 pdp = pmap_pml4e_to_pdpe(pml4, va);
8051 db_printf(" pdpe %#016lx", *pdp);
8052 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
8056 pde = pmap_pdpe_to_pde(pdp, va);
8057 db_printf(" pde %#016lx", *pde);
8058 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
8062 pte = pmap_pde_to_pte(pde, va);
8063 db_printf(" pte %#016lx\n", *pte);
8066 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
8071 a = (vm_paddr_t)addr;
8072 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
8074 db_printf("show phys2dmap addr\n");