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 *);
691 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
694 * Move the kernel virtual free pointer to the next
695 * 2MB. This is used to help improve performance
696 * by using a large (2MB) page for much of the kernel
697 * (.text, .data, .bss)
700 pmap_kmem_choose(vm_offset_t addr)
702 vm_offset_t newaddr = addr;
704 newaddr = roundup2(addr, NBPDR);
708 /********************/
709 /* Inline functions */
710 /********************/
712 /* Return a non-clipped PD index for a given VA */
713 static __inline vm_pindex_t
714 pmap_pde_pindex(vm_offset_t va)
716 return (va >> PDRSHIFT);
720 /* Return a pointer to the PML4 slot that corresponds to a VA */
721 static __inline pml4_entry_t *
722 pmap_pml4e(pmap_t pmap, vm_offset_t va)
725 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
728 /* Return a pointer to the PDP slot that corresponds to a VA */
729 static __inline pdp_entry_t *
730 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
734 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
735 return (&pdpe[pmap_pdpe_index(va)]);
738 /* Return a pointer to the PDP slot that corresponds to a VA */
739 static __inline pdp_entry_t *
740 pmap_pdpe(pmap_t pmap, vm_offset_t va)
745 PG_V = pmap_valid_bit(pmap);
746 pml4e = pmap_pml4e(pmap, va);
747 if ((*pml4e & PG_V) == 0)
749 return (pmap_pml4e_to_pdpe(pml4e, va));
752 /* Return a pointer to the PD slot that corresponds to a VA */
753 static __inline pd_entry_t *
754 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
758 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
759 return (&pde[pmap_pde_index(va)]);
762 /* Return a pointer to the PD slot that corresponds to a VA */
763 static __inline pd_entry_t *
764 pmap_pde(pmap_t pmap, vm_offset_t va)
769 PG_V = pmap_valid_bit(pmap);
770 pdpe = pmap_pdpe(pmap, va);
771 if (pdpe == NULL || (*pdpe & PG_V) == 0)
773 return (pmap_pdpe_to_pde(pdpe, va));
776 /* Return a pointer to the PT slot that corresponds to a VA */
777 static __inline pt_entry_t *
778 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
782 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
783 return (&pte[pmap_pte_index(va)]);
786 /* Return a pointer to the PT slot that corresponds to a VA */
787 static __inline pt_entry_t *
788 pmap_pte(pmap_t pmap, vm_offset_t va)
793 PG_V = pmap_valid_bit(pmap);
794 pde = pmap_pde(pmap, va);
795 if (pde == NULL || (*pde & PG_V) == 0)
797 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
798 return ((pt_entry_t *)pde);
799 return (pmap_pde_to_pte(pde, va));
803 pmap_resident_count_inc(pmap_t pmap, int count)
806 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
807 pmap->pm_stats.resident_count += count;
811 pmap_resident_count_dec(pmap_t pmap, int count)
814 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
815 KASSERT(pmap->pm_stats.resident_count >= count,
816 ("pmap %p resident count underflow %ld %d", pmap,
817 pmap->pm_stats.resident_count, count));
818 pmap->pm_stats.resident_count -= count;
821 PMAP_INLINE pt_entry_t *
822 vtopte(vm_offset_t va)
824 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
826 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
828 return (PTmap + ((va >> PAGE_SHIFT) & mask));
831 static __inline pd_entry_t *
832 vtopde(vm_offset_t va)
834 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
836 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
838 return (PDmap + ((va >> PDRSHIFT) & mask));
842 allocpages(vm_paddr_t *firstaddr, int n)
847 bzero((void *)ret, n * PAGE_SIZE);
848 *firstaddr += n * PAGE_SIZE;
852 CTASSERT(powerof2(NDMPML4E));
854 /* number of kernel PDP slots */
855 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
858 nkpt_init(vm_paddr_t addr)
865 pt_pages = howmany(addr, 1 << PDRSHIFT);
866 pt_pages += NKPDPE(pt_pages);
869 * Add some slop beyond the bare minimum required for bootstrapping
872 * This is quite important when allocating KVA for kernel modules.
873 * The modules are required to be linked in the negative 2GB of
874 * the address space. If we run out of KVA in this region then
875 * pmap_growkernel() will need to allocate page table pages to map
876 * the entire 512GB of KVA space which is an unnecessary tax on
879 * Secondly, device memory mapped as part of setting up the low-
880 * level console(s) is taken from KVA, starting at virtual_avail.
881 * This is because cninit() is called after pmap_bootstrap() but
882 * before vm_init() and pmap_init(). 20MB for a frame buffer is
885 pt_pages += 32; /* 64MB additional slop. */
891 create_pagetables(vm_paddr_t *firstaddr)
893 int i, j, ndm1g, nkpdpe;
899 /* Allocate page table pages for the direct map */
900 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
901 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
903 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
904 if (ndmpdpphys > NDMPML4E) {
906 * Each NDMPML4E allows 512 GB, so limit to that,
907 * and then readjust ndmpdp and ndmpdpphys.
909 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
910 Maxmem = atop(NDMPML4E * NBPML4);
911 ndmpdpphys = NDMPML4E;
912 ndmpdp = NDMPML4E * NPDEPG;
914 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
916 if ((amd_feature & AMDID_PAGE1GB) != 0)
917 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
919 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
920 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
923 KPML4phys = allocpages(firstaddr, 1);
924 KPDPphys = allocpages(firstaddr, NKPML4E);
927 * Allocate the initial number of kernel page table pages required to
928 * bootstrap. We defer this until after all memory-size dependent
929 * allocations are done (e.g. direct map), so that we don't have to
930 * build in too much slop in our estimate.
932 * Note that when NKPML4E > 1, we have an empty page underneath
933 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
934 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
936 nkpt_init(*firstaddr);
937 nkpdpe = NKPDPE(nkpt);
939 KPTphys = allocpages(firstaddr, nkpt);
940 KPDphys = allocpages(firstaddr, nkpdpe);
942 /* Fill in the underlying page table pages */
943 /* Nominally read-only (but really R/W) from zero to physfree */
944 /* XXX not fully used, underneath 2M pages */
945 pt_p = (pt_entry_t *)KPTphys;
946 for (i = 0; ptoa(i) < *firstaddr; i++)
947 pt_p[i] = ptoa(i) | X86_PG_RW | X86_PG_V | pg_g;
949 /* Now map the page tables at their location within PTmap */
950 pd_p = (pd_entry_t *)KPDphys;
951 for (i = 0; i < nkpt; i++)
952 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
954 /* Map from zero to end of allocations under 2M pages */
955 /* This replaces some of the KPTphys entries above */
956 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
957 pd_p[i] = (i << PDRSHIFT) | X86_PG_RW | X86_PG_V | PG_PS |
961 * Because we map the physical blocks in 2M pages, adjust firstaddr
962 * to record the physical blocks we've actually mapped into kernel
963 * virtual address space.
965 *firstaddr = round_2mpage(*firstaddr);
967 /* And connect up the PD to the PDP (leaving room for L4 pages) */
968 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
969 for (i = 0; i < nkpdpe; i++)
970 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
974 * Now, set up the direct map region using 2MB and/or 1GB pages. If
975 * the end of physical memory is not aligned to a 1GB page boundary,
976 * then the residual physical memory is mapped with 2MB pages. Later,
977 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
978 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
979 * that are partially used.
981 pd_p = (pd_entry_t *)DMPDphys;
982 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
983 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
984 /* Preset PG_M and PG_A because demotion expects it. */
985 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
988 pdp_p = (pdp_entry_t *)DMPDPphys;
989 for (i = 0; i < ndm1g; i++) {
990 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
991 /* Preset PG_M and PG_A because demotion expects it. */
992 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
995 for (j = 0; i < ndmpdp; i++, j++) {
996 pdp_p[i] = DMPDphys + ptoa(j);
997 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_U;
1000 /* And recursively map PML4 to itself in order to get PTmap */
1001 p4_p = (pml4_entry_t *)KPML4phys;
1002 p4_p[PML4PML4I] = KPML4phys;
1003 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | PG_U;
1005 /* Connect the Direct Map slot(s) up to the PML4. */
1006 for (i = 0; i < ndmpdpphys; i++) {
1007 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
1008 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | PG_U;
1011 /* Connect the KVA slots up to the PML4 */
1012 for (i = 0; i < NKPML4E; i++) {
1013 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
1014 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V | PG_U;
1019 * Bootstrap the system enough to run with virtual memory.
1021 * On amd64 this is called after mapping has already been enabled
1022 * and just syncs the pmap module with what has already been done.
1023 * [We can't call it easily with mapping off since the kernel is not
1024 * mapped with PA == VA, hence we would have to relocate every address
1025 * from the linked base (virtual) address "KERNBASE" to the actual
1026 * (physical) address starting relative to 0]
1029 pmap_bootstrap(vm_paddr_t *firstaddr)
1039 * Create an initial set of page tables to run the kernel in.
1041 create_pagetables(firstaddr);
1044 * Add a physical memory segment (vm_phys_seg) corresponding to the
1045 * preallocated kernel page table pages so that vm_page structures
1046 * representing these pages will be created. The vm_page structures
1047 * are required for promotion of the corresponding kernel virtual
1048 * addresses to superpage mappings.
1050 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1052 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
1053 virtual_avail = pmap_kmem_choose(virtual_avail);
1055 virtual_end = VM_MAX_KERNEL_ADDRESS;
1058 /* XXX do %cr0 as well */
1059 load_cr4(rcr4() | CR4_PGE);
1060 load_cr3(KPML4phys);
1061 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1062 load_cr4(rcr4() | CR4_SMEP);
1065 * Initialize the kernel pmap (which is statically allocated).
1067 PMAP_LOCK_INIT(kernel_pmap);
1068 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1069 kernel_pmap->pm_cr3 = KPML4phys;
1070 kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
1071 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1072 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1073 kernel_pmap->pm_flags = pmap_flags;
1076 * Initialize the TLB invalidations generation number lock.
1078 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1081 * Reserve some special page table entries/VA space for temporary
1084 #define SYSMAP(c, p, v, n) \
1085 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1091 * Crashdump maps. The first page is reused as CMAP1 for the
1094 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1095 CADDR1 = crashdumpmap;
1100 * Initialize the PAT MSR.
1101 * pmap_init_pat() clears and sets CR4_PGE, which, as a
1102 * side-effect, invalidates stale PG_G TLB entries that might
1103 * have been created in our pre-boot environment.
1107 /* Initialize TLB Context Id. */
1108 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1109 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1110 /* Check for INVPCID support */
1111 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1113 for (i = 0; i < MAXCPU; i++) {
1114 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1115 kernel_pmap->pm_pcids[i].pm_gen = 1;
1117 __pcpu[0].pc_pcid_next = PMAP_PCID_KERN + 1;
1118 __pcpu[0].pc_pcid_gen = 1;
1120 * pcpu area for APs is zeroed during AP startup.
1121 * pc_pcid_next and pc_pcid_gen are initialized by AP
1122 * during pcpu setup.
1124 load_cr4(rcr4() | CR4_PCIDE);
1126 pmap_pcid_enabled = 0;
1131 * Setup the PAT MSR.
1136 int pat_table[PAT_INDEX_SIZE];
1141 /* Bail if this CPU doesn't implement PAT. */
1142 if ((cpu_feature & CPUID_PAT) == 0)
1145 /* Set default PAT index table. */
1146 for (i = 0; i < PAT_INDEX_SIZE; i++)
1148 pat_table[PAT_WRITE_BACK] = 0;
1149 pat_table[PAT_WRITE_THROUGH] = 1;
1150 pat_table[PAT_UNCACHEABLE] = 3;
1151 pat_table[PAT_WRITE_COMBINING] = 3;
1152 pat_table[PAT_WRITE_PROTECTED] = 3;
1153 pat_table[PAT_UNCACHED] = 3;
1155 /* Initialize default PAT entries. */
1156 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1157 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1158 PAT_VALUE(2, PAT_UNCACHED) |
1159 PAT_VALUE(3, PAT_UNCACHEABLE) |
1160 PAT_VALUE(4, PAT_WRITE_BACK) |
1161 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1162 PAT_VALUE(6, PAT_UNCACHED) |
1163 PAT_VALUE(7, PAT_UNCACHEABLE);
1167 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1168 * Program 5 and 6 as WP and WC.
1169 * Leave 4 and 7 as WB and UC.
1171 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1172 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1173 PAT_VALUE(6, PAT_WRITE_COMBINING);
1174 pat_table[PAT_UNCACHED] = 2;
1175 pat_table[PAT_WRITE_PROTECTED] = 5;
1176 pat_table[PAT_WRITE_COMBINING] = 6;
1179 * Just replace PAT Index 2 with WC instead of UC-.
1181 pat_msr &= ~PAT_MASK(2);
1182 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1183 pat_table[PAT_WRITE_COMBINING] = 2;
1188 load_cr4(cr4 & ~CR4_PGE);
1190 /* Disable caches (CD = 1, NW = 0). */
1192 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1194 /* Flushes caches and TLBs. */
1198 /* Update PAT and index table. */
1199 wrmsr(MSR_PAT, pat_msr);
1200 for (i = 0; i < PAT_INDEX_SIZE; i++)
1201 pat_index[i] = pat_table[i];
1203 /* Flush caches and TLBs again. */
1207 /* Restore caches and PGE. */
1213 * Initialize a vm_page's machine-dependent fields.
1216 pmap_page_init(vm_page_t m)
1219 TAILQ_INIT(&m->md.pv_list);
1220 m->md.pat_mode = PAT_WRITE_BACK;
1224 * Initialize the pmap module.
1225 * Called by vm_init, to initialize any structures that the pmap
1226 * system needs to map virtual memory.
1231 struct pmap_preinit_mapping *ppim;
1234 int error, i, pv_npg, ret, skz63;
1236 /* Detect bare-metal Skylake Server and Skylake-X. */
1237 if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
1238 CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
1240 * Skylake-X errata SKZ63. Processor May Hang When
1241 * Executing Code In an HLE Transaction Region between
1242 * 40000000H and 403FFFFFH.
1244 * Mark the pages in the range as preallocated. It
1245 * seems to be impossible to distinguish between
1246 * Skylake Server and Skylake X.
1249 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
1252 printf("SKZ63: skipping 4M RAM starting "
1253 "at physical 1G\n");
1254 for (i = 0; i < atop(0x400000); i++) {
1255 ret = vm_page_blacklist_add(0x40000000 +
1257 if (!ret && bootverbose)
1258 printf("page at %#lx already used\n",
1259 0x40000000 + ptoa(i));
1265 * Initialize the vm page array entries for the kernel pmap's
1268 for (i = 0; i < nkpt; i++) {
1269 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1270 KASSERT(mpte >= vm_page_array &&
1271 mpte < &vm_page_array[vm_page_array_size],
1272 ("pmap_init: page table page is out of range"));
1273 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1274 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1275 mpte->wire_count = 1;
1277 atomic_add_int(&vm_cnt.v_wire_count, nkpt);
1280 * If the kernel is running on a virtual machine, then it must assume
1281 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1282 * be prepared for the hypervisor changing the vendor and family that
1283 * are reported by CPUID. Consequently, the workaround for AMD Family
1284 * 10h Erratum 383 is enabled if the processor's feature set does not
1285 * include at least one feature that is only supported by older Intel
1286 * or newer AMD processors.
1288 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1289 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1290 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1292 workaround_erratum383 = 1;
1295 * Are large page mappings enabled?
1297 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1298 if (pg_ps_enabled) {
1299 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1300 ("pmap_init: can't assign to pagesizes[1]"));
1301 pagesizes[1] = NBPDR;
1305 * Initialize the pv chunk list mutex.
1307 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1310 * Initialize the pool of pv list locks.
1312 for (i = 0; i < NPV_LIST_LOCKS; i++)
1313 rw_init(&pv_list_locks[i], "pmap pv list");
1316 * Calculate the size of the pv head table for superpages.
1318 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1321 * Allocate memory for the pv head table for superpages.
1323 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1325 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1327 for (i = 0; i < pv_npg; i++)
1328 TAILQ_INIT(&pv_table[i].pv_list);
1329 TAILQ_INIT(&pv_dummy.pv_list);
1331 pmap_initialized = 1;
1332 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1333 ppim = pmap_preinit_mapping + i;
1336 /* Make the direct map consistent */
1337 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1338 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1339 ppim->sz, ppim->mode);
1343 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1344 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1347 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1348 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1349 (vmem_addr_t *)&qframe);
1351 panic("qframe allocation failed");
1354 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1355 "2MB page mapping counters");
1357 static u_long pmap_pde_demotions;
1358 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1359 &pmap_pde_demotions, 0, "2MB page demotions");
1361 static u_long pmap_pde_mappings;
1362 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1363 &pmap_pde_mappings, 0, "2MB page mappings");
1365 static u_long pmap_pde_p_failures;
1366 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1367 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1369 static u_long pmap_pde_promotions;
1370 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1371 &pmap_pde_promotions, 0, "2MB page promotions");
1373 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1374 "1GB page mapping counters");
1376 static u_long pmap_pdpe_demotions;
1377 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1378 &pmap_pdpe_demotions, 0, "1GB page demotions");
1380 /***************************************************
1381 * Low level helper routines.....
1382 ***************************************************/
1385 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1387 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1389 switch (pmap->pm_type) {
1392 /* Verify that both PAT bits are not set at the same time */
1393 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1394 ("Invalid PAT bits in entry %#lx", entry));
1396 /* Swap the PAT bits if one of them is set */
1397 if ((entry & x86_pat_bits) != 0)
1398 entry ^= x86_pat_bits;
1402 * Nothing to do - the memory attributes are represented
1403 * the same way for regular pages and superpages.
1407 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1414 * Determine the appropriate bits to set in a PTE or PDE for a specified
1418 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1420 int cache_bits, pat_flag, pat_idx;
1422 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1423 panic("Unknown caching mode %d\n", mode);
1425 switch (pmap->pm_type) {
1428 /* The PAT bit is different for PTE's and PDE's. */
1429 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1431 /* Map the caching mode to a PAT index. */
1432 pat_idx = pat_index[mode];
1434 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1437 cache_bits |= pat_flag;
1439 cache_bits |= PG_NC_PCD;
1441 cache_bits |= PG_NC_PWT;
1445 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1449 panic("unsupported pmap type %d", pmap->pm_type);
1452 return (cache_bits);
1456 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1460 switch (pmap->pm_type) {
1463 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1466 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1469 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1476 pmap_ps_enabled(pmap_t pmap)
1479 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1483 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1486 switch (pmap->pm_type) {
1493 * This is a little bogus since the generation number is
1494 * supposed to be bumped up when a region of the address
1495 * space is invalidated in the page tables.
1497 * In this case the old PDE entry is valid but yet we want
1498 * to make sure that any mappings using the old entry are
1499 * invalidated in the TLB.
1501 * The reason this works as expected is because we rendezvous
1502 * "all" host cpus and force any vcpu context to exit as a
1505 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1508 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1510 pde_store(pde, newpde);
1514 * After changing the page size for the specified virtual address in the page
1515 * table, flush the corresponding entries from the processor's TLB. Only the
1516 * calling processor's TLB is affected.
1518 * The calling thread must be pinned to a processor.
1521 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1525 if (pmap_type_guest(pmap))
1528 KASSERT(pmap->pm_type == PT_X86,
1529 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1531 PG_G = pmap_global_bit(pmap);
1533 if ((newpde & PG_PS) == 0)
1534 /* Demotion: flush a specific 2MB page mapping. */
1536 else if ((newpde & PG_G) == 0)
1538 * Promotion: flush every 4KB page mapping from the TLB
1539 * because there are too many to flush individually.
1544 * Promotion: flush every 4KB page mapping from the TLB,
1545 * including any global (PG_G) mappings.
1553 * For SMP, these functions have to use the IPI mechanism for coherence.
1555 * N.B.: Before calling any of the following TLB invalidation functions,
1556 * the calling processor must ensure that all stores updating a non-
1557 * kernel page table are globally performed. Otherwise, another
1558 * processor could cache an old, pre-update entry without being
1559 * invalidated. This can happen one of two ways: (1) The pmap becomes
1560 * active on another processor after its pm_active field is checked by
1561 * one of the following functions but before a store updating the page
1562 * table is globally performed. (2) The pmap becomes active on another
1563 * processor before its pm_active field is checked but due to
1564 * speculative loads one of the following functions stills reads the
1565 * pmap as inactive on the other processor.
1567 * The kernel page table is exempt because its pm_active field is
1568 * immutable. The kernel page table is always active on every
1573 * Interrupt the cpus that are executing in the guest context.
1574 * This will force the vcpu to exit and the cached EPT mappings
1575 * will be invalidated by the host before the next vmresume.
1577 static __inline void
1578 pmap_invalidate_ept(pmap_t pmap)
1583 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1584 ("pmap_invalidate_ept: absurd pm_active"));
1587 * The TLB mappings associated with a vcpu context are not
1588 * flushed each time a different vcpu is chosen to execute.
1590 * This is in contrast with a process's vtop mappings that
1591 * are flushed from the TLB on each context switch.
1593 * Therefore we need to do more than just a TLB shootdown on
1594 * the active cpus in 'pmap->pm_active'. To do this we keep
1595 * track of the number of invalidations performed on this pmap.
1597 * Each vcpu keeps a cache of this counter and compares it
1598 * just before a vmresume. If the counter is out-of-date an
1599 * invept will be done to flush stale mappings from the TLB.
1601 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1604 * Force the vcpu to exit and trap back into the hypervisor.
1606 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1607 ipi_selected(pmap->pm_active, ipinum);
1612 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1615 struct invpcid_descr d;
1616 uint64_t kcr3, ucr3;
1620 if (pmap_type_guest(pmap)) {
1621 pmap_invalidate_ept(pmap);
1625 KASSERT(pmap->pm_type == PT_X86,
1626 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1629 if (pmap == kernel_pmap) {
1633 cpuid = PCPU_GET(cpuid);
1634 if (pmap == PCPU_GET(curpmap)) {
1636 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1638 * Disable context switching. pm_pcid
1639 * is recalculated on switch, which
1640 * might make us use wrong pcid below.
1643 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1645 if (invpcid_works) {
1646 d.pcid = pcid | PMAP_PCID_USER_PT;
1649 invpcid(&d, INVPCID_ADDR);
1651 kcr3 = pmap->pm_cr3 | pcid |
1653 ucr3 = pmap->pm_ucr3 | pcid |
1654 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1655 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1659 } else if (pmap_pcid_enabled)
1660 pmap->pm_pcids[cpuid].pm_gen = 0;
1661 if (pmap_pcid_enabled) {
1664 pmap->pm_pcids[i].pm_gen = 0;
1667 mask = &pmap->pm_active;
1669 smp_masked_invlpg(*mask, va, pmap);
1673 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1674 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1677 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1680 struct invpcid_descr d;
1682 uint64_t kcr3, ucr3;
1686 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1687 pmap_invalidate_all(pmap);
1691 if (pmap_type_guest(pmap)) {
1692 pmap_invalidate_ept(pmap);
1696 KASSERT(pmap->pm_type == PT_X86,
1697 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1700 cpuid = PCPU_GET(cpuid);
1701 if (pmap == kernel_pmap) {
1702 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1706 if (pmap == PCPU_GET(curpmap)) {
1707 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1709 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1711 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1712 if (invpcid_works) {
1713 d.pcid = pcid | PMAP_PCID_USER_PT;
1716 for (; d.addr < eva; d.addr +=
1718 invpcid(&d, INVPCID_ADDR);
1720 kcr3 = pmap->pm_cr3 | pcid |
1722 ucr3 = pmap->pm_ucr3 | pcid |
1723 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1724 pmap_pti_pcid_invlrng(ucr3, kcr3, sva,
1729 } else if (pmap_pcid_enabled) {
1730 pmap->pm_pcids[cpuid].pm_gen = 0;
1732 if (pmap_pcid_enabled) {
1735 pmap->pm_pcids[i].pm_gen = 0;
1738 mask = &pmap->pm_active;
1740 smp_masked_invlpg_range(*mask, sva, eva, pmap);
1745 pmap_invalidate_all(pmap_t pmap)
1748 struct invpcid_descr d;
1749 uint64_t kcr3, ucr3;
1753 if (pmap_type_guest(pmap)) {
1754 pmap_invalidate_ept(pmap);
1758 KASSERT(pmap->pm_type == PT_X86,
1759 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1762 if (pmap == kernel_pmap) {
1763 if (pmap_pcid_enabled && invpcid_works) {
1764 bzero(&d, sizeof(d));
1765 invpcid(&d, INVPCID_CTXGLOB);
1771 cpuid = PCPU_GET(cpuid);
1772 if (pmap == PCPU_GET(curpmap)) {
1773 if (pmap_pcid_enabled) {
1775 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1776 if (invpcid_works) {
1780 invpcid(&d, INVPCID_CTX);
1781 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1782 d.pcid |= PMAP_PCID_USER_PT;
1783 invpcid(&d, INVPCID_CTX);
1786 kcr3 = pmap->pm_cr3 | pcid;
1787 ucr3 = pmap->pm_ucr3;
1788 if (ucr3 != PMAP_NO_CR3) {
1789 ucr3 |= pcid | PMAP_PCID_USER_PT;
1790 pmap_pti_pcid_invalidate(ucr3,
1800 } else if (pmap_pcid_enabled) {
1801 pmap->pm_pcids[cpuid].pm_gen = 0;
1803 if (pmap_pcid_enabled) {
1806 pmap->pm_pcids[i].pm_gen = 0;
1809 mask = &pmap->pm_active;
1811 smp_masked_invltlb(*mask, pmap);
1816 pmap_invalidate_cache(void)
1826 cpuset_t invalidate; /* processors that invalidate their TLB */
1831 u_int store; /* processor that updates the PDE */
1835 pmap_update_pde_action(void *arg)
1837 struct pde_action *act = arg;
1839 if (act->store == PCPU_GET(cpuid))
1840 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1844 pmap_update_pde_teardown(void *arg)
1846 struct pde_action *act = arg;
1848 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1849 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1853 * Change the page size for the specified virtual address in a way that
1854 * prevents any possibility of the TLB ever having two entries that map the
1855 * same virtual address using different page sizes. This is the recommended
1856 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1857 * machine check exception for a TLB state that is improperly diagnosed as a
1861 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1863 struct pde_action act;
1864 cpuset_t active, other_cpus;
1868 cpuid = PCPU_GET(cpuid);
1869 other_cpus = all_cpus;
1870 CPU_CLR(cpuid, &other_cpus);
1871 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1874 active = pmap->pm_active;
1876 if (CPU_OVERLAP(&active, &other_cpus)) {
1878 act.invalidate = active;
1882 act.newpde = newpde;
1883 CPU_SET(cpuid, &active);
1884 smp_rendezvous_cpus(active,
1885 smp_no_rendezvous_barrier, pmap_update_pde_action,
1886 pmap_update_pde_teardown, &act);
1888 pmap_update_pde_store(pmap, pde, newpde);
1889 if (CPU_ISSET(cpuid, &active))
1890 pmap_update_pde_invalidate(pmap, va, newpde);
1896 * Normal, non-SMP, invalidation functions.
1899 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1901 struct invpcid_descr d;
1902 uint64_t kcr3, ucr3;
1905 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1909 KASSERT(pmap->pm_type == PT_X86,
1910 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1912 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1914 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
1915 pmap->pm_ucr3 != PMAP_NO_CR3) {
1917 pcid = pmap->pm_pcids[0].pm_pcid;
1918 if (invpcid_works) {
1919 d.pcid = pcid | PMAP_PCID_USER_PT;
1922 invpcid(&d, INVPCID_ADDR);
1924 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
1925 ucr3 = pmap->pm_ucr3 | pcid |
1926 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1927 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1931 } else if (pmap_pcid_enabled)
1932 pmap->pm_pcids[0].pm_gen = 0;
1936 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1938 struct invpcid_descr d;
1940 uint64_t kcr3, ucr3;
1942 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1946 KASSERT(pmap->pm_type == PT_X86,
1947 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1949 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1950 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1952 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
1953 pmap->pm_ucr3 != PMAP_NO_CR3) {
1955 if (invpcid_works) {
1956 d.pcid = pmap->pm_pcids[0].pm_pcid |
1960 for (; d.addr < eva; d.addr += PAGE_SIZE)
1961 invpcid(&d, INVPCID_ADDR);
1963 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].
1964 pm_pcid | CR3_PCID_SAVE;
1965 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[0].
1966 pm_pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1967 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
1971 } else if (pmap_pcid_enabled) {
1972 pmap->pm_pcids[0].pm_gen = 0;
1977 pmap_invalidate_all(pmap_t pmap)
1979 struct invpcid_descr d;
1980 uint64_t kcr3, ucr3;
1982 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1986 KASSERT(pmap->pm_type == PT_X86,
1987 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
1989 if (pmap == kernel_pmap) {
1990 if (pmap_pcid_enabled && invpcid_works) {
1991 bzero(&d, sizeof(d));
1992 invpcid(&d, INVPCID_CTXGLOB);
1996 } else if (pmap == PCPU_GET(curpmap)) {
1997 if (pmap_pcid_enabled) {
1999 if (invpcid_works) {
2000 d.pcid = pmap->pm_pcids[0].pm_pcid;
2003 invpcid(&d, INVPCID_CTX);
2004 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2005 d.pcid |= PMAP_PCID_USER_PT;
2006 invpcid(&d, INVPCID_CTX);
2009 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].pm_pcid;
2010 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2011 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[
2012 0].pm_pcid | PMAP_PCID_USER_PT;
2013 pmap_pti_pcid_invalidate(ucr3, kcr3);
2021 } else if (pmap_pcid_enabled) {
2022 pmap->pm_pcids[0].pm_gen = 0;
2027 pmap_invalidate_cache(void)
2034 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
2037 pmap_update_pde_store(pmap, pde, newpde);
2038 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
2039 pmap_update_pde_invalidate(pmap, va, newpde);
2041 pmap->pm_pcids[0].pm_gen = 0;
2046 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
2050 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
2051 * by a promotion that did not invalidate the 512 4KB page mappings
2052 * that might exist in the TLB. Consequently, at this point, the TLB
2053 * may hold both 4KB and 2MB page mappings for the address range [va,
2054 * va + NBPDR). Therefore, the entire range must be invalidated here.
2055 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
2056 * 4KB page mappings for the address range [va, va + NBPDR), and so a
2057 * single INVLPG suffices to invalidate the 2MB page mapping from the
2060 if ((pde & PG_PROMOTED) != 0)
2061 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
2063 pmap_invalidate_page(pmap, va);
2066 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
2069 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
2073 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
2075 KASSERT((sva & PAGE_MASK) == 0,
2076 ("pmap_invalidate_cache_range: sva not page-aligned"));
2077 KASSERT((eva & PAGE_MASK) == 0,
2078 ("pmap_invalidate_cache_range: eva not page-aligned"));
2081 if ((cpu_feature & CPUID_SS) != 0 && !force)
2082 ; /* If "Self Snoop" is supported and allowed, do nothing. */
2083 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
2084 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2086 * XXX: Some CPUs fault, hang, or trash the local APIC
2087 * registers if we use CLFLUSH on the local APIC
2088 * range. The local APIC is always uncached, so we
2089 * don't need to flush for that range anyway.
2091 if (pmap_kextract(sva) == lapic_paddr)
2095 * Otherwise, do per-cache line flush. Use the sfence
2096 * instruction to insure that previous stores are
2097 * included in the write-back. The processor
2098 * propagates flush to other processors in the cache
2102 for (; sva < eva; sva += cpu_clflush_line_size)
2105 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
2106 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2107 if (pmap_kextract(sva) == lapic_paddr)
2110 * Writes are ordered by CLFLUSH on Intel CPUs.
2112 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2114 for (; sva < eva; sva += cpu_clflush_line_size)
2116 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2121 * No targeted cache flush methods are supported by CPU,
2122 * or the supplied range is bigger than 2MB.
2123 * Globally invalidate cache.
2125 pmap_invalidate_cache();
2130 * Remove the specified set of pages from the data and instruction caches.
2132 * In contrast to pmap_invalidate_cache_range(), this function does not
2133 * rely on the CPU's self-snoop feature, because it is intended for use
2134 * when moving pages into a different cache domain.
2137 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
2139 vm_offset_t daddr, eva;
2143 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
2144 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
2145 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
2146 pmap_invalidate_cache();
2150 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2152 for (i = 0; i < count; i++) {
2153 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
2154 eva = daddr + PAGE_SIZE;
2155 for (; daddr < eva; daddr += cpu_clflush_line_size) {
2164 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2170 * Routine: pmap_extract
2172 * Extract the physical page address associated
2173 * with the given map/virtual_address pair.
2176 pmap_extract(pmap_t pmap, vm_offset_t va)
2180 pt_entry_t *pte, PG_V;
2184 PG_V = pmap_valid_bit(pmap);
2186 pdpe = pmap_pdpe(pmap, va);
2187 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2188 if ((*pdpe & PG_PS) != 0)
2189 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
2191 pde = pmap_pdpe_to_pde(pdpe, va);
2192 if ((*pde & PG_V) != 0) {
2193 if ((*pde & PG_PS) != 0) {
2194 pa = (*pde & PG_PS_FRAME) |
2197 pte = pmap_pde_to_pte(pde, va);
2198 pa = (*pte & PG_FRAME) |
2209 * Routine: pmap_extract_and_hold
2211 * Atomically extract and hold the physical page
2212 * with the given pmap and virtual address pair
2213 * if that mapping permits the given protection.
2216 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
2218 pd_entry_t pde, *pdep;
2219 pt_entry_t pte, PG_RW, PG_V;
2225 PG_RW = pmap_rw_bit(pmap);
2226 PG_V = pmap_valid_bit(pmap);
2229 pdep = pmap_pde(pmap, va);
2230 if (pdep != NULL && (pde = *pdep)) {
2232 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2233 if (vm_page_pa_tryrelock(pmap, (pde &
2234 PG_PS_FRAME) | (va & PDRMASK), &pa))
2236 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
2241 pte = *pmap_pde_to_pte(pdep, va);
2243 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2244 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2247 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
2258 pmap_kextract(vm_offset_t va)
2263 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2264 pa = DMAP_TO_PHYS(va);
2268 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2271 * Beware of a concurrent promotion that changes the
2272 * PDE at this point! For example, vtopte() must not
2273 * be used to access the PTE because it would use the
2274 * new PDE. It is, however, safe to use the old PDE
2275 * because the page table page is preserved by the
2278 pa = *pmap_pde_to_pte(&pde, va);
2279 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2285 /***************************************************
2286 * Low level mapping routines.....
2287 ***************************************************/
2290 * Add a wired page to the kva.
2291 * Note: not SMP coherent.
2294 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2299 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g);
2302 static __inline void
2303 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2309 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2310 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | cache_bits);
2314 * Remove a page from the kernel pagetables.
2315 * Note: not SMP coherent.
2318 pmap_kremove(vm_offset_t va)
2327 * Used to map a range of physical addresses into kernel
2328 * virtual address space.
2330 * The value passed in '*virt' is a suggested virtual address for
2331 * the mapping. Architectures which can support a direct-mapped
2332 * physical to virtual region can return the appropriate address
2333 * within that region, leaving '*virt' unchanged. Other
2334 * architectures should map the pages starting at '*virt' and
2335 * update '*virt' with the first usable address after the mapped
2339 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2341 return PHYS_TO_DMAP(start);
2346 * Add a list of wired pages to the kva
2347 * this routine is only used for temporary
2348 * kernel mappings that do not need to have
2349 * page modification or references recorded.
2350 * Note that old mappings are simply written
2351 * over. The page *must* be wired.
2352 * Note: SMP coherent. Uses a ranged shootdown IPI.
2355 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2357 pt_entry_t *endpte, oldpte, pa, *pte;
2363 endpte = pte + count;
2364 while (pte < endpte) {
2366 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2367 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2368 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2370 pte_store(pte, pa | pg_g | X86_PG_RW | X86_PG_V);
2374 if (__predict_false((oldpte & X86_PG_V) != 0))
2375 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2380 * This routine tears out page mappings from the
2381 * kernel -- it is meant only for temporary mappings.
2382 * Note: SMP coherent. Uses a ranged shootdown IPI.
2385 pmap_qremove(vm_offset_t sva, int count)
2390 while (count-- > 0) {
2391 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2395 pmap_invalidate_range(kernel_pmap, sva, va);
2398 /***************************************************
2399 * Page table page management routines.....
2400 ***************************************************/
2401 static __inline void
2402 pmap_free_zero_pages(struct spglist *free)
2407 for (count = 0; (m = SLIST_FIRST(free)) != NULL; count++) {
2408 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2409 /* Preserve the page's PG_ZERO setting. */
2410 vm_page_free_toq(m);
2412 atomic_subtract_int(&vm_cnt.v_wire_count, count);
2416 * Schedule the specified unused page table page to be freed. Specifically,
2417 * add the page to the specified list of pages that will be released to the
2418 * physical memory manager after the TLB has been updated.
2420 static __inline void
2421 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2422 boolean_t set_PG_ZERO)
2426 m->flags |= PG_ZERO;
2428 m->flags &= ~PG_ZERO;
2429 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2433 * Inserts the specified page table page into the specified pmap's collection
2434 * of idle page table pages. Each of a pmap's page table pages is responsible
2435 * for mapping a distinct range of virtual addresses. The pmap's collection is
2436 * ordered by this virtual address range.
2439 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2442 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2443 return (vm_radix_insert(&pmap->pm_root, mpte));
2447 * Removes the page table page mapping the specified virtual address from the
2448 * specified pmap's collection of idle page table pages, and returns it.
2449 * Otherwise, returns NULL if there is no page table page corresponding to the
2450 * specified virtual address.
2452 static __inline vm_page_t
2453 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
2456 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2457 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
2461 * Decrements a page table page's wire count, which is used to record the
2462 * number of valid page table entries within the page. If the wire count
2463 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2464 * page table page was unmapped and FALSE otherwise.
2466 static inline boolean_t
2467 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2471 if (m->wire_count == 0) {
2472 _pmap_unwire_ptp(pmap, va, m, free);
2479 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2482 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2484 * unmap the page table page
2486 if (m->pindex >= (NUPDE + NUPDPE)) {
2489 pml4 = pmap_pml4e(pmap, va);
2491 if (pmap->pm_pml4u != NULL && va <= VM_MAXUSER_ADDRESS) {
2492 pml4 = &pmap->pm_pml4u[pmap_pml4e_index(va)];
2495 } else if (m->pindex >= NUPDE) {
2498 pdp = pmap_pdpe(pmap, va);
2503 pd = pmap_pde(pmap, va);
2506 pmap_resident_count_dec(pmap, 1);
2507 if (m->pindex < NUPDE) {
2508 /* We just released a PT, unhold the matching PD */
2511 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2512 pmap_unwire_ptp(pmap, va, pdpg, free);
2514 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2515 /* We just released a PD, unhold the matching PDP */
2518 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2519 pmap_unwire_ptp(pmap, va, pdppg, free);
2523 * Put page on a list so that it is released after
2524 * *ALL* TLB shootdown is done
2526 pmap_add_delayed_free_list(m, free, TRUE);
2530 * After removing a page table entry, this routine is used to
2531 * conditionally free the page, and manage the hold/wire counts.
2534 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2535 struct spglist *free)
2539 if (va >= VM_MAXUSER_ADDRESS)
2541 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2542 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2543 return (pmap_unwire_ptp(pmap, va, mpte, free));
2547 pmap_pinit0(pmap_t pmap)
2551 PMAP_LOCK_INIT(pmap);
2552 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2553 pmap->pm_pml4u = NULL;
2554 pmap->pm_cr3 = KPML4phys;
2555 /* hack to keep pmap_pti_pcid_invalidate() alive */
2556 pmap->pm_ucr3 = PMAP_NO_CR3;
2557 pmap->pm_root.rt_root = 0;
2558 CPU_ZERO(&pmap->pm_active);
2559 TAILQ_INIT(&pmap->pm_pvchunk);
2560 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2561 pmap->pm_flags = pmap_flags;
2563 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2564 pmap->pm_pcids[i].pm_gen = 0;
2566 __pcpu[i].pc_kcr3 = PMAP_NO_CR3;
2568 PCPU_SET(curpmap, kernel_pmap);
2569 pmap_activate(curthread);
2570 CPU_FILL(&kernel_pmap->pm_active);
2574 pmap_pinit_pml4(vm_page_t pml4pg)
2576 pml4_entry_t *pm_pml4;
2579 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2581 /* Wire in kernel global address entries. */
2582 for (i = 0; i < NKPML4E; i++) {
2583 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2586 for (i = 0; i < ndmpdpphys; i++) {
2587 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2591 /* install self-referential address mapping entry(s) */
2592 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2593 X86_PG_A | X86_PG_M;
2597 pmap_pinit_pml4_pti(vm_page_t pml4pg)
2599 pml4_entry_t *pm_pml4;
2602 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2603 for (i = 0; i < NPML4EPG; i++)
2604 pm_pml4[i] = pti_pml4[i];
2608 * Initialize a preallocated and zeroed pmap structure,
2609 * such as one in a vmspace structure.
2612 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2614 vm_page_t pml4pg, pml4pgu;
2615 vm_paddr_t pml4phys;
2619 * allocate the page directory page
2621 pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
2622 VM_ALLOC_WIRED | VM_ALLOC_ZERO | VM_ALLOC_WAITOK);
2624 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2625 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2627 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2628 pmap->pm_pcids[i].pm_gen = 0;
2630 pmap->pm_cr3 = PMAP_NO_CR3; /* initialize to an invalid value */
2631 pmap->pm_ucr3 = PMAP_NO_CR3;
2632 pmap->pm_pml4u = NULL;
2634 pmap->pm_type = pm_type;
2635 if ((pml4pg->flags & PG_ZERO) == 0)
2636 pagezero(pmap->pm_pml4);
2639 * Do not install the host kernel mappings in the nested page
2640 * tables. These mappings are meaningless in the guest physical
2642 * Install minimal kernel mappings in PTI case.
2644 if (pm_type == PT_X86) {
2645 pmap->pm_cr3 = pml4phys;
2646 pmap_pinit_pml4(pml4pg);
2648 pml4pgu = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2649 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2650 pmap->pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(
2651 VM_PAGE_TO_PHYS(pml4pgu));
2652 pmap_pinit_pml4_pti(pml4pgu);
2653 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pml4pgu);
2657 pmap->pm_root.rt_root = 0;
2658 CPU_ZERO(&pmap->pm_active);
2659 TAILQ_INIT(&pmap->pm_pvchunk);
2660 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2661 pmap->pm_flags = flags;
2662 pmap->pm_eptgen = 0;
2668 pmap_pinit(pmap_t pmap)
2671 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2675 * This routine is called if the desired page table page does not exist.
2677 * If page table page allocation fails, this routine may sleep before
2678 * returning NULL. It sleeps only if a lock pointer was given.
2680 * Note: If a page allocation fails at page table level two or three,
2681 * one or two pages may be held during the wait, only to be released
2682 * afterwards. This conservative approach is easily argued to avoid
2686 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2688 vm_page_t m, pdppg, pdpg;
2689 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2691 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2693 PG_A = pmap_accessed_bit(pmap);
2694 PG_M = pmap_modified_bit(pmap);
2695 PG_V = pmap_valid_bit(pmap);
2696 PG_RW = pmap_rw_bit(pmap);
2699 * Allocate a page table page.
2701 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2702 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2703 if (lockp != NULL) {
2704 RELEASE_PV_LIST_LOCK(lockp);
2706 PMAP_ASSERT_NOT_IN_DI();
2712 * Indicate the need to retry. While waiting, the page table
2713 * page may have been allocated.
2717 if ((m->flags & PG_ZERO) == 0)
2721 * Map the pagetable page into the process address space, if
2722 * it isn't already there.
2725 if (ptepindex >= (NUPDE + NUPDPE)) {
2726 pml4_entry_t *pml4, *pml4u;
2727 vm_pindex_t pml4index;
2729 /* Wire up a new PDPE page */
2730 pml4index = ptepindex - (NUPDE + NUPDPE);
2731 pml4 = &pmap->pm_pml4[pml4index];
2732 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2733 if (pmap->pm_pml4u != NULL && pml4index < NUPML4E) {
2735 * PTI: Make all user-space mappings in the
2736 * kernel-mode page table no-execute so that
2737 * we detect any programming errors that leave
2738 * the kernel-mode page table active on return
2743 pml4u = &pmap->pm_pml4u[pml4index];
2744 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
2748 } else if (ptepindex >= NUPDE) {
2749 vm_pindex_t pml4index;
2750 vm_pindex_t pdpindex;
2754 /* Wire up a new PDE page */
2755 pdpindex = ptepindex - NUPDE;
2756 pml4index = pdpindex >> NPML4EPGSHIFT;
2758 pml4 = &pmap->pm_pml4[pml4index];
2759 if ((*pml4 & PG_V) == 0) {
2760 /* Have to allocate a new pdp, recurse */
2761 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2764 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2765 vm_page_free_zero(m);
2769 /* Add reference to pdp page */
2770 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2771 pdppg->wire_count++;
2773 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2775 /* Now find the pdp page */
2776 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2777 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2780 vm_pindex_t pml4index;
2781 vm_pindex_t pdpindex;
2786 /* Wire up a new PTE page */
2787 pdpindex = ptepindex >> NPDPEPGSHIFT;
2788 pml4index = pdpindex >> NPML4EPGSHIFT;
2790 /* First, find the pdp and check that its valid. */
2791 pml4 = &pmap->pm_pml4[pml4index];
2792 if ((*pml4 & PG_V) == 0) {
2793 /* Have to allocate a new pd, recurse */
2794 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2797 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2798 vm_page_free_zero(m);
2801 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2802 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2804 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2805 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2806 if ((*pdp & PG_V) == 0) {
2807 /* Have to allocate a new pd, recurse */
2808 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2811 atomic_subtract_int(&vm_cnt.v_wire_count,
2813 vm_page_free_zero(m);
2817 /* Add reference to the pd page */
2818 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2822 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2824 /* Now we know where the page directory page is */
2825 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2826 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2829 pmap_resident_count_inc(pmap, 1);
2835 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2837 vm_pindex_t pdpindex, ptepindex;
2838 pdp_entry_t *pdpe, PG_V;
2841 PG_V = pmap_valid_bit(pmap);
2844 pdpe = pmap_pdpe(pmap, va);
2845 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2846 /* Add a reference to the pd page. */
2847 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2850 /* Allocate a pd page. */
2851 ptepindex = pmap_pde_pindex(va);
2852 pdpindex = ptepindex >> NPDPEPGSHIFT;
2853 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2854 if (pdpg == NULL && lockp != NULL)
2861 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2863 vm_pindex_t ptepindex;
2864 pd_entry_t *pd, PG_V;
2867 PG_V = pmap_valid_bit(pmap);
2870 * Calculate pagetable page index
2872 ptepindex = pmap_pde_pindex(va);
2875 * Get the page directory entry
2877 pd = pmap_pde(pmap, va);
2880 * This supports switching from a 2MB page to a
2883 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2884 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2886 * Invalidation of the 2MB page mapping may have caused
2887 * the deallocation of the underlying PD page.
2894 * If the page table page is mapped, we just increment the
2895 * hold count, and activate it.
2897 if (pd != NULL && (*pd & PG_V) != 0) {
2898 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2902 * Here if the pte page isn't mapped, or if it has been
2905 m = _pmap_allocpte(pmap, ptepindex, lockp);
2906 if (m == NULL && lockp != NULL)
2913 /***************************************************
2914 * Pmap allocation/deallocation routines.
2915 ***************************************************/
2918 * Release any resources held by the given physical map.
2919 * Called when a pmap initialized by pmap_pinit is being released.
2920 * Should only be called if the map contains no valid mappings.
2923 pmap_release(pmap_t pmap)
2928 KASSERT(pmap->pm_stats.resident_count == 0,
2929 ("pmap_release: pmap resident count %ld != 0",
2930 pmap->pm_stats.resident_count));
2931 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2932 ("pmap_release: pmap has reserved page table page(s)"));
2933 KASSERT(CPU_EMPTY(&pmap->pm_active),
2934 ("releasing active pmap %p", pmap));
2936 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2938 for (i = 0; i < NKPML4E; i++) /* KVA */
2939 pmap->pm_pml4[KPML4BASE + i] = 0;
2940 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
2941 pmap->pm_pml4[DMPML4I + i] = 0;
2942 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
2945 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2946 vm_page_free_zero(m);
2948 if (pmap->pm_pml4u != NULL) {
2949 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4u));
2951 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2957 kvm_size(SYSCTL_HANDLER_ARGS)
2959 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2961 return sysctl_handle_long(oidp, &ksize, 0, req);
2963 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2964 0, 0, kvm_size, "LU", "Size of KVM");
2967 kvm_free(SYSCTL_HANDLER_ARGS)
2969 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2971 return sysctl_handle_long(oidp, &kfree, 0, req);
2973 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2974 0, 0, kvm_free, "LU", "Amount of KVM free");
2977 * grow the number of kernel page table entries, if needed
2980 pmap_growkernel(vm_offset_t addr)
2984 pd_entry_t *pde, newpdir;
2987 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2990 * Return if "addr" is within the range of kernel page table pages
2991 * that were preallocated during pmap bootstrap. Moreover, leave
2992 * "kernel_vm_end" and the kernel page table as they were.
2994 * The correctness of this action is based on the following
2995 * argument: vm_map_insert() allocates contiguous ranges of the
2996 * kernel virtual address space. It calls this function if a range
2997 * ends after "kernel_vm_end". If the kernel is mapped between
2998 * "kernel_vm_end" and "addr", then the range cannot begin at
2999 * "kernel_vm_end". In fact, its beginning address cannot be less
3000 * than the kernel. Thus, there is no immediate need to allocate
3001 * any new kernel page table pages between "kernel_vm_end" and
3004 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
3007 addr = roundup2(addr, NBPDR);
3008 if (addr - 1 >= kernel_map->max_offset)
3009 addr = kernel_map->max_offset;
3010 while (kernel_vm_end < addr) {
3011 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
3012 if ((*pdpe & X86_PG_V) == 0) {
3013 /* We need a new PDP entry */
3014 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
3015 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
3016 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
3018 panic("pmap_growkernel: no memory to grow kernel");
3019 if ((nkpg->flags & PG_ZERO) == 0)
3020 pmap_zero_page(nkpg);
3021 paddr = VM_PAGE_TO_PHYS(nkpg);
3022 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
3023 X86_PG_A | X86_PG_M);
3024 continue; /* try again */
3026 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
3027 if ((*pde & X86_PG_V) != 0) {
3028 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3029 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
3030 kernel_vm_end = kernel_map->max_offset;
3036 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
3037 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
3040 panic("pmap_growkernel: no memory to grow kernel");
3041 if ((nkpg->flags & PG_ZERO) == 0)
3042 pmap_zero_page(nkpg);
3043 paddr = VM_PAGE_TO_PHYS(nkpg);
3044 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
3045 pde_store(pde, newpdir);
3047 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3048 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
3049 kernel_vm_end = kernel_map->max_offset;
3056 /***************************************************
3057 * page management routines.
3058 ***************************************************/
3060 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
3061 CTASSERT(_NPCM == 3);
3062 CTASSERT(_NPCPV == 168);
3064 static __inline struct pv_chunk *
3065 pv_to_chunk(pv_entry_t pv)
3068 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
3071 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
3073 #define PC_FREE0 0xfffffffffffffffful
3074 #define PC_FREE1 0xfffffffffffffffful
3075 #define PC_FREE2 0x000000fffffffffful
3077 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
3080 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
3082 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
3083 "Current number of pv entry chunks");
3084 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
3085 "Current number of pv entry chunks allocated");
3086 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
3087 "Current number of pv entry chunks frees");
3088 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
3089 "Number of times tried to get a chunk page but failed.");
3091 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
3092 static int pv_entry_spare;
3094 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
3095 "Current number of pv entry frees");
3096 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
3097 "Current number of pv entry allocs");
3098 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
3099 "Current number of pv entries");
3100 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
3101 "Current number of spare pv entries");
3105 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
3110 pmap_invalidate_all(pmap);
3111 if (pmap != locked_pmap)
3114 pmap_delayed_invl_finished();
3118 * We are in a serious low memory condition. Resort to
3119 * drastic measures to free some pages so we can allocate
3120 * another pv entry chunk.
3122 * Returns NULL if PV entries were reclaimed from the specified pmap.
3124 * We do not, however, unmap 2mpages because subsequent accesses will
3125 * allocate per-page pv entries until repromotion occurs, thereby
3126 * exacerbating the shortage of free pv entries.
3129 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
3131 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
3132 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
3133 struct md_page *pvh;
3135 pmap_t next_pmap, pmap;
3136 pt_entry_t *pte, tpte;
3137 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3141 struct spglist free;
3143 int bit, field, freed;
3145 static int active_reclaims = 0;
3147 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
3148 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
3151 PG_G = PG_A = PG_M = PG_RW = 0;
3153 bzero(&pc_marker_b, sizeof(pc_marker_b));
3154 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
3155 pc_marker = (struct pv_chunk *)&pc_marker_b;
3156 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
3159 * A delayed invalidation block should already be active if
3160 * pmap_advise() or pmap_remove() called this function by way
3161 * of pmap_demote_pde_locked().
3163 start_di = pmap_not_in_di();
3165 mtx_lock(&pv_chunks_mutex);
3167 TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
3168 TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
3169 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
3170 SLIST_EMPTY(&free)) {
3171 next_pmap = pc->pc_pmap;
3172 if (next_pmap == NULL) {
3174 * The next chunk is a marker. However, it is
3175 * not our marker, so active_reclaims must be
3176 * > 1. Consequently, the next_chunk code
3177 * will not rotate the pv_chunks list.
3181 mtx_unlock(&pv_chunks_mutex);
3184 * A pv_chunk can only be removed from the pc_lru list
3185 * when both pc_chunks_mutex is owned and the
3186 * corresponding pmap is locked.
3188 if (pmap != next_pmap) {
3189 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
3192 /* Avoid deadlock and lock recursion. */
3193 if (pmap > locked_pmap) {
3194 RELEASE_PV_LIST_LOCK(lockp);
3197 pmap_delayed_invl_started();
3198 mtx_lock(&pv_chunks_mutex);
3200 } else if (pmap != locked_pmap) {
3201 if (PMAP_TRYLOCK(pmap)) {
3203 pmap_delayed_invl_started();
3204 mtx_lock(&pv_chunks_mutex);
3207 pmap = NULL; /* pmap is not locked */
3208 mtx_lock(&pv_chunks_mutex);
3209 pc = TAILQ_NEXT(pc_marker, pc_lru);
3211 pc->pc_pmap != next_pmap)
3215 } else if (start_di)
3216 pmap_delayed_invl_started();
3217 PG_G = pmap_global_bit(pmap);
3218 PG_A = pmap_accessed_bit(pmap);
3219 PG_M = pmap_modified_bit(pmap);
3220 PG_RW = pmap_rw_bit(pmap);
3224 * Destroy every non-wired, 4 KB page mapping in the chunk.
3227 for (field = 0; field < _NPCM; field++) {
3228 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
3229 inuse != 0; inuse &= ~(1UL << bit)) {
3231 pv = &pc->pc_pventry[field * 64 + bit];
3233 pde = pmap_pde(pmap, va);
3234 if ((*pde & PG_PS) != 0)
3236 pte = pmap_pde_to_pte(pde, va);
3237 if ((*pte & PG_W) != 0)
3239 tpte = pte_load_clear(pte);
3240 if ((tpte & PG_G) != 0)
3241 pmap_invalidate_page(pmap, va);
3242 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3243 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3245 if ((tpte & PG_A) != 0)
3246 vm_page_aflag_set(m, PGA_REFERENCED);
3247 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3248 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3250 if (TAILQ_EMPTY(&m->md.pv_list) &&
3251 (m->flags & PG_FICTITIOUS) == 0) {
3252 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3253 if (TAILQ_EMPTY(&pvh->pv_list)) {
3254 vm_page_aflag_clear(m,
3258 pmap_delayed_invl_page(m);
3259 pc->pc_map[field] |= 1UL << bit;
3260 pmap_unuse_pt(pmap, va, *pde, &free);
3265 mtx_lock(&pv_chunks_mutex);
3268 /* Every freed mapping is for a 4 KB page. */
3269 pmap_resident_count_dec(pmap, freed);
3270 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
3271 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
3272 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
3273 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3274 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
3275 pc->pc_map[2] == PC_FREE2) {
3276 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3277 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3278 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3279 /* Entire chunk is free; return it. */
3280 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3281 dump_drop_page(m_pc->phys_addr);
3282 mtx_lock(&pv_chunks_mutex);
3283 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3286 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3287 mtx_lock(&pv_chunks_mutex);
3288 /* One freed pv entry in locked_pmap is sufficient. */
3289 if (pmap == locked_pmap)
3292 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3293 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
3294 if (active_reclaims == 1 && pmap != NULL) {
3296 * Rotate the pv chunks list so that we do not
3297 * scan the same pv chunks that could not be
3298 * freed (because they contained a wired
3299 * and/or superpage mapping) on every
3300 * invocation of reclaim_pv_chunk().
3302 while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
3303 MPASS(pc->pc_pmap != NULL);
3304 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3305 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3309 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3310 TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
3312 mtx_unlock(&pv_chunks_mutex);
3313 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
3314 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
3315 m_pc = SLIST_FIRST(&free);
3316 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3317 /* Recycle a freed page table page. */
3318 m_pc->wire_count = 1;
3320 pmap_free_zero_pages(&free);
3325 * free the pv_entry back to the free list
3328 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3330 struct pv_chunk *pc;
3331 int idx, field, bit;
3333 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3334 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3335 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3336 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3337 pc = pv_to_chunk(pv);
3338 idx = pv - &pc->pc_pventry[0];
3341 pc->pc_map[field] |= 1ul << bit;
3342 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3343 pc->pc_map[2] != PC_FREE2) {
3344 /* 98% of the time, pc is already at the head of the list. */
3345 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3346 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3347 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3351 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3356 free_pv_chunk(struct pv_chunk *pc)
3360 mtx_lock(&pv_chunks_mutex);
3361 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3362 mtx_unlock(&pv_chunks_mutex);
3363 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3364 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3365 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3366 /* entire chunk is free, return it */
3367 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3368 dump_drop_page(m->phys_addr);
3369 vm_page_unwire(m, PQ_NONE);
3374 * Returns a new PV entry, allocating a new PV chunk from the system when
3375 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3376 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3379 * The given PV list lock may be released.
3382 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3386 struct pv_chunk *pc;
3389 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3390 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3392 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3394 for (field = 0; field < _NPCM; field++) {
3395 if (pc->pc_map[field]) {
3396 bit = bsfq(pc->pc_map[field]);
3400 if (field < _NPCM) {
3401 pv = &pc->pc_pventry[field * 64 + bit];
3402 pc->pc_map[field] &= ~(1ul << bit);
3403 /* If this was the last item, move it to tail */
3404 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3405 pc->pc_map[2] == 0) {
3406 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3407 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3410 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3411 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3415 /* No free items, allocate another chunk */
3416 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3419 if (lockp == NULL) {
3420 PV_STAT(pc_chunk_tryfail++);
3423 m = reclaim_pv_chunk(pmap, lockp);
3427 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3428 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3429 dump_add_page(m->phys_addr);
3430 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3432 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3433 pc->pc_map[1] = PC_FREE1;
3434 pc->pc_map[2] = PC_FREE2;
3435 mtx_lock(&pv_chunks_mutex);
3436 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3437 mtx_unlock(&pv_chunks_mutex);
3438 pv = &pc->pc_pventry[0];
3439 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3440 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3441 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3446 * Returns the number of one bits within the given PV chunk map.
3448 * The erratas for Intel processors state that "POPCNT Instruction May
3449 * Take Longer to Execute Than Expected". It is believed that the
3450 * issue is the spurious dependency on the destination register.
3451 * Provide a hint to the register rename logic that the destination
3452 * value is overwritten, by clearing it, as suggested in the
3453 * optimization manual. It should be cheap for unaffected processors
3456 * Reference numbers for erratas are
3457 * 4th Gen Core: HSD146
3458 * 5th Gen Core: BDM85
3459 * 6th Gen Core: SKL029
3462 popcnt_pc_map_pq(uint64_t *map)
3466 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3467 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3468 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3469 : "=&r" (result), "=&r" (tmp)
3470 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3475 * Ensure that the number of spare PV entries in the specified pmap meets or
3476 * exceeds the given count, "needed".
3478 * The given PV list lock may be released.
3481 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3483 struct pch new_tail;
3484 struct pv_chunk *pc;
3488 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3489 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3492 * Newly allocated PV chunks must be stored in a private list until
3493 * the required number of PV chunks have been allocated. Otherwise,
3494 * reclaim_pv_chunk() could recycle one of these chunks. In
3495 * contrast, these chunks must be added to the pmap upon allocation.
3497 TAILQ_INIT(&new_tail);
3500 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3502 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3503 bit_count((bitstr_t *)pc->pc_map, 0,
3504 sizeof(pc->pc_map) * NBBY, &free);
3507 free = popcnt_pc_map_pq(pc->pc_map);
3511 if (avail >= needed)
3514 for (; avail < needed; avail += _NPCPV) {
3515 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3518 m = reclaim_pv_chunk(pmap, lockp);
3522 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3523 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3524 dump_add_page(m->phys_addr);
3525 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3527 pc->pc_map[0] = PC_FREE0;
3528 pc->pc_map[1] = PC_FREE1;
3529 pc->pc_map[2] = PC_FREE2;
3530 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3531 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3532 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3534 if (!TAILQ_EMPTY(&new_tail)) {
3535 mtx_lock(&pv_chunks_mutex);
3536 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3537 mtx_unlock(&pv_chunks_mutex);
3542 * First find and then remove the pv entry for the specified pmap and virtual
3543 * address from the specified pv list. Returns the pv entry if found and NULL
3544 * otherwise. This operation can be performed on pv lists for either 4KB or
3545 * 2MB page mappings.
3547 static __inline pv_entry_t
3548 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3552 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3553 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3554 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3563 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3564 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3565 * entries for each of the 4KB page mappings.
3568 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3569 struct rwlock **lockp)
3571 struct md_page *pvh;
3572 struct pv_chunk *pc;
3574 vm_offset_t va_last;
3578 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3579 KASSERT((pa & PDRMASK) == 0,
3580 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3581 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3584 * Transfer the 2mpage's pv entry for this mapping to the first
3585 * page's pv list. Once this transfer begins, the pv list lock
3586 * must not be released until the last pv entry is reinstantiated.
3588 pvh = pa_to_pvh(pa);
3589 va = trunc_2mpage(va);
3590 pv = pmap_pvh_remove(pvh, pmap, va);
3591 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3592 m = PHYS_TO_VM_PAGE(pa);
3593 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3595 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3596 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3597 va_last = va + NBPDR - PAGE_SIZE;
3599 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3600 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3601 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3602 for (field = 0; field < _NPCM; field++) {
3603 while (pc->pc_map[field]) {
3604 bit = bsfq(pc->pc_map[field]);
3605 pc->pc_map[field] &= ~(1ul << bit);
3606 pv = &pc->pc_pventry[field * 64 + bit];
3610 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3611 ("pmap_pv_demote_pde: page %p is not managed", m));
3612 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3618 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3619 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3622 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3623 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3624 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3626 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3627 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3630 #if VM_NRESERVLEVEL > 0
3632 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3633 * replace the many pv entries for the 4KB page mappings by a single pv entry
3634 * for the 2MB page mapping.
3637 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3638 struct rwlock **lockp)
3640 struct md_page *pvh;
3642 vm_offset_t va_last;
3645 KASSERT((pa & PDRMASK) == 0,
3646 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3647 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3650 * Transfer the first page's pv entry for this mapping to the 2mpage's
3651 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3652 * a transfer avoids the possibility that get_pv_entry() calls
3653 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3654 * mappings that is being promoted.
3656 m = PHYS_TO_VM_PAGE(pa);
3657 va = trunc_2mpage(va);
3658 pv = pmap_pvh_remove(&m->md, pmap, va);
3659 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3660 pvh = pa_to_pvh(pa);
3661 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3663 /* Free the remaining NPTEPG - 1 pv entries. */
3664 va_last = va + NBPDR - PAGE_SIZE;
3668 pmap_pvh_free(&m->md, pmap, va);
3669 } while (va < va_last);
3671 #endif /* VM_NRESERVLEVEL > 0 */
3674 * First find and then destroy the pv entry for the specified pmap and virtual
3675 * address. This operation can be performed on pv lists for either 4KB or 2MB
3679 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3683 pv = pmap_pvh_remove(pvh, pmap, va);
3684 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3685 free_pv_entry(pmap, pv);
3689 * Conditionally create the PV entry for a 4KB page mapping if the required
3690 * memory can be allocated without resorting to reclamation.
3693 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3694 struct rwlock **lockp)
3698 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3699 /* Pass NULL instead of the lock pointer to disable reclamation. */
3700 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3702 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3703 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3711 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3712 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3713 * false if the PV entry cannot be allocated without resorting to reclamation.
3716 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
3717 struct rwlock **lockp)
3719 struct md_page *pvh;
3723 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3724 /* Pass NULL instead of the lock pointer to disable reclamation. */
3725 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3726 NULL : lockp)) == NULL)
3729 pa = pde & PG_PS_FRAME;
3730 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3731 pvh = pa_to_pvh(pa);
3732 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3738 * Fills a page table page with mappings to consecutive physical pages.
3741 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3745 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3747 newpte += PAGE_SIZE;
3752 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3753 * mapping is invalidated.
3756 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3758 struct rwlock *lock;
3762 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3769 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3770 struct rwlock **lockp)
3772 pd_entry_t newpde, oldpde;
3773 pt_entry_t *firstpte, newpte;
3774 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3777 struct spglist free;
3781 PG_G = pmap_global_bit(pmap);
3782 PG_A = pmap_accessed_bit(pmap);
3783 PG_M = pmap_modified_bit(pmap);
3784 PG_RW = pmap_rw_bit(pmap);
3785 PG_V = pmap_valid_bit(pmap);
3786 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3788 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3790 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3791 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3792 if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
3794 KASSERT((oldpde & PG_W) == 0,
3795 ("pmap_demote_pde: page table page for a wired mapping"
3799 * Invalidate the 2MB page mapping and return "failure" if the
3800 * mapping was never accessed or the allocation of the new
3801 * page table page fails. If the 2MB page mapping belongs to
3802 * the direct map region of the kernel's address space, then
3803 * the page allocation request specifies the highest possible
3804 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3805 * normal. Page table pages are preallocated for every other
3806 * part of the kernel address space, so the direct map region
3807 * is the only part of the kernel address space that must be
3810 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3811 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3812 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3813 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3815 sva = trunc_2mpage(va);
3816 pmap_remove_pde(pmap, pde, sva, &free, lockp);
3817 if ((oldpde & PG_G) == 0)
3818 pmap_invalidate_pde_page(pmap, sva, oldpde);
3819 pmap_free_zero_pages(&free);
3820 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3821 " in pmap %p", va, pmap);
3824 if (va < VM_MAXUSER_ADDRESS)
3825 pmap_resident_count_inc(pmap, 1);
3827 mptepa = VM_PAGE_TO_PHYS(mpte);
3828 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3829 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3830 KASSERT((oldpde & PG_A) != 0,
3831 ("pmap_demote_pde: oldpde is missing PG_A"));
3832 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3833 ("pmap_demote_pde: oldpde is missing PG_M"));
3834 newpte = oldpde & ~PG_PS;
3835 newpte = pmap_swap_pat(pmap, newpte);
3838 * If the page table page is new, initialize it.
3840 if (mpte->wire_count == 1) {
3841 mpte->wire_count = NPTEPG;
3842 pmap_fill_ptp(firstpte, newpte);
3844 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3845 ("pmap_demote_pde: firstpte and newpte map different physical"
3849 * If the mapping has changed attributes, update the page table
3852 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3853 pmap_fill_ptp(firstpte, newpte);
3856 * The spare PV entries must be reserved prior to demoting the
3857 * mapping, that is, prior to changing the PDE. Otherwise, the state
3858 * of the PDE and the PV lists will be inconsistent, which can result
3859 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3860 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3861 * PV entry for the 2MB page mapping that is being demoted.
3863 if ((oldpde & PG_MANAGED) != 0)
3864 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3867 * Demote the mapping. This pmap is locked. The old PDE has
3868 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3869 * set. Thus, there is no danger of a race with another
3870 * processor changing the setting of PG_A and/or PG_M between
3871 * the read above and the store below.
3873 if (workaround_erratum383)
3874 pmap_update_pde(pmap, va, pde, newpde);
3876 pde_store(pde, newpde);
3879 * Invalidate a stale recursive mapping of the page table page.
3881 if (va >= VM_MAXUSER_ADDRESS)
3882 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3885 * Demote the PV entry.
3887 if ((oldpde & PG_MANAGED) != 0)
3888 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3890 atomic_add_long(&pmap_pde_demotions, 1);
3891 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3892 " in pmap %p", va, pmap);
3897 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3900 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3906 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3907 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3908 mpte = pmap_remove_pt_page(pmap, va);
3910 panic("pmap_remove_kernel_pde: Missing pt page.");
3912 mptepa = VM_PAGE_TO_PHYS(mpte);
3913 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3916 * Initialize the page table page.
3918 pagezero((void *)PHYS_TO_DMAP(mptepa));
3921 * Demote the mapping.
3923 if (workaround_erratum383)
3924 pmap_update_pde(pmap, va, pde, newpde);
3926 pde_store(pde, newpde);
3929 * Invalidate a stale recursive mapping of the page table page.
3931 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3935 * pmap_remove_pde: do the things to unmap a superpage in a process
3938 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
3939 struct spglist *free, struct rwlock **lockp)
3941 struct md_page *pvh;
3943 vm_offset_t eva, va;
3945 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3947 PG_G = pmap_global_bit(pmap);
3948 PG_A = pmap_accessed_bit(pmap);
3949 PG_M = pmap_modified_bit(pmap);
3950 PG_RW = pmap_rw_bit(pmap);
3952 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3953 KASSERT((sva & PDRMASK) == 0,
3954 ("pmap_remove_pde: sva is not 2mpage aligned"));
3955 oldpde = pte_load_clear(pdq);
3957 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
3958 if ((oldpde & PG_G) != 0)
3959 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
3960 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
3961 if (oldpde & PG_MANAGED) {
3962 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
3963 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
3964 pmap_pvh_free(pvh, pmap, sva);
3966 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3967 va < eva; va += PAGE_SIZE, m++) {
3968 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3971 vm_page_aflag_set(m, PGA_REFERENCED);
3972 if (TAILQ_EMPTY(&m->md.pv_list) &&
3973 TAILQ_EMPTY(&pvh->pv_list))
3974 vm_page_aflag_clear(m, PGA_WRITEABLE);
3975 pmap_delayed_invl_page(m);
3978 if (pmap == kernel_pmap) {
3979 pmap_remove_kernel_pde(pmap, pdq, sva);
3981 mpte = pmap_remove_pt_page(pmap, sva);
3983 pmap_resident_count_dec(pmap, 1);
3984 KASSERT(mpte->wire_count == NPTEPG,
3985 ("pmap_remove_pde: pte page wire count error"));
3986 mpte->wire_count = 0;
3987 pmap_add_delayed_free_list(mpte, free, FALSE);
3990 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
3994 * pmap_remove_pte: do the things to unmap a page in a process
3997 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
3998 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
4000 struct md_page *pvh;
4001 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
4004 PG_A = pmap_accessed_bit(pmap);
4005 PG_M = pmap_modified_bit(pmap);
4006 PG_RW = pmap_rw_bit(pmap);
4008 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4009 oldpte = pte_load_clear(ptq);
4011 pmap->pm_stats.wired_count -= 1;
4012 pmap_resident_count_dec(pmap, 1);
4013 if (oldpte & PG_MANAGED) {
4014 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
4015 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4018 vm_page_aflag_set(m, PGA_REFERENCED);
4019 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
4020 pmap_pvh_free(&m->md, pmap, va);
4021 if (TAILQ_EMPTY(&m->md.pv_list) &&
4022 (m->flags & PG_FICTITIOUS) == 0) {
4023 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4024 if (TAILQ_EMPTY(&pvh->pv_list))
4025 vm_page_aflag_clear(m, PGA_WRITEABLE);
4027 pmap_delayed_invl_page(m);
4029 return (pmap_unuse_pt(pmap, va, ptepde, free));
4033 * Remove a single page from a process address space
4036 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
4037 struct spglist *free)
4039 struct rwlock *lock;
4040 pt_entry_t *pte, PG_V;
4042 PG_V = pmap_valid_bit(pmap);
4043 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4044 if ((*pde & PG_V) == 0)
4046 pte = pmap_pde_to_pte(pde, va);
4047 if ((*pte & PG_V) == 0)
4050 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
4053 pmap_invalidate_page(pmap, va);
4057 * Removes the specified range of addresses from the page table page.
4060 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
4061 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
4063 pt_entry_t PG_G, *pte;
4067 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4068 PG_G = pmap_global_bit(pmap);
4071 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
4075 pmap_invalidate_range(pmap, va, sva);
4080 if ((*pte & PG_G) == 0)
4084 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
4090 pmap_invalidate_range(pmap, va, sva);
4095 * Remove the given range of addresses from the specified map.
4097 * It is assumed that the start and end are properly
4098 * rounded to the page size.
4101 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4103 struct rwlock *lock;
4104 vm_offset_t va_next;
4105 pml4_entry_t *pml4e;
4107 pd_entry_t ptpaddr, *pde;
4108 pt_entry_t PG_G, PG_V;
4109 struct spglist free;
4112 PG_G = pmap_global_bit(pmap);
4113 PG_V = pmap_valid_bit(pmap);
4116 * Perform an unsynchronized read. This is, however, safe.
4118 if (pmap->pm_stats.resident_count == 0)
4124 pmap_delayed_invl_started();
4128 * special handling of removing one page. a very
4129 * common operation and easy to short circuit some
4132 if (sva + PAGE_SIZE == eva) {
4133 pde = pmap_pde(pmap, sva);
4134 if (pde && (*pde & PG_PS) == 0) {
4135 pmap_remove_page(pmap, sva, pde, &free);
4141 for (; sva < eva; sva = va_next) {
4143 if (pmap->pm_stats.resident_count == 0)
4146 pml4e = pmap_pml4e(pmap, sva);
4147 if ((*pml4e & PG_V) == 0) {
4148 va_next = (sva + NBPML4) & ~PML4MASK;
4154 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4155 if ((*pdpe & PG_V) == 0) {
4156 va_next = (sva + NBPDP) & ~PDPMASK;
4163 * Calculate index for next page table.
4165 va_next = (sva + NBPDR) & ~PDRMASK;
4169 pde = pmap_pdpe_to_pde(pdpe, sva);
4173 * Weed out invalid mappings.
4179 * Check for large page.
4181 if ((ptpaddr & PG_PS) != 0) {
4183 * Are we removing the entire large page? If not,
4184 * demote the mapping and fall through.
4186 if (sva + NBPDR == va_next && eva >= va_next) {
4188 * The TLB entry for a PG_G mapping is
4189 * invalidated by pmap_remove_pde().
4191 if ((ptpaddr & PG_G) == 0)
4193 pmap_remove_pde(pmap, pde, sva, &free, &lock);
4195 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
4197 /* The large page mapping was destroyed. */
4204 * Limit our scan to either the end of the va represented
4205 * by the current page table page, or to the end of the
4206 * range being removed.
4211 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
4218 pmap_invalidate_all(pmap);
4220 pmap_delayed_invl_finished();
4221 pmap_free_zero_pages(&free);
4225 * Routine: pmap_remove_all
4227 * Removes this physical page from
4228 * all physical maps in which it resides.
4229 * Reflects back modify bits to the pager.
4232 * Original versions of this routine were very
4233 * inefficient because they iteratively called
4234 * pmap_remove (slow...)
4238 pmap_remove_all(vm_page_t m)
4240 struct md_page *pvh;
4243 struct rwlock *lock;
4244 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
4247 struct spglist free;
4248 int pvh_gen, md_gen;
4250 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4251 ("pmap_remove_all: page %p is not managed", m));
4253 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4254 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
4255 pa_to_pvh(VM_PAGE_TO_PHYS(m));
4258 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
4260 if (!PMAP_TRYLOCK(pmap)) {
4261 pvh_gen = pvh->pv_gen;
4265 if (pvh_gen != pvh->pv_gen) {
4272 pde = pmap_pde(pmap, va);
4273 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
4276 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4278 if (!PMAP_TRYLOCK(pmap)) {
4279 pvh_gen = pvh->pv_gen;
4280 md_gen = m->md.pv_gen;
4284 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
4290 PG_A = pmap_accessed_bit(pmap);
4291 PG_M = pmap_modified_bit(pmap);
4292 PG_RW = pmap_rw_bit(pmap);
4293 pmap_resident_count_dec(pmap, 1);
4294 pde = pmap_pde(pmap, pv->pv_va);
4295 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
4296 " a 2mpage in page %p's pv list", m));
4297 pte = pmap_pde_to_pte(pde, pv->pv_va);
4298 tpte = pte_load_clear(pte);
4300 pmap->pm_stats.wired_count--;
4302 vm_page_aflag_set(m, PGA_REFERENCED);
4305 * Update the vm_page_t clean and reference bits.
4307 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4309 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
4310 pmap_invalidate_page(pmap, pv->pv_va);
4311 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4313 free_pv_entry(pmap, pv);
4316 vm_page_aflag_clear(m, PGA_WRITEABLE);
4318 pmap_delayed_invl_wait(m);
4319 pmap_free_zero_pages(&free);
4323 * pmap_protect_pde: do the things to protect a 2mpage in a process
4326 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
4328 pd_entry_t newpde, oldpde;
4329 vm_offset_t eva, va;
4331 boolean_t anychanged;
4332 pt_entry_t PG_G, PG_M, PG_RW;
4334 PG_G = pmap_global_bit(pmap);
4335 PG_M = pmap_modified_bit(pmap);
4336 PG_RW = pmap_rw_bit(pmap);
4338 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4339 KASSERT((sva & PDRMASK) == 0,
4340 ("pmap_protect_pde: sva is not 2mpage aligned"));
4343 oldpde = newpde = *pde;
4344 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4345 (PG_MANAGED | PG_M | PG_RW)) {
4347 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4348 va < eva; va += PAGE_SIZE, m++)
4351 if ((prot & VM_PROT_WRITE) == 0)
4352 newpde &= ~(PG_RW | PG_M);
4353 if ((prot & VM_PROT_EXECUTE) == 0)
4355 if (newpde != oldpde) {
4357 * As an optimization to future operations on this PDE, clear
4358 * PG_PROMOTED. The impending invalidation will remove any
4359 * lingering 4KB page mappings from the TLB.
4361 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
4363 if ((oldpde & PG_G) != 0)
4364 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4368 return (anychanged);
4372 * Set the physical protection on the
4373 * specified range of this map as requested.
4376 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4378 vm_offset_t va_next;
4379 pml4_entry_t *pml4e;
4381 pd_entry_t ptpaddr, *pde;
4382 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4383 boolean_t anychanged;
4385 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4386 if (prot == VM_PROT_NONE) {
4387 pmap_remove(pmap, sva, eva);
4391 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4392 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4395 PG_G = pmap_global_bit(pmap);
4396 PG_M = pmap_modified_bit(pmap);
4397 PG_V = pmap_valid_bit(pmap);
4398 PG_RW = pmap_rw_bit(pmap);
4402 * Although this function delays and batches the invalidation
4403 * of stale TLB entries, it does not need to call
4404 * pmap_delayed_invl_started() and
4405 * pmap_delayed_invl_finished(), because it does not
4406 * ordinarily destroy mappings. Stale TLB entries from
4407 * protection-only changes need only be invalidated before the
4408 * pmap lock is released, because protection-only changes do
4409 * not destroy PV entries. Even operations that iterate over
4410 * a physical page's PV list of mappings, like
4411 * pmap_remove_write(), acquire the pmap lock for each
4412 * mapping. Consequently, for protection-only changes, the
4413 * pmap lock suffices to synchronize both page table and TLB
4416 * This function only destroys a mapping if pmap_demote_pde()
4417 * fails. In that case, stale TLB entries are immediately
4422 for (; sva < eva; sva = va_next) {
4424 pml4e = pmap_pml4e(pmap, sva);
4425 if ((*pml4e & PG_V) == 0) {
4426 va_next = (sva + NBPML4) & ~PML4MASK;
4432 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4433 if ((*pdpe & PG_V) == 0) {
4434 va_next = (sva + NBPDP) & ~PDPMASK;
4440 va_next = (sva + NBPDR) & ~PDRMASK;
4444 pde = pmap_pdpe_to_pde(pdpe, sva);
4448 * Weed out invalid mappings.
4454 * Check for large page.
4456 if ((ptpaddr & PG_PS) != 0) {
4458 * Are we protecting the entire large page? If not,
4459 * demote the mapping and fall through.
4461 if (sva + NBPDR == va_next && eva >= va_next) {
4463 * The TLB entry for a PG_G mapping is
4464 * invalidated by pmap_protect_pde().
4466 if (pmap_protect_pde(pmap, pde, sva, prot))
4469 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4471 * The large page mapping was destroyed.
4480 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4482 pt_entry_t obits, pbits;
4486 obits = pbits = *pte;
4487 if ((pbits & PG_V) == 0)
4490 if ((prot & VM_PROT_WRITE) == 0) {
4491 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4492 (PG_MANAGED | PG_M | PG_RW)) {
4493 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4496 pbits &= ~(PG_RW | PG_M);
4498 if ((prot & VM_PROT_EXECUTE) == 0)
4501 if (pbits != obits) {
4502 if (!atomic_cmpset_long(pte, obits, pbits))
4505 pmap_invalidate_page(pmap, sva);
4512 pmap_invalidate_all(pmap);
4516 #if VM_NRESERVLEVEL > 0
4518 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4519 * single page table page (PTP) to a single 2MB page mapping. For promotion
4520 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4521 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4522 * identical characteristics.
4525 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4526 struct rwlock **lockp)
4529 pt_entry_t *firstpte, oldpte, pa, *pte;
4530 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4534 PG_A = pmap_accessed_bit(pmap);
4535 PG_G = pmap_global_bit(pmap);
4536 PG_M = pmap_modified_bit(pmap);
4537 PG_V = pmap_valid_bit(pmap);
4538 PG_RW = pmap_rw_bit(pmap);
4539 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4541 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4544 * Examine the first PTE in the specified PTP. Abort if this PTE is
4545 * either invalid, unused, or does not map the first 4KB physical page
4546 * within a 2MB page.
4548 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4551 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4552 atomic_add_long(&pmap_pde_p_failures, 1);
4553 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4554 " in pmap %p", va, pmap);
4557 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4559 * When PG_M is already clear, PG_RW can be cleared without
4560 * a TLB invalidation.
4562 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4568 * Examine each of the other PTEs in the specified PTP. Abort if this
4569 * PTE maps an unexpected 4KB physical page or does not have identical
4570 * characteristics to the first PTE.
4572 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4573 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4576 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4577 atomic_add_long(&pmap_pde_p_failures, 1);
4578 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4579 " in pmap %p", va, pmap);
4582 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4584 * When PG_M is already clear, PG_RW can be cleared
4585 * without a TLB invalidation.
4587 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4590 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4591 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4592 (va & ~PDRMASK), pmap);
4594 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4595 atomic_add_long(&pmap_pde_p_failures, 1);
4596 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4597 " in pmap %p", va, pmap);
4604 * Save the page table page in its current state until the PDE
4605 * mapping the superpage is demoted by pmap_demote_pde() or
4606 * destroyed by pmap_remove_pde().
4608 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4609 KASSERT(mpte >= vm_page_array &&
4610 mpte < &vm_page_array[vm_page_array_size],
4611 ("pmap_promote_pde: page table page is out of range"));
4612 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4613 ("pmap_promote_pde: page table page's pindex is wrong"));
4614 if (pmap_insert_pt_page(pmap, mpte)) {
4615 atomic_add_long(&pmap_pde_p_failures, 1);
4617 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4623 * Promote the pv entries.
4625 if ((newpde & PG_MANAGED) != 0)
4626 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4629 * Propagate the PAT index to its proper position.
4631 newpde = pmap_swap_pat(pmap, newpde);
4634 * Map the superpage.
4636 if (workaround_erratum383)
4637 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4639 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
4641 atomic_add_long(&pmap_pde_promotions, 1);
4642 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4643 " in pmap %p", va, pmap);
4645 #endif /* VM_NRESERVLEVEL > 0 */
4648 * Insert the given physical page (p) at
4649 * the specified virtual address (v) in the
4650 * target physical map with the protection requested.
4652 * If specified, the page will be wired down, meaning
4653 * that the related pte can not be reclaimed.
4655 * NB: This is the only routine which MAY NOT lazy-evaluate
4656 * or lose information. That is, this routine must actually
4657 * insert this page into the given map NOW.
4659 * When destroying both a page table and PV entry, this function
4660 * performs the TLB invalidation before releasing the PV list
4661 * lock, so we do not need pmap_delayed_invl_page() calls here.
4664 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4665 u_int flags, int8_t psind)
4667 struct rwlock *lock;
4669 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4670 pt_entry_t newpte, origpte;
4677 PG_A = pmap_accessed_bit(pmap);
4678 PG_G = pmap_global_bit(pmap);
4679 PG_M = pmap_modified_bit(pmap);
4680 PG_V = pmap_valid_bit(pmap);
4681 PG_RW = pmap_rw_bit(pmap);
4683 va = trunc_page(va);
4684 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4685 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4686 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4688 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4689 va >= kmi.clean_eva,
4690 ("pmap_enter: managed mapping within the clean submap"));
4691 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4692 VM_OBJECT_ASSERT_LOCKED(m->object);
4693 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
4694 ("pmap_enter: flags %u has reserved bits set", flags));
4695 pa = VM_PAGE_TO_PHYS(m);
4696 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4697 if ((flags & VM_PROT_WRITE) != 0)
4699 if ((prot & VM_PROT_WRITE) != 0)
4701 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4702 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4703 if ((prot & VM_PROT_EXECUTE) == 0)
4705 if ((flags & PMAP_ENTER_WIRED) != 0)
4707 if (va < VM_MAXUSER_ADDRESS)
4709 if (pmap == kernel_pmap)
4711 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
4714 * Set modified bit gratuitously for writeable mappings if
4715 * the page is unmanaged. We do not want to take a fault
4716 * to do the dirty bit accounting for these mappings.
4718 if ((m->oflags & VPO_UNMANAGED) != 0) {
4719 if ((newpte & PG_RW) != 0)
4722 newpte |= PG_MANAGED;
4727 /* Assert the required virtual and physical alignment. */
4728 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
4729 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4730 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
4736 * In the case that a page table page is not
4737 * resident, we are creating it here.
4740 pde = pmap_pde(pmap, va);
4741 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4742 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4743 pte = pmap_pde_to_pte(pde, va);
4744 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4745 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4748 } else if (va < VM_MAXUSER_ADDRESS) {
4750 * Here if the pte page isn't mapped, or if it has been
4753 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4754 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4755 nosleep ? NULL : &lock);
4756 if (mpte == NULL && nosleep) {
4757 rv = KERN_RESOURCE_SHORTAGE;
4762 panic("pmap_enter: invalid page directory va=%#lx", va);
4767 * Is the specified virtual address already mapped?
4769 if ((origpte & PG_V) != 0) {
4771 * Wiring change, just update stats. We don't worry about
4772 * wiring PT pages as they remain resident as long as there
4773 * are valid mappings in them. Hence, if a user page is wired,
4774 * the PT page will be also.
4776 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4777 pmap->pm_stats.wired_count++;
4778 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4779 pmap->pm_stats.wired_count--;
4782 * Remove the extra PT page reference.
4786 KASSERT(mpte->wire_count > 0,
4787 ("pmap_enter: missing reference to page table page,"
4792 * Has the physical page changed?
4794 opa = origpte & PG_FRAME;
4797 * No, might be a protection or wiring change.
4799 if ((origpte & PG_MANAGED) != 0 &&
4800 (newpte & PG_RW) != 0)
4801 vm_page_aflag_set(m, PGA_WRITEABLE);
4802 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4808 * Increment the counters.
4810 if ((newpte & PG_W) != 0)
4811 pmap->pm_stats.wired_count++;
4812 pmap_resident_count_inc(pmap, 1);
4816 * Enter on the PV list if part of our managed memory.
4818 if ((newpte & PG_MANAGED) != 0) {
4819 pv = get_pv_entry(pmap, &lock);
4821 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4822 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4824 if ((newpte & PG_RW) != 0)
4825 vm_page_aflag_set(m, PGA_WRITEABLE);
4831 if ((origpte & PG_V) != 0) {
4833 origpte = pte_load_store(pte, newpte);
4834 opa = origpte & PG_FRAME;
4836 if ((origpte & PG_MANAGED) != 0) {
4837 om = PHYS_TO_VM_PAGE(opa);
4838 if ((origpte & (PG_M | PG_RW)) == (PG_M |
4841 if ((origpte & PG_A) != 0)
4842 vm_page_aflag_set(om, PGA_REFERENCED);
4843 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4844 pmap_pvh_free(&om->md, pmap, va);
4845 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4846 TAILQ_EMPTY(&om->md.pv_list) &&
4847 ((om->flags & PG_FICTITIOUS) != 0 ||
4848 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4849 vm_page_aflag_clear(om, PGA_WRITEABLE);
4851 } else if ((newpte & PG_M) == 0 && (origpte & (PG_M |
4852 PG_RW)) == (PG_M | PG_RW)) {
4853 if ((origpte & PG_MANAGED) != 0)
4857 * Although the PTE may still have PG_RW set, TLB
4858 * invalidation may nonetheless be required because
4859 * the PTE no longer has PG_M set.
4861 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4863 * This PTE change does not require TLB invalidation.
4867 if ((origpte & PG_A) != 0)
4868 pmap_invalidate_page(pmap, va);
4870 pte_store(pte, newpte);
4874 #if VM_NRESERVLEVEL > 0
4876 * If both the page table page and the reservation are fully
4877 * populated, then attempt promotion.
4879 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4880 pmap_ps_enabled(pmap) &&
4881 (m->flags & PG_FICTITIOUS) == 0 &&
4882 vm_reserv_level_iffullpop(m) == 0)
4883 pmap_promote_pde(pmap, pde, va, &lock);
4895 * Tries to create a read- and/or execute-only 2MB page mapping. Returns true
4896 * if successful. Returns false if (1) a page table page cannot be allocated
4897 * without sleeping, (2) a mapping already exists at the specified virtual
4898 * address, or (3) a PV entry cannot be allocated without reclaiming another
4902 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4903 struct rwlock **lockp)
4908 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4909 PG_V = pmap_valid_bit(pmap);
4910 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
4912 if ((m->oflags & VPO_UNMANAGED) == 0)
4913 newpde |= PG_MANAGED;
4914 if ((prot & VM_PROT_EXECUTE) == 0)
4916 if (va < VM_MAXUSER_ADDRESS)
4918 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
4919 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
4924 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
4925 * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
4926 * otherwise. Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
4927 * a mapping already exists at the specified virtual address. Returns
4928 * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
4929 * page allocation failed. Returns KERN_RESOURCE_SHORTAGE if
4930 * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
4932 * The parameter "m" is only used when creating a managed, writeable mapping.
4935 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
4936 vm_page_t m, struct rwlock **lockp)
4938 struct spglist free;
4939 pd_entry_t oldpde, *pde;
4940 pt_entry_t PG_G, PG_RW, PG_V;
4943 PG_G = pmap_global_bit(pmap);
4944 PG_RW = pmap_rw_bit(pmap);
4945 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
4946 ("pmap_enter_pde: newpde is missing PG_M"));
4947 PG_V = pmap_valid_bit(pmap);
4948 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4950 if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
4951 NULL : lockp)) == NULL) {
4952 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4953 " in pmap %p", va, pmap);
4954 return (KERN_RESOURCE_SHORTAGE);
4956 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4957 pde = &pde[pmap_pde_index(va)];
4959 if ((oldpde & PG_V) != 0) {
4960 KASSERT(pdpg->wire_count > 1,
4961 ("pmap_enter_pde: pdpg's wire count is too low"));
4962 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
4964 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4965 " in pmap %p", va, pmap);
4966 return (KERN_FAILURE);
4968 /* Break the existing mapping(s). */
4970 if ((oldpde & PG_PS) != 0) {
4972 * The reference to the PD page that was acquired by
4973 * pmap_allocpde() ensures that it won't be freed.
4974 * However, if the PDE resulted from a promotion, then
4975 * a reserved PT page could be freed.
4977 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
4978 if ((oldpde & PG_G) == 0)
4979 pmap_invalidate_pde_page(pmap, va, oldpde);
4981 pmap_delayed_invl_started();
4982 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
4984 pmap_invalidate_all(pmap);
4985 pmap_delayed_invl_finished();
4987 pmap_free_zero_pages(&free);
4988 if (va >= VM_MAXUSER_ADDRESS) {
4989 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4990 if (pmap_insert_pt_page(pmap, mt)) {
4992 * XXX Currently, this can't happen because
4993 * we do not perform pmap_enter(psind == 1)
4994 * on the kernel pmap.
4996 panic("pmap_enter_pde: trie insert failed");
4999 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
5002 if ((newpde & PG_MANAGED) != 0) {
5004 * Abort this mapping if its PV entry could not be created.
5006 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
5008 if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
5010 * Although "va" is not mapped, paging-
5011 * structure caches could nonetheless have
5012 * entries that refer to the freed page table
5013 * pages. Invalidate those entries.
5015 pmap_invalidate_page(pmap, va);
5016 pmap_free_zero_pages(&free);
5018 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5019 " in pmap %p", va, pmap);
5020 return (KERN_RESOURCE_SHORTAGE);
5022 if ((newpde & PG_RW) != 0) {
5023 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5024 vm_page_aflag_set(mt, PGA_WRITEABLE);
5029 * Increment counters.
5031 if ((newpde & PG_W) != 0)
5032 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
5033 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5036 * Map the superpage. (This is not a promoted mapping; there will not
5037 * be any lingering 4KB page mappings in the TLB.)
5039 pde_store(pde, newpde);
5041 atomic_add_long(&pmap_pde_mappings, 1);
5042 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
5043 " in pmap %p", va, pmap);
5044 return (KERN_SUCCESS);
5048 * Maps a sequence of resident pages belonging to the same object.
5049 * The sequence begins with the given page m_start. This page is
5050 * mapped at the given virtual address start. Each subsequent page is
5051 * mapped at a virtual address that is offset from start by the same
5052 * amount as the page is offset from m_start within the object. The
5053 * last page in the sequence is the page with the largest offset from
5054 * m_start that can be mapped at a virtual address less than the given
5055 * virtual address end. Not every virtual page between start and end
5056 * is mapped; only those for which a resident page exists with the
5057 * corresponding offset from m_start are mapped.
5060 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
5061 vm_page_t m_start, vm_prot_t prot)
5063 struct rwlock *lock;
5066 vm_pindex_t diff, psize;
5068 VM_OBJECT_ASSERT_LOCKED(m_start->object);
5070 psize = atop(end - start);
5075 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
5076 va = start + ptoa(diff);
5077 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
5078 m->psind == 1 && pmap_ps_enabled(pmap) &&
5079 pmap_enter_2mpage(pmap, va, m, prot, &lock))
5080 m = &m[NBPDR / PAGE_SIZE - 1];
5082 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
5084 m = TAILQ_NEXT(m, listq);
5092 * this code makes some *MAJOR* assumptions:
5093 * 1. Current pmap & pmap exists.
5096 * 4. No page table pages.
5097 * but is *MUCH* faster than pmap_enter...
5101 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
5103 struct rwlock *lock;
5107 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
5114 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
5115 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
5117 struct spglist free;
5118 pt_entry_t *pte, PG_V;
5121 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
5122 (m->oflags & VPO_UNMANAGED) != 0,
5123 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
5124 PG_V = pmap_valid_bit(pmap);
5125 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5128 * In the case that a page table page is not
5129 * resident, we are creating it here.
5131 if (va < VM_MAXUSER_ADDRESS) {
5132 vm_pindex_t ptepindex;
5136 * Calculate pagetable page index
5138 ptepindex = pmap_pde_pindex(va);
5139 if (mpte && (mpte->pindex == ptepindex)) {
5143 * Get the page directory entry
5145 ptepa = pmap_pde(pmap, va);
5148 * If the page table page is mapped, we just increment
5149 * the hold count, and activate it. Otherwise, we
5150 * attempt to allocate a page table page. If this
5151 * attempt fails, we don't retry. Instead, we give up.
5153 if (ptepa && (*ptepa & PG_V) != 0) {
5156 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
5160 * Pass NULL instead of the PV list lock
5161 * pointer, because we don't intend to sleep.
5163 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
5168 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
5169 pte = &pte[pmap_pte_index(va)];
5183 * Enter on the PV list if part of our managed memory.
5185 if ((m->oflags & VPO_UNMANAGED) == 0 &&
5186 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
5189 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
5191 * Although "va" is not mapped, paging-
5192 * structure caches could nonetheless have
5193 * entries that refer to the freed page table
5194 * pages. Invalidate those entries.
5196 pmap_invalidate_page(pmap, va);
5197 pmap_free_zero_pages(&free);
5205 * Increment counters
5207 pmap_resident_count_inc(pmap, 1);
5209 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
5210 if ((prot & VM_PROT_EXECUTE) == 0)
5214 * Now validate mapping with RO protection
5216 if ((m->oflags & VPO_UNMANAGED) != 0)
5217 pte_store(pte, pa | PG_V | PG_U);
5219 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
5224 * Make a temporary mapping for a physical address. This is only intended
5225 * to be used for panic dumps.
5228 pmap_kenter_temporary(vm_paddr_t pa, int i)
5232 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
5233 pmap_kenter(va, pa);
5235 return ((void *)crashdumpmap);
5239 * This code maps large physical mmap regions into the
5240 * processor address space. Note that some shortcuts
5241 * are taken, but the code works.
5244 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
5245 vm_pindex_t pindex, vm_size_t size)
5248 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5249 vm_paddr_t pa, ptepa;
5253 PG_A = pmap_accessed_bit(pmap);
5254 PG_M = pmap_modified_bit(pmap);
5255 PG_V = pmap_valid_bit(pmap);
5256 PG_RW = pmap_rw_bit(pmap);
5258 VM_OBJECT_ASSERT_WLOCKED(object);
5259 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
5260 ("pmap_object_init_pt: non-device object"));
5261 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
5262 if (!pmap_ps_enabled(pmap))
5264 if (!vm_object_populate(object, pindex, pindex + atop(size)))
5266 p = vm_page_lookup(object, pindex);
5267 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5268 ("pmap_object_init_pt: invalid page %p", p));
5269 pat_mode = p->md.pat_mode;
5272 * Abort the mapping if the first page is not physically
5273 * aligned to a 2MB page boundary.
5275 ptepa = VM_PAGE_TO_PHYS(p);
5276 if (ptepa & (NBPDR - 1))
5280 * Skip the first page. Abort the mapping if the rest of
5281 * the pages are not physically contiguous or have differing
5282 * memory attributes.
5284 p = TAILQ_NEXT(p, listq);
5285 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
5287 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5288 ("pmap_object_init_pt: invalid page %p", p));
5289 if (pa != VM_PAGE_TO_PHYS(p) ||
5290 pat_mode != p->md.pat_mode)
5292 p = TAILQ_NEXT(p, listq);
5296 * Map using 2MB pages. Since "ptepa" is 2M aligned and
5297 * "size" is a multiple of 2M, adding the PAT setting to "pa"
5298 * will not affect the termination of this loop.
5301 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
5302 pa < ptepa + size; pa += NBPDR) {
5303 pdpg = pmap_allocpde(pmap, addr, NULL);
5306 * The creation of mappings below is only an
5307 * optimization. If a page directory page
5308 * cannot be allocated without blocking,
5309 * continue on to the next mapping rather than
5315 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5316 pde = &pde[pmap_pde_index(addr)];
5317 if ((*pde & PG_V) == 0) {
5318 pde_store(pde, pa | PG_PS | PG_M | PG_A |
5319 PG_U | PG_RW | PG_V);
5320 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5321 atomic_add_long(&pmap_pde_mappings, 1);
5323 /* Continue on if the PDE is already valid. */
5325 KASSERT(pdpg->wire_count > 0,
5326 ("pmap_object_init_pt: missing reference "
5327 "to page directory page, va: 0x%lx", addr));
5336 * Clear the wired attribute from the mappings for the specified range of
5337 * addresses in the given pmap. Every valid mapping within that range
5338 * must have the wired attribute set. In contrast, invalid mappings
5339 * cannot have the wired attribute set, so they are ignored.
5341 * The wired attribute of the page table entry is not a hardware
5342 * feature, so there is no need to invalidate any TLB entries.
5343 * Since pmap_demote_pde() for the wired entry must never fail,
5344 * pmap_delayed_invl_started()/finished() calls around the
5345 * function are not needed.
5348 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5350 vm_offset_t va_next;
5351 pml4_entry_t *pml4e;
5354 pt_entry_t *pte, PG_V;
5356 PG_V = pmap_valid_bit(pmap);
5358 for (; sva < eva; sva = va_next) {
5359 pml4e = pmap_pml4e(pmap, sva);
5360 if ((*pml4e & PG_V) == 0) {
5361 va_next = (sva + NBPML4) & ~PML4MASK;
5366 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5367 if ((*pdpe & PG_V) == 0) {
5368 va_next = (sva + NBPDP) & ~PDPMASK;
5373 va_next = (sva + NBPDR) & ~PDRMASK;
5376 pde = pmap_pdpe_to_pde(pdpe, sva);
5377 if ((*pde & PG_V) == 0)
5379 if ((*pde & PG_PS) != 0) {
5380 if ((*pde & PG_W) == 0)
5381 panic("pmap_unwire: pde %#jx is missing PG_W",
5385 * Are we unwiring the entire large page? If not,
5386 * demote the mapping and fall through.
5388 if (sva + NBPDR == va_next && eva >= va_next) {
5389 atomic_clear_long(pde, PG_W);
5390 pmap->pm_stats.wired_count -= NBPDR /
5393 } else if (!pmap_demote_pde(pmap, pde, sva))
5394 panic("pmap_unwire: demotion failed");
5398 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
5400 if ((*pte & PG_V) == 0)
5402 if ((*pte & PG_W) == 0)
5403 panic("pmap_unwire: pte %#jx is missing PG_W",
5407 * PG_W must be cleared atomically. Although the pmap
5408 * lock synchronizes access to PG_W, another processor
5409 * could be setting PG_M and/or PG_A concurrently.
5411 atomic_clear_long(pte, PG_W);
5412 pmap->pm_stats.wired_count--;
5419 * Copy the range specified by src_addr/len
5420 * from the source map to the range dst_addr/len
5421 * in the destination map.
5423 * This routine is only advisory and need not do anything.
5427 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5428 vm_offset_t src_addr)
5430 struct rwlock *lock;
5431 struct spglist free;
5433 vm_offset_t end_addr = src_addr + len;
5434 vm_offset_t va_next;
5435 vm_page_t dst_pdpg, dstmpte, srcmpte;
5436 pt_entry_t PG_A, PG_M, PG_V;
5438 if (dst_addr != src_addr)
5441 if (dst_pmap->pm_type != src_pmap->pm_type)
5445 * EPT page table entries that require emulation of A/D bits are
5446 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5447 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5448 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5449 * implementations flag an EPT misconfiguration for exec-only
5450 * mappings we skip this function entirely for emulated pmaps.
5452 if (pmap_emulate_ad_bits(dst_pmap))
5456 if (dst_pmap < src_pmap) {
5457 PMAP_LOCK(dst_pmap);
5458 PMAP_LOCK(src_pmap);
5460 PMAP_LOCK(src_pmap);
5461 PMAP_LOCK(dst_pmap);
5464 PG_A = pmap_accessed_bit(dst_pmap);
5465 PG_M = pmap_modified_bit(dst_pmap);
5466 PG_V = pmap_valid_bit(dst_pmap);
5468 for (addr = src_addr; addr < end_addr; addr = va_next) {
5469 pt_entry_t *src_pte, *dst_pte;
5470 pml4_entry_t *pml4e;
5472 pd_entry_t srcptepaddr, *pde;
5474 KASSERT(addr < UPT_MIN_ADDRESS,
5475 ("pmap_copy: invalid to pmap_copy page tables"));
5477 pml4e = pmap_pml4e(src_pmap, addr);
5478 if ((*pml4e & PG_V) == 0) {
5479 va_next = (addr + NBPML4) & ~PML4MASK;
5485 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5486 if ((*pdpe & PG_V) == 0) {
5487 va_next = (addr + NBPDP) & ~PDPMASK;
5493 va_next = (addr + NBPDR) & ~PDRMASK;
5497 pde = pmap_pdpe_to_pde(pdpe, addr);
5499 if (srcptepaddr == 0)
5502 if (srcptepaddr & PG_PS) {
5503 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5505 dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
5506 if (dst_pdpg == NULL)
5508 pde = (pd_entry_t *)
5509 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
5510 pde = &pde[pmap_pde_index(addr)];
5511 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5512 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
5513 PMAP_ENTER_NORECLAIM, &lock))) {
5514 *pde = srcptepaddr & ~PG_W;
5515 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5516 atomic_add_long(&pmap_pde_mappings, 1);
5518 dst_pdpg->wire_count--;
5522 srcptepaddr &= PG_FRAME;
5523 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5524 KASSERT(srcmpte->wire_count > 0,
5525 ("pmap_copy: source page table page is unused"));
5527 if (va_next > end_addr)
5530 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5531 src_pte = &src_pte[pmap_pte_index(addr)];
5533 while (addr < va_next) {
5537 * we only virtual copy managed pages
5539 if ((ptetemp & PG_MANAGED) != 0) {
5540 if (dstmpte != NULL &&
5541 dstmpte->pindex == pmap_pde_pindex(addr))
5542 dstmpte->wire_count++;
5543 else if ((dstmpte = pmap_allocpte(dst_pmap,
5544 addr, NULL)) == NULL)
5546 dst_pte = (pt_entry_t *)
5547 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5548 dst_pte = &dst_pte[pmap_pte_index(addr)];
5549 if (*dst_pte == 0 &&
5550 pmap_try_insert_pv_entry(dst_pmap, addr,
5551 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5554 * Clear the wired, modified, and
5555 * accessed (referenced) bits
5558 *dst_pte = ptetemp & ~(PG_W | PG_M |
5560 pmap_resident_count_inc(dst_pmap, 1);
5563 if (pmap_unwire_ptp(dst_pmap, addr,
5566 * Although "addr" is not
5567 * mapped, paging-structure
5568 * caches could nonetheless
5569 * have entries that refer to
5570 * the freed page table pages.
5571 * Invalidate those entries.
5573 pmap_invalidate_page(dst_pmap,
5575 pmap_free_zero_pages(&free);
5579 if (dstmpte->wire_count >= srcmpte->wire_count)
5589 PMAP_UNLOCK(src_pmap);
5590 PMAP_UNLOCK(dst_pmap);
5594 * pmap_zero_page zeros the specified hardware page by mapping
5595 * the page into KVM and using bzero to clear its contents.
5598 pmap_zero_page(vm_page_t m)
5600 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5602 pagezero((void *)va);
5606 * pmap_zero_page_area zeros the specified hardware page by mapping
5607 * the page into KVM and using bzero to clear its contents.
5609 * off and size may not cover an area beyond a single hardware page.
5612 pmap_zero_page_area(vm_page_t m, int off, int size)
5614 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5616 if (off == 0 && size == PAGE_SIZE)
5617 pagezero((void *)va);
5619 bzero((char *)va + off, size);
5623 * pmap_zero_page_idle zeros the specified hardware page by mapping
5624 * the page into KVM and using bzero to clear its contents. This
5625 * is intended to be called from the vm_pagezero process only and
5629 pmap_zero_page_idle(vm_page_t m)
5631 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5633 pagezero((void *)va);
5637 * pmap_copy_page copies the specified (machine independent)
5638 * page by mapping the page into virtual memory and using
5639 * bcopy to copy the page, one machine dependent page at a
5643 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5645 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5646 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5648 pagecopy((void *)src, (void *)dst);
5651 int unmapped_buf_allowed = 1;
5654 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5655 vm_offset_t b_offset, int xfersize)
5659 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5663 while (xfersize > 0) {
5664 a_pg_offset = a_offset & PAGE_MASK;
5665 pages[0] = ma[a_offset >> PAGE_SHIFT];
5666 b_pg_offset = b_offset & PAGE_MASK;
5667 pages[1] = mb[b_offset >> PAGE_SHIFT];
5668 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5669 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5670 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5671 a_cp = (char *)vaddr[0] + a_pg_offset;
5672 b_cp = (char *)vaddr[1] + b_pg_offset;
5673 bcopy(a_cp, b_cp, cnt);
5674 if (__predict_false(mapped))
5675 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5683 * Returns true if the pmap's pv is one of the first
5684 * 16 pvs linked to from this page. This count may
5685 * be changed upwards or downwards in the future; it
5686 * is only necessary that true be returned for a small
5687 * subset of pmaps for proper page aging.
5690 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5692 struct md_page *pvh;
5693 struct rwlock *lock;
5698 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5699 ("pmap_page_exists_quick: page %p is not managed", m));
5701 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5703 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5704 if (PV_PMAP(pv) == pmap) {
5712 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5713 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5714 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5715 if (PV_PMAP(pv) == pmap) {
5729 * pmap_page_wired_mappings:
5731 * Return the number of managed mappings to the given physical page
5735 pmap_page_wired_mappings(vm_page_t m)
5737 struct rwlock *lock;
5738 struct md_page *pvh;
5742 int count, md_gen, pvh_gen;
5744 if ((m->oflags & VPO_UNMANAGED) != 0)
5746 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5750 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5752 if (!PMAP_TRYLOCK(pmap)) {
5753 md_gen = m->md.pv_gen;
5757 if (md_gen != m->md.pv_gen) {
5762 pte = pmap_pte(pmap, pv->pv_va);
5763 if ((*pte & PG_W) != 0)
5767 if ((m->flags & PG_FICTITIOUS) == 0) {
5768 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5769 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5771 if (!PMAP_TRYLOCK(pmap)) {
5772 md_gen = m->md.pv_gen;
5773 pvh_gen = pvh->pv_gen;
5777 if (md_gen != m->md.pv_gen ||
5778 pvh_gen != pvh->pv_gen) {
5783 pte = pmap_pde(pmap, pv->pv_va);
5784 if ((*pte & PG_W) != 0)
5794 * Returns TRUE if the given page is mapped individually or as part of
5795 * a 2mpage. Otherwise, returns FALSE.
5798 pmap_page_is_mapped(vm_page_t m)
5800 struct rwlock *lock;
5803 if ((m->oflags & VPO_UNMANAGED) != 0)
5805 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5807 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5808 ((m->flags & PG_FICTITIOUS) == 0 &&
5809 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5815 * Destroy all managed, non-wired mappings in the given user-space
5816 * pmap. This pmap cannot be active on any processor besides the
5819 * This function cannot be applied to the kernel pmap. Moreover, it
5820 * is not intended for general use. It is only to be used during
5821 * process termination. Consequently, it can be implemented in ways
5822 * that make it faster than pmap_remove(). First, it can more quickly
5823 * destroy mappings by iterating over the pmap's collection of PV
5824 * entries, rather than searching the page table. Second, it doesn't
5825 * have to test and clear the page table entries atomically, because
5826 * no processor is currently accessing the user address space. In
5827 * particular, a page table entry's dirty bit won't change state once
5828 * this function starts.
5830 * Although this function destroys all of the pmap's managed,
5831 * non-wired mappings, it can delay and batch the invalidation of TLB
5832 * entries without calling pmap_delayed_invl_started() and
5833 * pmap_delayed_invl_finished(). Because the pmap is not active on
5834 * any other processor, none of these TLB entries will ever be used
5835 * before their eventual invalidation. Consequently, there is no need
5836 * for either pmap_remove_all() or pmap_remove_write() to wait for
5837 * that eventual TLB invalidation.
5840 pmap_remove_pages(pmap_t pmap)
5843 pt_entry_t *pte, tpte;
5844 pt_entry_t PG_M, PG_RW, PG_V;
5845 struct spglist free;
5846 vm_page_t m, mpte, mt;
5848 struct md_page *pvh;
5849 struct pv_chunk *pc, *npc;
5850 struct rwlock *lock;
5852 uint64_t inuse, bitmask;
5853 int allfree, field, freed, idx;
5854 boolean_t superpage;
5858 * Assert that the given pmap is only active on the current
5859 * CPU. Unfortunately, we cannot block another CPU from
5860 * activating the pmap while this function is executing.
5862 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5865 cpuset_t other_cpus;
5867 other_cpus = all_cpus;
5869 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5870 CPU_AND(&other_cpus, &pmap->pm_active);
5872 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5877 PG_M = pmap_modified_bit(pmap);
5878 PG_V = pmap_valid_bit(pmap);
5879 PG_RW = pmap_rw_bit(pmap);
5883 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5886 for (field = 0; field < _NPCM; field++) {
5887 inuse = ~pc->pc_map[field] & pc_freemask[field];
5888 while (inuse != 0) {
5890 bitmask = 1UL << bit;
5891 idx = field * 64 + bit;
5892 pv = &pc->pc_pventry[idx];
5895 pte = pmap_pdpe(pmap, pv->pv_va);
5897 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5899 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5902 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5904 pte = &pte[pmap_pte_index(pv->pv_va)];
5908 * Keep track whether 'tpte' is a
5909 * superpage explicitly instead of
5910 * relying on PG_PS being set.
5912 * This is because PG_PS is numerically
5913 * identical to PG_PTE_PAT and thus a
5914 * regular page could be mistaken for
5920 if ((tpte & PG_V) == 0) {
5921 panic("bad pte va %lx pte %lx",
5926 * We cannot remove wired pages from a process' mapping at this time
5934 pa = tpte & PG_PS_FRAME;
5936 pa = tpte & PG_FRAME;
5938 m = PHYS_TO_VM_PAGE(pa);
5939 KASSERT(m->phys_addr == pa,
5940 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5941 m, (uintmax_t)m->phys_addr,
5944 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5945 m < &vm_page_array[vm_page_array_size],
5946 ("pmap_remove_pages: bad tpte %#jx",
5952 * Update the vm_page_t clean/reference bits.
5954 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5956 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5962 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5965 pc->pc_map[field] |= bitmask;
5967 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
5968 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
5969 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5971 if (TAILQ_EMPTY(&pvh->pv_list)) {
5972 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5973 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
5974 TAILQ_EMPTY(&mt->md.pv_list))
5975 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5977 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
5979 pmap_resident_count_dec(pmap, 1);
5980 KASSERT(mpte->wire_count == NPTEPG,
5981 ("pmap_remove_pages: pte page wire count error"));
5982 mpte->wire_count = 0;
5983 pmap_add_delayed_free_list(mpte, &free, FALSE);
5986 pmap_resident_count_dec(pmap, 1);
5987 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5989 if ((m->aflags & PGA_WRITEABLE) != 0 &&
5990 TAILQ_EMPTY(&m->md.pv_list) &&
5991 (m->flags & PG_FICTITIOUS) == 0) {
5992 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5993 if (TAILQ_EMPTY(&pvh->pv_list))
5994 vm_page_aflag_clear(m, PGA_WRITEABLE);
5997 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
6001 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
6002 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
6003 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
6005 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
6011 pmap_invalidate_all(pmap);
6013 pmap_free_zero_pages(&free);
6017 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
6019 struct rwlock *lock;
6021 struct md_page *pvh;
6022 pt_entry_t *pte, mask;
6023 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6025 int md_gen, pvh_gen;
6029 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6032 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6034 if (!PMAP_TRYLOCK(pmap)) {
6035 md_gen = m->md.pv_gen;
6039 if (md_gen != m->md.pv_gen) {
6044 pte = pmap_pte(pmap, pv->pv_va);
6047 PG_M = pmap_modified_bit(pmap);
6048 PG_RW = pmap_rw_bit(pmap);
6049 mask |= PG_RW | PG_M;
6052 PG_A = pmap_accessed_bit(pmap);
6053 PG_V = pmap_valid_bit(pmap);
6054 mask |= PG_V | PG_A;
6056 rv = (*pte & mask) == mask;
6061 if ((m->flags & PG_FICTITIOUS) == 0) {
6062 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6063 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
6065 if (!PMAP_TRYLOCK(pmap)) {
6066 md_gen = m->md.pv_gen;
6067 pvh_gen = pvh->pv_gen;
6071 if (md_gen != m->md.pv_gen ||
6072 pvh_gen != pvh->pv_gen) {
6077 pte = pmap_pde(pmap, pv->pv_va);
6080 PG_M = pmap_modified_bit(pmap);
6081 PG_RW = pmap_rw_bit(pmap);
6082 mask |= PG_RW | PG_M;
6085 PG_A = pmap_accessed_bit(pmap);
6086 PG_V = pmap_valid_bit(pmap);
6087 mask |= PG_V | PG_A;
6089 rv = (*pte & mask) == mask;
6103 * Return whether or not the specified physical page was modified
6104 * in any physical maps.
6107 pmap_is_modified(vm_page_t m)
6110 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6111 ("pmap_is_modified: page %p is not managed", m));
6114 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6115 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
6116 * is clear, no PTEs can have PG_M set.
6118 VM_OBJECT_ASSERT_WLOCKED(m->object);
6119 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6121 return (pmap_page_test_mappings(m, FALSE, TRUE));
6125 * pmap_is_prefaultable:
6127 * Return whether or not the specified virtual address is eligible
6131 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
6134 pt_entry_t *pte, PG_V;
6137 PG_V = pmap_valid_bit(pmap);
6140 pde = pmap_pde(pmap, addr);
6141 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
6142 pte = pmap_pde_to_pte(pde, addr);
6143 rv = (*pte & PG_V) == 0;
6150 * pmap_is_referenced:
6152 * Return whether or not the specified physical page was referenced
6153 * in any physical maps.
6156 pmap_is_referenced(vm_page_t m)
6159 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6160 ("pmap_is_referenced: page %p is not managed", m));
6161 return (pmap_page_test_mappings(m, TRUE, FALSE));
6165 * Clear the write and modified bits in each of the given page's mappings.
6168 pmap_remove_write(vm_page_t m)
6170 struct md_page *pvh;
6172 struct rwlock *lock;
6173 pv_entry_t next_pv, pv;
6175 pt_entry_t oldpte, *pte, PG_M, PG_RW;
6177 int pvh_gen, md_gen;
6179 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6180 ("pmap_remove_write: page %p is not managed", m));
6183 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6184 * set by another thread while the object is locked. Thus,
6185 * if PGA_WRITEABLE is clear, no page table entries need updating.
6187 VM_OBJECT_ASSERT_WLOCKED(m->object);
6188 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6190 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6191 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6192 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6195 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6197 if (!PMAP_TRYLOCK(pmap)) {
6198 pvh_gen = pvh->pv_gen;
6202 if (pvh_gen != pvh->pv_gen) {
6208 PG_RW = pmap_rw_bit(pmap);
6210 pde = pmap_pde(pmap, va);
6211 if ((*pde & PG_RW) != 0)
6212 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6213 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6214 ("inconsistent pv lock %p %p for page %p",
6215 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6218 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6220 if (!PMAP_TRYLOCK(pmap)) {
6221 pvh_gen = pvh->pv_gen;
6222 md_gen = m->md.pv_gen;
6226 if (pvh_gen != pvh->pv_gen ||
6227 md_gen != m->md.pv_gen) {
6233 PG_M = pmap_modified_bit(pmap);
6234 PG_RW = pmap_rw_bit(pmap);
6235 pde = pmap_pde(pmap, pv->pv_va);
6236 KASSERT((*pde & PG_PS) == 0,
6237 ("pmap_remove_write: found a 2mpage in page %p's pv list",
6239 pte = pmap_pde_to_pte(pde, pv->pv_va);
6242 if (oldpte & PG_RW) {
6243 if (!atomic_cmpset_long(pte, oldpte, oldpte &
6246 if ((oldpte & PG_M) != 0)
6248 pmap_invalidate_page(pmap, pv->pv_va);
6253 vm_page_aflag_clear(m, PGA_WRITEABLE);
6254 pmap_delayed_invl_wait(m);
6257 static __inline boolean_t
6258 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
6261 if (!pmap_emulate_ad_bits(pmap))
6264 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
6267 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
6268 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
6269 * if the EPT_PG_WRITE bit is set.
6271 if ((pte & EPT_PG_WRITE) != 0)
6275 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
6277 if ((pte & EPT_PG_EXECUTE) == 0 ||
6278 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
6285 * pmap_ts_referenced:
6287 * Return a count of reference bits for a page, clearing those bits.
6288 * It is not necessary for every reference bit to be cleared, but it
6289 * is necessary that 0 only be returned when there are truly no
6290 * reference bits set.
6292 * As an optimization, update the page's dirty field if a modified bit is
6293 * found while counting reference bits. This opportunistic update can be
6294 * performed at low cost and can eliminate the need for some future calls
6295 * to pmap_is_modified(). However, since this function stops after
6296 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
6297 * dirty pages. Those dirty pages will only be detected by a future call
6298 * to pmap_is_modified().
6300 * A DI block is not needed within this function, because
6301 * invalidations are performed before the PV list lock is
6305 pmap_ts_referenced(vm_page_t m)
6307 struct md_page *pvh;
6310 struct rwlock *lock;
6311 pd_entry_t oldpde, *pde;
6312 pt_entry_t *pte, PG_A, PG_M, PG_RW;
6315 int cleared, md_gen, not_cleared, pvh_gen;
6316 struct spglist free;
6319 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6320 ("pmap_ts_referenced: page %p is not managed", m));
6323 pa = VM_PAGE_TO_PHYS(m);
6324 lock = PHYS_TO_PV_LIST_LOCK(pa);
6325 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
6329 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6330 goto small_mappings;
6336 if (!PMAP_TRYLOCK(pmap)) {
6337 pvh_gen = pvh->pv_gen;
6341 if (pvh_gen != pvh->pv_gen) {
6346 PG_A = pmap_accessed_bit(pmap);
6347 PG_M = pmap_modified_bit(pmap);
6348 PG_RW = pmap_rw_bit(pmap);
6350 pde = pmap_pde(pmap, pv->pv_va);
6352 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6354 * Although "oldpde" is mapping a 2MB page, because
6355 * this function is called at a 4KB page granularity,
6356 * we only update the 4KB page under test.
6360 if ((oldpde & PG_A) != 0) {
6362 * Since this reference bit is shared by 512 4KB
6363 * pages, it should not be cleared every time it is
6364 * tested. Apply a simple "hash" function on the
6365 * physical page number, the virtual superpage number,
6366 * and the pmap address to select one 4KB page out of
6367 * the 512 on which testing the reference bit will
6368 * result in clearing that reference bit. This
6369 * function is designed to avoid the selection of the
6370 * same 4KB page for every 2MB page mapping.
6372 * On demotion, a mapping that hasn't been referenced
6373 * is simply destroyed. To avoid the possibility of a
6374 * subsequent page fault on a demoted wired mapping,
6375 * always leave its reference bit set. Moreover,
6376 * since the superpage is wired, the current state of
6377 * its reference bit won't affect page replacement.
6379 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
6380 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
6381 (oldpde & PG_W) == 0) {
6382 if (safe_to_clear_referenced(pmap, oldpde)) {
6383 atomic_clear_long(pde, PG_A);
6384 pmap_invalidate_page(pmap, pv->pv_va);
6386 } else if (pmap_demote_pde_locked(pmap, pde,
6387 pv->pv_va, &lock)) {
6389 * Remove the mapping to a single page
6390 * so that a subsequent access may
6391 * repromote. Since the underlying
6392 * page table page is fully populated,
6393 * this removal never frees a page
6397 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6399 pte = pmap_pde_to_pte(pde, va);
6400 pmap_remove_pte(pmap, pte, va, *pde,
6402 pmap_invalidate_page(pmap, va);
6408 * The superpage mapping was removed
6409 * entirely and therefore 'pv' is no
6417 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6418 ("inconsistent pv lock %p %p for page %p",
6419 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6424 /* Rotate the PV list if it has more than one entry. */
6425 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6426 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6427 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6430 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6432 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6434 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6441 if (!PMAP_TRYLOCK(pmap)) {
6442 pvh_gen = pvh->pv_gen;
6443 md_gen = m->md.pv_gen;
6447 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6452 PG_A = pmap_accessed_bit(pmap);
6453 PG_M = pmap_modified_bit(pmap);
6454 PG_RW = pmap_rw_bit(pmap);
6455 pde = pmap_pde(pmap, pv->pv_va);
6456 KASSERT((*pde & PG_PS) == 0,
6457 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6459 pte = pmap_pde_to_pte(pde, pv->pv_va);
6460 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6462 if ((*pte & PG_A) != 0) {
6463 if (safe_to_clear_referenced(pmap, *pte)) {
6464 atomic_clear_long(pte, PG_A);
6465 pmap_invalidate_page(pmap, pv->pv_va);
6467 } else if ((*pte & PG_W) == 0) {
6469 * Wired pages cannot be paged out so
6470 * doing accessed bit emulation for
6471 * them is wasted effort. We do the
6472 * hard work for unwired pages only.
6474 pmap_remove_pte(pmap, pte, pv->pv_va,
6475 *pde, &free, &lock);
6476 pmap_invalidate_page(pmap, pv->pv_va);
6481 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6482 ("inconsistent pv lock %p %p for page %p",
6483 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6488 /* Rotate the PV list if it has more than one entry. */
6489 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6490 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6491 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6494 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6495 not_cleared < PMAP_TS_REFERENCED_MAX);
6498 pmap_free_zero_pages(&free);
6499 return (cleared + not_cleared);
6503 * Apply the given advice to the specified range of addresses within the
6504 * given pmap. Depending on the advice, clear the referenced and/or
6505 * modified flags in each mapping and set the mapped page's dirty field.
6508 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6510 struct rwlock *lock;
6511 pml4_entry_t *pml4e;
6513 pd_entry_t oldpde, *pde;
6514 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6515 vm_offset_t va, va_next;
6517 boolean_t anychanged;
6519 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6523 * A/D bit emulation requires an alternate code path when clearing
6524 * the modified and accessed bits below. Since this function is
6525 * advisory in nature we skip it entirely for pmaps that require
6526 * A/D bit emulation.
6528 if (pmap_emulate_ad_bits(pmap))
6531 PG_A = pmap_accessed_bit(pmap);
6532 PG_G = pmap_global_bit(pmap);
6533 PG_M = pmap_modified_bit(pmap);
6534 PG_V = pmap_valid_bit(pmap);
6535 PG_RW = pmap_rw_bit(pmap);
6537 pmap_delayed_invl_started();
6539 for (; sva < eva; sva = va_next) {
6540 pml4e = pmap_pml4e(pmap, sva);
6541 if ((*pml4e & PG_V) == 0) {
6542 va_next = (sva + NBPML4) & ~PML4MASK;
6547 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6548 if ((*pdpe & PG_V) == 0) {
6549 va_next = (sva + NBPDP) & ~PDPMASK;
6554 va_next = (sva + NBPDR) & ~PDRMASK;
6557 pde = pmap_pdpe_to_pde(pdpe, sva);
6559 if ((oldpde & PG_V) == 0)
6561 else if ((oldpde & PG_PS) != 0) {
6562 if ((oldpde & PG_MANAGED) == 0)
6565 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6570 * The large page mapping was destroyed.
6576 * Unless the page mappings are wired, remove the
6577 * mapping to a single page so that a subsequent
6578 * access may repromote. Since the underlying page
6579 * table page is fully populated, this removal never
6580 * frees a page table page.
6582 if ((oldpde & PG_W) == 0) {
6583 pte = pmap_pde_to_pte(pde, sva);
6584 KASSERT((*pte & PG_V) != 0,
6585 ("pmap_advise: invalid PTE"));
6586 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6596 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6598 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6600 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6601 if (advice == MADV_DONTNEED) {
6603 * Future calls to pmap_is_modified()
6604 * can be avoided by making the page
6607 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6610 atomic_clear_long(pte, PG_M | PG_A);
6611 } else if ((*pte & PG_A) != 0)
6612 atomic_clear_long(pte, PG_A);
6616 if ((*pte & PG_G) != 0) {
6623 if (va != va_next) {
6624 pmap_invalidate_range(pmap, va, sva);
6629 pmap_invalidate_range(pmap, va, sva);
6632 pmap_invalidate_all(pmap);
6634 pmap_delayed_invl_finished();
6638 * Clear the modify bits on the specified physical page.
6641 pmap_clear_modify(vm_page_t m)
6643 struct md_page *pvh;
6645 pv_entry_t next_pv, pv;
6646 pd_entry_t oldpde, *pde;
6647 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6648 struct rwlock *lock;
6650 int md_gen, pvh_gen;
6652 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6653 ("pmap_clear_modify: page %p is not managed", m));
6654 VM_OBJECT_ASSERT_WLOCKED(m->object);
6655 KASSERT(!vm_page_xbusied(m),
6656 ("pmap_clear_modify: page %p is exclusive busied", m));
6659 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6660 * If the object containing the page is locked and the page is not
6661 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6663 if ((m->aflags & PGA_WRITEABLE) == 0)
6665 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6666 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6667 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6670 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6672 if (!PMAP_TRYLOCK(pmap)) {
6673 pvh_gen = pvh->pv_gen;
6677 if (pvh_gen != pvh->pv_gen) {
6682 PG_M = pmap_modified_bit(pmap);
6683 PG_V = pmap_valid_bit(pmap);
6684 PG_RW = pmap_rw_bit(pmap);
6686 pde = pmap_pde(pmap, va);
6688 if ((oldpde & PG_RW) != 0) {
6689 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6690 if ((oldpde & PG_W) == 0) {
6692 * Write protect the mapping to a
6693 * single page so that a subsequent
6694 * write access may repromote.
6696 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6698 pte = pmap_pde_to_pte(pde, va);
6700 if ((oldpte & PG_V) != 0) {
6701 while (!atomic_cmpset_long(pte,
6703 oldpte & ~(PG_M | PG_RW)))
6706 pmap_invalidate_page(pmap, va);
6713 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6715 if (!PMAP_TRYLOCK(pmap)) {
6716 md_gen = m->md.pv_gen;
6717 pvh_gen = pvh->pv_gen;
6721 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6726 PG_M = pmap_modified_bit(pmap);
6727 PG_RW = pmap_rw_bit(pmap);
6728 pde = pmap_pde(pmap, pv->pv_va);
6729 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6730 " a 2mpage in page %p's pv list", m));
6731 pte = pmap_pde_to_pte(pde, pv->pv_va);
6732 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6733 atomic_clear_long(pte, PG_M);
6734 pmap_invalidate_page(pmap, pv->pv_va);
6742 * Miscellaneous support routines follow
6745 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6746 static __inline void
6747 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6752 * The cache mode bits are all in the low 32-bits of the
6753 * PTE, so we can just spin on updating the low 32-bits.
6756 opte = *(u_int *)pte;
6757 npte = opte & ~mask;
6759 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6762 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6763 static __inline void
6764 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6769 * The cache mode bits are all in the low 32-bits of the
6770 * PDE, so we can just spin on updating the low 32-bits.
6773 opde = *(u_int *)pde;
6774 npde = opde & ~mask;
6776 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6780 * Map a set of physical memory pages into the kernel virtual
6781 * address space. Return a pointer to where it is mapped. This
6782 * routine is intended to be used for mapping device memory,
6786 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6788 struct pmap_preinit_mapping *ppim;
6789 vm_offset_t va, offset;
6793 offset = pa & PAGE_MASK;
6794 size = round_page(offset + size);
6795 pa = trunc_page(pa);
6797 if (!pmap_initialized) {
6799 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6800 ppim = pmap_preinit_mapping + i;
6801 if (ppim->va == 0) {
6805 ppim->va = virtual_avail;
6806 virtual_avail += size;
6812 panic("%s: too many preinit mappings", __func__);
6815 * If we have a preinit mapping, re-use it.
6817 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6818 ppim = pmap_preinit_mapping + i;
6819 if (ppim->pa == pa && ppim->sz == size &&
6821 return ((void *)(ppim->va + offset));
6824 * If the specified range of physical addresses fits within
6825 * the direct map window, use the direct map.
6827 if (pa < dmaplimit && pa + size < dmaplimit) {
6828 va = PHYS_TO_DMAP(pa);
6829 if (!pmap_change_attr(va, size, mode))
6830 return ((void *)(va + offset));
6832 va = kva_alloc(size);
6834 panic("%s: Couldn't allocate KVA", __func__);
6836 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6837 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6838 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6839 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6840 return ((void *)(va + offset));
6844 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6847 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6851 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6854 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6858 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6860 struct pmap_preinit_mapping *ppim;
6864 /* If we gave a direct map region in pmap_mapdev, do nothing */
6865 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6867 offset = va & PAGE_MASK;
6868 size = round_page(offset + size);
6869 va = trunc_page(va);
6870 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6871 ppim = pmap_preinit_mapping + i;
6872 if (ppim->va == va && ppim->sz == size) {
6873 if (pmap_initialized)
6879 if (va + size == virtual_avail)
6884 if (pmap_initialized)
6889 * Tries to demote a 1GB page mapping.
6892 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6894 pdp_entry_t newpdpe, oldpdpe;
6895 pd_entry_t *firstpde, newpde, *pde;
6896 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6900 PG_A = pmap_accessed_bit(pmap);
6901 PG_M = pmap_modified_bit(pmap);
6902 PG_V = pmap_valid_bit(pmap);
6903 PG_RW = pmap_rw_bit(pmap);
6905 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6907 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6908 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6909 if ((pdpg = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6910 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6911 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6912 " in pmap %p", va, pmap);
6915 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
6916 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
6917 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6918 KASSERT((oldpdpe & PG_A) != 0,
6919 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6920 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6921 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
6925 * Initialize the page directory page.
6927 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
6933 * Demote the mapping.
6938 * Invalidate a stale recursive mapping of the page directory page.
6940 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
6942 pmap_pdpe_demotions++;
6943 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
6944 " in pmap %p", va, pmap);
6949 * Sets the memory attribute for the specified page.
6952 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6955 m->md.pat_mode = ma;
6958 * If "m" is a normal page, update its direct mapping. This update
6959 * can be relied upon to perform any cache operations that are
6960 * required for data coherence.
6962 if ((m->flags & PG_FICTITIOUS) == 0 &&
6963 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6965 panic("memory attribute change on the direct map failed");
6969 * Changes the specified virtual address range's memory type to that given by
6970 * the parameter "mode". The specified virtual address range must be
6971 * completely contained within either the direct map or the kernel map. If
6972 * the virtual address range is contained within the kernel map, then the
6973 * memory type for each of the corresponding ranges of the direct map is also
6974 * changed. (The corresponding ranges of the direct map are those ranges that
6975 * map the same physical pages as the specified virtual address range.) These
6976 * changes to the direct map are necessary because Intel describes the
6977 * behavior of their processors as "undefined" if two or more mappings to the
6978 * same physical page have different memory types.
6980 * Returns zero if the change completed successfully, and either EINVAL or
6981 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6982 * of the virtual address range was not mapped, and ENOMEM is returned if
6983 * there was insufficient memory available to complete the change. In the
6984 * latter case, the memory type may have been changed on some part of the
6985 * virtual address range or the direct map.
6988 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6992 PMAP_LOCK(kernel_pmap);
6993 error = pmap_change_attr_locked(va, size, mode);
6994 PMAP_UNLOCK(kernel_pmap);
6999 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
7001 vm_offset_t base, offset, tmpva;
7002 vm_paddr_t pa_start, pa_end, pa_end1;
7006 int cache_bits_pte, cache_bits_pde, error;
7009 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
7010 base = trunc_page(va);
7011 offset = va & PAGE_MASK;
7012 size = round_page(offset + size);
7015 * Only supported on kernel virtual addresses, including the direct
7016 * map but excluding the recursive map.
7018 if (base < DMAP_MIN_ADDRESS)
7021 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
7022 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
7026 * Pages that aren't mapped aren't supported. Also break down 2MB pages
7027 * into 4KB pages if required.
7029 for (tmpva = base; tmpva < base + size; ) {
7030 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7031 if (pdpe == NULL || *pdpe == 0)
7033 if (*pdpe & PG_PS) {
7035 * If the current 1GB page already has the required
7036 * memory type, then we need not demote this page. Just
7037 * increment tmpva to the next 1GB page frame.
7039 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
7040 tmpva = trunc_1gpage(tmpva) + NBPDP;
7045 * If the current offset aligns with a 1GB page frame
7046 * and there is at least 1GB left within the range, then
7047 * we need not break down this page into 2MB pages.
7049 if ((tmpva & PDPMASK) == 0 &&
7050 tmpva + PDPMASK < base + size) {
7054 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
7057 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7062 * If the current 2MB page already has the required
7063 * memory type, then we need not demote this page. Just
7064 * increment tmpva to the next 2MB page frame.
7066 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
7067 tmpva = trunc_2mpage(tmpva) + NBPDR;
7072 * If the current offset aligns with a 2MB page frame
7073 * and there is at least 2MB left within the range, then
7074 * we need not break down this page into 4KB pages.
7076 if ((tmpva & PDRMASK) == 0 &&
7077 tmpva + PDRMASK < base + size) {
7081 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
7084 pte = pmap_pde_to_pte(pde, tmpva);
7092 * Ok, all the pages exist, so run through them updating their
7093 * cache mode if required.
7095 pa_start = pa_end = 0;
7096 for (tmpva = base; tmpva < base + size; ) {
7097 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7098 if (*pdpe & PG_PS) {
7099 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
7100 pmap_pde_attr(pdpe, cache_bits_pde,
7104 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7105 (*pdpe & PG_PS_FRAME) < dmaplimit) {
7106 if (pa_start == pa_end) {
7107 /* Start physical address run. */
7108 pa_start = *pdpe & PG_PS_FRAME;
7109 pa_end = pa_start + NBPDP;
7110 } else if (pa_end == (*pdpe & PG_PS_FRAME))
7113 /* Run ended, update direct map. */
7114 error = pmap_change_attr_locked(
7115 PHYS_TO_DMAP(pa_start),
7116 pa_end - pa_start, mode);
7119 /* Start physical address run. */
7120 pa_start = *pdpe & PG_PS_FRAME;
7121 pa_end = pa_start + NBPDP;
7124 tmpva = trunc_1gpage(tmpva) + NBPDP;
7127 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7129 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
7130 pmap_pde_attr(pde, cache_bits_pde,
7134 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7135 (*pde & PG_PS_FRAME) < dmaplimit) {
7136 if (pa_start == pa_end) {
7137 /* Start physical address run. */
7138 pa_start = *pde & PG_PS_FRAME;
7139 pa_end = pa_start + NBPDR;
7140 } else if (pa_end == (*pde & PG_PS_FRAME))
7143 /* Run ended, update direct map. */
7144 error = pmap_change_attr_locked(
7145 PHYS_TO_DMAP(pa_start),
7146 pa_end - pa_start, mode);
7149 /* Start physical address run. */
7150 pa_start = *pde & PG_PS_FRAME;
7151 pa_end = pa_start + NBPDR;
7154 tmpva = trunc_2mpage(tmpva) + NBPDR;
7156 pte = pmap_pde_to_pte(pde, tmpva);
7157 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
7158 pmap_pte_attr(pte, cache_bits_pte,
7162 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7163 (*pte & PG_FRAME) < dmaplimit) {
7164 if (pa_start == pa_end) {
7165 /* Start physical address run. */
7166 pa_start = *pte & PG_FRAME;
7167 pa_end = pa_start + PAGE_SIZE;
7168 } else if (pa_end == (*pte & PG_FRAME))
7169 pa_end += PAGE_SIZE;
7171 /* Run ended, update direct map. */
7172 error = pmap_change_attr_locked(
7173 PHYS_TO_DMAP(pa_start),
7174 pa_end - pa_start, mode);
7177 /* Start physical address run. */
7178 pa_start = *pte & PG_FRAME;
7179 pa_end = pa_start + PAGE_SIZE;
7185 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
7186 pa_end1 = MIN(pa_end, dmaplimit);
7187 if (pa_start != pa_end1)
7188 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
7189 pa_end1 - pa_start, mode);
7193 * Flush CPU caches if required to make sure any data isn't cached that
7194 * shouldn't be, etc.
7197 pmap_invalidate_range(kernel_pmap, base, tmpva);
7198 pmap_invalidate_cache_range(base, tmpva, FALSE);
7204 * Demotes any mapping within the direct map region that covers more than the
7205 * specified range of physical addresses. This range's size must be a power
7206 * of two and its starting address must be a multiple of its size. Since the
7207 * demotion does not change any attributes of the mapping, a TLB invalidation
7208 * is not mandatory. The caller may, however, request a TLB invalidation.
7211 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
7220 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
7221 KASSERT((base & (len - 1)) == 0,
7222 ("pmap_demote_DMAP: base is not a multiple of len"));
7223 if (len < NBPDP && base < dmaplimit) {
7224 va = PHYS_TO_DMAP(base);
7226 PMAP_LOCK(kernel_pmap);
7227 pdpe = pmap_pdpe(kernel_pmap, va);
7228 if ((*pdpe & X86_PG_V) == 0)
7229 panic("pmap_demote_DMAP: invalid PDPE");
7230 if ((*pdpe & PG_PS) != 0) {
7231 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
7232 panic("pmap_demote_DMAP: PDPE failed");
7236 pde = pmap_pdpe_to_pde(pdpe, va);
7237 if ((*pde & X86_PG_V) == 0)
7238 panic("pmap_demote_DMAP: invalid PDE");
7239 if ((*pde & PG_PS) != 0) {
7240 if (!pmap_demote_pde(kernel_pmap, pde, va))
7241 panic("pmap_demote_DMAP: PDE failed");
7245 if (changed && invalidate)
7246 pmap_invalidate_page(kernel_pmap, va);
7247 PMAP_UNLOCK(kernel_pmap);
7252 * perform the pmap work for mincore
7255 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
7258 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
7262 PG_A = pmap_accessed_bit(pmap);
7263 PG_M = pmap_modified_bit(pmap);
7264 PG_V = pmap_valid_bit(pmap);
7265 PG_RW = pmap_rw_bit(pmap);
7269 pdep = pmap_pde(pmap, addr);
7270 if (pdep != NULL && (*pdep & PG_V)) {
7271 if (*pdep & PG_PS) {
7273 /* Compute the physical address of the 4KB page. */
7274 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
7276 val = MINCORE_SUPER;
7278 pte = *pmap_pde_to_pte(pdep, addr);
7279 pa = pte & PG_FRAME;
7287 if ((pte & PG_V) != 0) {
7288 val |= MINCORE_INCORE;
7289 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7290 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
7291 if ((pte & PG_A) != 0)
7292 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
7294 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
7295 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
7296 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
7297 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
7298 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
7301 PA_UNLOCK_COND(*locked_pa);
7307 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
7309 uint32_t gen, new_gen, pcid_next;
7311 CRITICAL_ASSERT(curthread);
7312 gen = PCPU_GET(pcid_gen);
7313 if (!pti && (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN ||
7314 pmap->pm_pcids[cpuid].pm_gen == gen))
7315 return (CR3_PCID_SAVE);
7316 pcid_next = PCPU_GET(pcid_next);
7317 KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
7318 (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
7319 ("cpu %d pcid_next %#x", cpuid, pcid_next));
7320 if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
7321 (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
7325 PCPU_SET(pcid_gen, new_gen);
7326 pcid_next = PMAP_PCID_KERN + 1;
7330 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
7331 pmap->pm_pcids[cpuid].pm_gen = new_gen;
7332 PCPU_SET(pcid_next, pcid_next + 1);
7337 pmap_activate_sw(struct thread *td)
7339 pmap_t oldpmap, pmap;
7340 struct invpcid_descr d;
7341 uint64_t cached, cr3, kcr3, ucr3;
7345 oldpmap = PCPU_GET(curpmap);
7346 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7347 if (oldpmap == pmap)
7349 cpuid = PCPU_GET(cpuid);
7351 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7353 CPU_SET(cpuid, &pmap->pm_active);
7356 if (pmap_pcid_enabled) {
7357 cached = pmap_pcid_alloc(pmap, cpuid);
7358 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
7359 pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
7360 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
7361 pmap->pm_pcids[cpuid].pm_pcid));
7362 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
7363 pmap == kernel_pmap,
7364 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
7365 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
7368 * If the INVPCID instruction is not available,
7369 * invltlb_pcid_handler() is used for handle
7370 * invalidate_all IPI, which checks for curpmap ==
7371 * smp_tlb_pmap. Below operations sequence has a
7372 * window where %CR3 is loaded with the new pmap's
7373 * PML4 address, but curpmap value is not yet updated.
7374 * This causes invltlb IPI handler, called between the
7375 * updates, to execute as NOP, which leaves stale TLB
7378 * Note that the most typical use of
7379 * pmap_activate_sw(), from the context switch, is
7380 * immune to this race, because interrupts are
7381 * disabled (while the thread lock is owned), and IPI
7382 * happends after curpmap is updated. Protect other
7383 * callers in a similar way, by disabling interrupts
7384 * around the %cr3 register reload and curpmap
7388 rflags = intr_disable();
7390 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
7391 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
7394 PCPU_INC(pm_save_cnt);
7396 PCPU_SET(curpmap, pmap);
7398 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid;
7399 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[cpuid].pm_pcid |
7403 * Manually invalidate translations cached
7404 * from the user page table, which are not
7405 * flushed by reload of cr3 with the kernel
7406 * page table pointer above.
7408 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
7409 if (invpcid_works) {
7410 d.pcid = PMAP_PCID_USER_PT |
7411 pmap->pm_pcids[cpuid].pm_pcid;
7414 invpcid(&d, INVPCID_CTX);
7416 pmap_pti_pcid_invalidate(ucr3, kcr3);
7420 PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
7421 PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
7424 intr_restore(rflags);
7425 } else if (cr3 != pmap->pm_cr3) {
7426 load_cr3(pmap->pm_cr3);
7427 PCPU_SET(curpmap, pmap);
7429 PCPU_SET(kcr3, pmap->pm_cr3);
7430 PCPU_SET(ucr3, pmap->pm_ucr3);
7434 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
7436 CPU_CLR(cpuid, &oldpmap->pm_active);
7441 pmap_activate(struct thread *td)
7445 pmap_activate_sw(td);
7450 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
7455 * Increase the starting virtual address of the given mapping if a
7456 * different alignment might result in more superpage mappings.
7459 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7460 vm_offset_t *addr, vm_size_t size)
7462 vm_offset_t superpage_offset;
7466 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7467 offset += ptoa(object->pg_color);
7468 superpage_offset = offset & PDRMASK;
7469 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
7470 (*addr & PDRMASK) == superpage_offset)
7472 if ((*addr & PDRMASK) < superpage_offset)
7473 *addr = (*addr & ~PDRMASK) + superpage_offset;
7475 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
7479 static unsigned long num_dirty_emulations;
7480 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
7481 &num_dirty_emulations, 0, NULL);
7483 static unsigned long num_accessed_emulations;
7484 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
7485 &num_accessed_emulations, 0, NULL);
7487 static unsigned long num_superpage_accessed_emulations;
7488 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7489 &num_superpage_accessed_emulations, 0, NULL);
7491 static unsigned long ad_emulation_superpage_promotions;
7492 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7493 &ad_emulation_superpage_promotions, 0, NULL);
7494 #endif /* INVARIANTS */
7497 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7500 struct rwlock *lock;
7501 #if VM_NRESERVLEVEL > 0
7505 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7507 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7508 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7510 if (!pmap_emulate_ad_bits(pmap))
7513 PG_A = pmap_accessed_bit(pmap);
7514 PG_M = pmap_modified_bit(pmap);
7515 PG_V = pmap_valid_bit(pmap);
7516 PG_RW = pmap_rw_bit(pmap);
7522 pde = pmap_pde(pmap, va);
7523 if (pde == NULL || (*pde & PG_V) == 0)
7526 if ((*pde & PG_PS) != 0) {
7527 if (ftype == VM_PROT_READ) {
7529 atomic_add_long(&num_superpage_accessed_emulations, 1);
7537 pte = pmap_pde_to_pte(pde, va);
7538 if ((*pte & PG_V) == 0)
7541 if (ftype == VM_PROT_WRITE) {
7542 if ((*pte & PG_RW) == 0)
7545 * Set the modified and accessed bits simultaneously.
7547 * Intel EPT PTEs that do software emulation of A/D bits map
7548 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7549 * An EPT misconfiguration is triggered if the PTE is writable
7550 * but not readable (WR=10). This is avoided by setting PG_A
7551 * and PG_M simultaneously.
7553 *pte |= PG_M | PG_A;
7558 #if VM_NRESERVLEVEL > 0
7559 /* try to promote the mapping */
7560 if (va < VM_MAXUSER_ADDRESS)
7561 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7565 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7567 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7568 pmap_ps_enabled(pmap) &&
7569 (m->flags & PG_FICTITIOUS) == 0 &&
7570 vm_reserv_level_iffullpop(m) == 0) {
7571 pmap_promote_pde(pmap, pde, va, &lock);
7573 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7579 if (ftype == VM_PROT_WRITE)
7580 atomic_add_long(&num_dirty_emulations, 1);
7582 atomic_add_long(&num_accessed_emulations, 1);
7584 rv = 0; /* success */
7593 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7598 pt_entry_t *pte, PG_V;
7602 PG_V = pmap_valid_bit(pmap);
7605 pml4 = pmap_pml4e(pmap, va);
7607 if ((*pml4 & PG_V) == 0)
7610 pdp = pmap_pml4e_to_pdpe(pml4, va);
7612 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7615 pde = pmap_pdpe_to_pde(pdp, va);
7617 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7620 pte = pmap_pde_to_pte(pde, va);
7629 * Get the kernel virtual address of a set of physical pages. If there are
7630 * physical addresses not covered by the DMAP perform a transient mapping
7631 * that will be removed when calling pmap_unmap_io_transient.
7633 * \param page The pages the caller wishes to obtain the virtual
7634 * address on the kernel memory map.
7635 * \param vaddr On return contains the kernel virtual memory address
7636 * of the pages passed in the page parameter.
7637 * \param count Number of pages passed in.
7638 * \param can_fault TRUE if the thread using the mapped pages can take
7639 * page faults, FALSE otherwise.
7641 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7642 * finished or FALSE otherwise.
7646 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7647 boolean_t can_fault)
7650 boolean_t needs_mapping;
7652 int cache_bits, error, i;
7655 * Allocate any KVA space that we need, this is done in a separate
7656 * loop to prevent calling vmem_alloc while pinned.
7658 needs_mapping = FALSE;
7659 for (i = 0; i < count; i++) {
7660 paddr = VM_PAGE_TO_PHYS(page[i]);
7661 if (__predict_false(paddr >= dmaplimit)) {
7662 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7663 M_BESTFIT | M_WAITOK, &vaddr[i]);
7664 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7665 needs_mapping = TRUE;
7667 vaddr[i] = PHYS_TO_DMAP(paddr);
7671 /* Exit early if everything is covered by the DMAP */
7676 * NB: The sequence of updating a page table followed by accesses
7677 * to the corresponding pages used in the !DMAP case is subject to
7678 * the situation described in the "AMD64 Architecture Programmer's
7679 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7680 * Coherency Considerations". Therefore, issuing the INVLPG right
7681 * after modifying the PTE bits is crucial.
7685 for (i = 0; i < count; i++) {
7686 paddr = VM_PAGE_TO_PHYS(page[i]);
7687 if (paddr >= dmaplimit) {
7690 * Slow path, since we can get page faults
7691 * while mappings are active don't pin the
7692 * thread to the CPU and instead add a global
7693 * mapping visible to all CPUs.
7695 pmap_qenter(vaddr[i], &page[i], 1);
7697 pte = vtopte(vaddr[i]);
7698 cache_bits = pmap_cache_bits(kernel_pmap,
7699 page[i]->md.pat_mode, 0);
7700 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7707 return (needs_mapping);
7711 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7712 boolean_t can_fault)
7719 for (i = 0; i < count; i++) {
7720 paddr = VM_PAGE_TO_PHYS(page[i]);
7721 if (paddr >= dmaplimit) {
7723 pmap_qremove(vaddr[i], 1);
7724 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7730 pmap_quick_enter_page(vm_page_t m)
7734 paddr = VM_PAGE_TO_PHYS(m);
7735 if (paddr < dmaplimit)
7736 return (PHYS_TO_DMAP(paddr));
7737 mtx_lock_spin(&qframe_mtx);
7738 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7739 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7740 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7745 pmap_quick_remove_page(vm_offset_t addr)
7750 pte_store(vtopte(qframe), 0);
7752 mtx_unlock_spin(&qframe_mtx);
7756 pmap_pti_alloc_page(void)
7760 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7761 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_NOBUSY |
7762 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
7767 pmap_pti_free_page(vm_page_t m)
7770 KASSERT(m->wire_count > 0, ("page %p not wired", m));
7772 if (m->wire_count != 0)
7774 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
7775 vm_page_free_zero(m);
7789 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
7790 VM_OBJECT_WLOCK(pti_obj);
7791 pml4_pg = pmap_pti_alloc_page();
7792 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
7793 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
7794 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
7795 pdpe = pmap_pti_pdpe(va);
7796 pmap_pti_wire_pte(pdpe);
7798 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
7799 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
7800 pmap_pti_add_kva_locked((vm_offset_t)gdt, (vm_offset_t)gdt +
7801 sizeof(struct user_segment_descriptor) * NGDT * MAXCPU, false);
7802 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
7803 sizeof(struct gate_descriptor) * NIDT, false);
7804 pmap_pti_add_kva_locked((vm_offset_t)common_tss,
7805 (vm_offset_t)common_tss + sizeof(struct amd64tss) * MAXCPU, false);
7807 /* Doublefault stack IST 1 */
7808 va = common_tss[i].tss_ist1;
7809 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7810 /* NMI stack IST 2 */
7811 va = common_tss[i].tss_ist2 + sizeof(struct nmi_pcpu);
7812 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7813 /* MC# stack IST 3 */
7814 va = common_tss[i].tss_ist3 + sizeof(struct nmi_pcpu);
7815 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7817 pmap_pti_add_kva_locked((vm_offset_t)kernphys + KERNBASE,
7818 (vm_offset_t)etext, true);
7819 pti_finalized = true;
7820 VM_OBJECT_WUNLOCK(pti_obj);
7822 SYSINIT(pmap_pti, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_pti_init, NULL);
7824 static pdp_entry_t *
7825 pmap_pti_pdpe(vm_offset_t va)
7827 pml4_entry_t *pml4e;
7830 vm_pindex_t pml4_idx;
7833 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7835 pml4_idx = pmap_pml4e_index(va);
7836 pml4e = &pti_pml4[pml4_idx];
7840 panic("pml4 alloc after finalization\n");
7841 m = pmap_pti_alloc_page();
7843 pmap_pti_free_page(m);
7844 mphys = *pml4e & ~PAGE_MASK;
7846 mphys = VM_PAGE_TO_PHYS(m);
7847 *pml4e = mphys | X86_PG_RW | X86_PG_V;
7850 mphys = *pml4e & ~PAGE_MASK;
7852 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
7857 pmap_pti_wire_pte(void *pte)
7861 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7862 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7867 pmap_pti_unwire_pde(void *pde, bool only_ref)
7871 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7872 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
7873 MPASS(m->wire_count > 0);
7874 MPASS(only_ref || m->wire_count > 1);
7875 pmap_pti_free_page(m);
7879 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
7884 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7885 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7886 MPASS(m->wire_count > 0);
7887 if (pmap_pti_free_page(m)) {
7888 pde = pmap_pti_pde(va);
7889 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
7891 pmap_pti_unwire_pde(pde, false);
7896 pmap_pti_pde(vm_offset_t va)
7904 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7906 pdpe = pmap_pti_pdpe(va);
7908 m = pmap_pti_alloc_page();
7910 pmap_pti_free_page(m);
7911 MPASS((*pdpe & X86_PG_PS) == 0);
7912 mphys = *pdpe & ~PAGE_MASK;
7914 mphys = VM_PAGE_TO_PHYS(m);
7915 *pdpe = mphys | X86_PG_RW | X86_PG_V;
7918 MPASS((*pdpe & X86_PG_PS) == 0);
7919 mphys = *pdpe & ~PAGE_MASK;
7922 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
7923 pd_idx = pmap_pde_index(va);
7929 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
7936 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7938 pde = pmap_pti_pde(va);
7939 if (unwire_pde != NULL) {
7941 pmap_pti_wire_pte(pde);
7944 m = pmap_pti_alloc_page();
7946 pmap_pti_free_page(m);
7947 MPASS((*pde & X86_PG_PS) == 0);
7948 mphys = *pde & ~(PAGE_MASK | pg_nx);
7950 mphys = VM_PAGE_TO_PHYS(m);
7951 *pde = mphys | X86_PG_RW | X86_PG_V;
7952 if (unwire_pde != NULL)
7953 *unwire_pde = false;
7956 MPASS((*pde & X86_PG_PS) == 0);
7957 mphys = *pde & ~(PAGE_MASK | pg_nx);
7960 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
7961 pte += pmap_pte_index(va);
7967 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
7971 pt_entry_t *pte, ptev;
7974 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7976 sva = trunc_page(sva);
7977 MPASS(sva > VM_MAXUSER_ADDRESS);
7978 eva = round_page(eva);
7980 for (; sva < eva; sva += PAGE_SIZE) {
7981 pte = pmap_pti_pte(sva, &unwire_pde);
7982 pa = pmap_kextract(sva);
7983 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A |
7984 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
7985 VM_MEMATTR_DEFAULT, FALSE);
7987 pte_store(pte, ptev);
7988 pmap_pti_wire_pte(pte);
7990 KASSERT(!pti_finalized,
7991 ("pti overlap after fin %#lx %#lx %#lx",
7993 KASSERT(*pte == ptev,
7994 ("pti non-identical pte after fin %#lx %#lx %#lx",
7998 pde = pmap_pti_pde(sva);
7999 pmap_pti_unwire_pde(pde, true);
8005 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
8010 VM_OBJECT_WLOCK(pti_obj);
8011 pmap_pti_add_kva_locked(sva, eva, exec);
8012 VM_OBJECT_WUNLOCK(pti_obj);
8016 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
8023 sva = rounddown2(sva, PAGE_SIZE);
8024 MPASS(sva > VM_MAXUSER_ADDRESS);
8025 eva = roundup2(eva, PAGE_SIZE);
8027 VM_OBJECT_WLOCK(pti_obj);
8028 for (va = sva; va < eva; va += PAGE_SIZE) {
8029 pte = pmap_pti_pte(va, NULL);
8030 KASSERT((*pte & X86_PG_V) != 0,
8031 ("invalid pte va %#lx pte %#lx pt %#lx", va,
8032 (u_long)pte, *pte));
8034 pmap_pti_unwire_pte(pte, va);
8036 pmap_invalidate_range(kernel_pmap, sva, eva);
8037 VM_OBJECT_WUNLOCK(pti_obj);
8040 #include "opt_ddb.h"
8042 #include <ddb/ddb.h>
8044 DB_SHOW_COMMAND(pte, pmap_print_pte)
8050 pt_entry_t *pte, PG_V;
8054 va = (vm_offset_t)addr;
8055 pmap = PCPU_GET(curpmap); /* XXX */
8057 db_printf("show pte addr\n");
8060 PG_V = pmap_valid_bit(pmap);
8061 pml4 = pmap_pml4e(pmap, va);
8062 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
8063 if ((*pml4 & PG_V) == 0) {
8067 pdp = pmap_pml4e_to_pdpe(pml4, va);
8068 db_printf(" pdpe %#016lx", *pdp);
8069 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
8073 pde = pmap_pdpe_to_pde(pdp, va);
8074 db_printf(" pde %#016lx", *pde);
8075 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
8079 pte = pmap_pde_to_pte(pde, va);
8080 db_printf(" pte %#016lx\n", *pte);
8083 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
8088 a = (vm_paddr_t)addr;
8089 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
8091 db_printf("show phys2dmap addr\n");