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.
13 * This code is derived from software contributed to Berkeley by
14 * the Systems Programming Group of the University of Utah Computer
15 * Science Department and William Jolitz of UUNET Technologies Inc.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
25 * 3. All advertising materials mentioning features or use of this software
26 * must display the following acknowledgement:
27 * This product includes software developed by the University of
28 * California, Berkeley and its contributors.
29 * 4. Neither the name of the University nor the names of its contributors
30 * may be used to endorse or promote products derived from this software
31 * without specific prior written permission.
33 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
34 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
35 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
36 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
37 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
38 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
39 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
40 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
41 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
42 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
45 * from: @(#)pmap.c 7.7 (Berkeley) 5/12/91
48 * Copyright (c) 2003 Networks Associates Technology, Inc.
49 * All rights reserved.
51 * This software was developed for the FreeBSD Project by Jake Burkholder,
52 * Safeport Network Services, and Network Associates Laboratories, the
53 * Security Research Division of Network Associates, Inc. under
54 * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
55 * CHATS research program.
57 * Redistribution and use in source and binary forms, with or without
58 * modification, are permitted provided that the following conditions
60 * 1. Redistributions of source code must retain the above copyright
61 * notice, this list of conditions and the following disclaimer.
62 * 2. Redistributions in binary form must reproduce the above copyright
63 * notice, this list of conditions and the following disclaimer in the
64 * documentation and/or other materials provided with the distribution.
66 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
67 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
68 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
69 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
70 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
71 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
72 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
73 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
74 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
75 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
79 #define AMD64_NPT_AWARE
81 #include <sys/cdefs.h>
82 __FBSDID("$FreeBSD$");
85 * Manages physical address maps.
87 * Since the information managed by this module is
88 * also stored by the logical address mapping module,
89 * this module may throw away valid virtual-to-physical
90 * mappings at almost any time. However, invalidations
91 * of virtual-to-physical mappings must be done as
94 * In order to cope with hardware architectures which
95 * make virtual-to-physical map invalidates expensive,
96 * this module may delay invalidate or reduced protection
97 * operations until such time as they are actually
98 * necessary. This module is given full information as
99 * to which processors are currently using which maps,
100 * and to when physical maps must be made correct.
103 #include "opt_pmap.h"
106 #include <sys/param.h>
107 #include <sys/bitstring.h>
109 #include <sys/systm.h>
110 #include <sys/kernel.h>
112 #include <sys/lock.h>
113 #include <sys/malloc.h>
114 #include <sys/mman.h>
115 #include <sys/mutex.h>
116 #include <sys/proc.h>
117 #include <sys/rwlock.h>
119 #include <sys/turnstile.h>
120 #include <sys/vmem.h>
121 #include <sys/vmmeter.h>
122 #include <sys/sched.h>
123 #include <sys/sysctl.h>
127 #include <vm/vm_param.h>
128 #include <vm/vm_kern.h>
129 #include <vm/vm_page.h>
130 #include <vm/vm_map.h>
131 #include <vm/vm_object.h>
132 #include <vm/vm_extern.h>
133 #include <vm/vm_pageout.h>
134 #include <vm/vm_pager.h>
135 #include <vm/vm_phys.h>
136 #include <vm/vm_radix.h>
137 #include <vm/vm_reserv.h>
140 #include <machine/intr_machdep.h>
141 #include <x86/apicvar.h>
142 #include <machine/cpu.h>
143 #include <machine/cputypes.h>
144 #include <machine/md_var.h>
145 #include <machine/pcb.h>
146 #include <machine/specialreg.h>
148 #include <machine/smp.h>
151 static __inline boolean_t
152 pmap_type_guest(pmap_t pmap)
155 return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
158 static __inline boolean_t
159 pmap_emulate_ad_bits(pmap_t pmap)
162 return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
165 static __inline pt_entry_t
166 pmap_valid_bit(pmap_t pmap)
170 switch (pmap->pm_type) {
176 if (pmap_emulate_ad_bits(pmap))
177 mask = EPT_PG_EMUL_V;
182 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
188 static __inline pt_entry_t
189 pmap_rw_bit(pmap_t pmap)
193 switch (pmap->pm_type) {
199 if (pmap_emulate_ad_bits(pmap))
200 mask = EPT_PG_EMUL_RW;
205 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
211 static __inline pt_entry_t
212 pmap_global_bit(pmap_t pmap)
216 switch (pmap->pm_type) {
225 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
231 static __inline pt_entry_t
232 pmap_accessed_bit(pmap_t pmap)
236 switch (pmap->pm_type) {
242 if (pmap_emulate_ad_bits(pmap))
248 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
254 static __inline pt_entry_t
255 pmap_modified_bit(pmap_t pmap)
259 switch (pmap->pm_type) {
265 if (pmap_emulate_ad_bits(pmap))
271 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
277 #if !defined(DIAGNOSTIC)
278 #ifdef __GNUC_GNU_INLINE__
279 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
281 #define PMAP_INLINE extern inline
288 #define PV_STAT(x) do { x ; } while (0)
290 #define PV_STAT(x) do { } while (0)
293 #define pa_index(pa) ((pa) >> PDRSHIFT)
294 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
296 #define NPV_LIST_LOCKS MAXCPU
298 #define PHYS_TO_PV_LIST_LOCK(pa) \
299 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
301 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
302 struct rwlock **_lockp = (lockp); \
303 struct rwlock *_new_lock; \
305 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
306 if (_new_lock != *_lockp) { \
307 if (*_lockp != NULL) \
308 rw_wunlock(*_lockp); \
309 *_lockp = _new_lock; \
314 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
315 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
317 #define RELEASE_PV_LIST_LOCK(lockp) do { \
318 struct rwlock **_lockp = (lockp); \
320 if (*_lockp != NULL) { \
321 rw_wunlock(*_lockp); \
326 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
327 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
329 struct pmap kernel_pmap_store;
331 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
332 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
335 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
336 "Number of kernel page table pages allocated on bootup");
339 vm_paddr_t dmaplimit;
340 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
343 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
345 static int pat_works = 1;
346 SYSCTL_INT(_vm_pmap, OID_AUTO, pat_works, CTLFLAG_RD, &pat_works, 1,
347 "Is page attribute table fully functional?");
349 static int pg_ps_enabled = 1;
350 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
351 &pg_ps_enabled, 0, "Are large page mappings enabled?");
353 #define PAT_INDEX_SIZE 8
354 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
356 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
357 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
358 u_int64_t KPDPphys; /* phys addr of kernel level 3 */
359 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
361 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
362 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
363 static int ndmpdpphys; /* number of DMPDPphys pages */
366 * pmap_mapdev support pre initialization (i.e. console)
368 #define PMAP_PREINIT_MAPPING_COUNT 8
369 static struct pmap_preinit_mapping {
374 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
375 static int pmap_initialized;
378 * Data for the pv entry allocation mechanism.
379 * Updates to pv_invl_gen are protected by the pv_list_locks[]
380 * elements, but reads are not.
382 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
383 static struct mtx __exclusive_cache_line pv_chunks_mutex;
384 static struct rwlock __exclusive_cache_line pv_list_locks[NPV_LIST_LOCKS];
385 static u_long pv_invl_gen[NPV_LIST_LOCKS];
386 static struct md_page *pv_table;
387 static struct md_page pv_dummy;
390 * All those kernel PT submaps that BSD is so fond of
392 pt_entry_t *CMAP1 = NULL;
394 static vm_offset_t qframe = 0;
395 static struct mtx qframe_mtx;
397 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
399 int pmap_pcid_enabled = 1;
400 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
401 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
402 int invpcid_works = 0;
403 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
404 "Is the invpcid instruction available ?");
407 pmap_pcid_save_cnt_proc(SYSCTL_HANDLER_ARGS)
414 res += cpuid_to_pcpu[i]->pc_pm_save_cnt;
416 return (sysctl_handle_64(oidp, &res, 0, req));
418 SYSCTL_PROC(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLTYPE_U64 | CTLFLAG_RW |
419 CTLFLAG_MPSAFE, NULL, 0, pmap_pcid_save_cnt_proc, "QU",
420 "Count of saved TLB context on switch");
422 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
423 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
424 static struct mtx invl_gen_mtx;
425 static u_long pmap_invl_gen = 0;
426 /* Fake lock object to satisfy turnstiles interface. */
427 static struct lock_object invl_gen_ts = {
435 return (curthread->td_md.md_invl_gen.gen == 0);
438 #define PMAP_ASSERT_NOT_IN_DI() \
439 KASSERT(pmap_not_in_di(), ("DI already started"))
442 * Start a new Delayed Invalidation (DI) block of code, executed by
443 * the current thread. Within a DI block, the current thread may
444 * destroy both the page table and PV list entries for a mapping and
445 * then release the corresponding PV list lock before ensuring that
446 * the mapping is flushed from the TLBs of any processors with the
450 pmap_delayed_invl_started(void)
452 struct pmap_invl_gen *invl_gen;
455 invl_gen = &curthread->td_md.md_invl_gen;
456 PMAP_ASSERT_NOT_IN_DI();
457 mtx_lock(&invl_gen_mtx);
458 if (LIST_EMPTY(&pmap_invl_gen_tracker))
459 currgen = pmap_invl_gen;
461 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
462 invl_gen->gen = currgen + 1;
463 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
464 mtx_unlock(&invl_gen_mtx);
468 * Finish the DI block, previously started by the current thread. All
469 * required TLB flushes for the pages marked by
470 * pmap_delayed_invl_page() must be finished before this function is
473 * This function works by bumping the global DI generation number to
474 * the generation number of the current thread's DI, unless there is a
475 * pending DI that started earlier. In the latter case, bumping the
476 * global DI generation number would incorrectly signal that the
477 * earlier DI had finished. Instead, this function bumps the earlier
478 * DI's generation number to match the generation number of the
479 * current thread's DI.
482 pmap_delayed_invl_finished(void)
484 struct pmap_invl_gen *invl_gen, *next;
485 struct turnstile *ts;
487 invl_gen = &curthread->td_md.md_invl_gen;
488 KASSERT(invl_gen->gen != 0, ("missed invl_started"));
489 mtx_lock(&invl_gen_mtx);
490 next = LIST_NEXT(invl_gen, link);
492 turnstile_chain_lock(&invl_gen_ts);
493 ts = turnstile_lookup(&invl_gen_ts);
494 pmap_invl_gen = invl_gen->gen;
496 turnstile_broadcast(ts, TS_SHARED_QUEUE);
497 turnstile_unpend(ts, TS_SHARED_LOCK);
499 turnstile_chain_unlock(&invl_gen_ts);
501 next->gen = invl_gen->gen;
503 LIST_REMOVE(invl_gen, link);
504 mtx_unlock(&invl_gen_mtx);
509 static long invl_wait;
510 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
511 "Number of times DI invalidation blocked pmap_remove_all/write");
515 pmap_delayed_invl_genp(vm_page_t m)
518 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
522 * Ensure that all currently executing DI blocks, that need to flush
523 * TLB for the given page m, actually flushed the TLB at the time the
524 * function returned. If the page m has an empty PV list and we call
525 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
526 * valid mapping for the page m in either its page table or TLB.
528 * This function works by blocking until the global DI generation
529 * number catches up with the generation number associated with the
530 * given page m and its PV list. Since this function's callers
531 * typically own an object lock and sometimes own a page lock, it
532 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
536 pmap_delayed_invl_wait(vm_page_t m)
538 struct turnstile *ts;
541 bool accounted = false;
544 m_gen = pmap_delayed_invl_genp(m);
545 while (*m_gen > pmap_invl_gen) {
548 atomic_add_long(&invl_wait, 1);
552 ts = turnstile_trywait(&invl_gen_ts);
553 if (*m_gen > pmap_invl_gen)
554 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
556 turnstile_cancel(ts);
561 * Mark the page m's PV list as participating in the current thread's
562 * DI block. Any threads concurrently using m's PV list to remove or
563 * restrict all mappings to m will wait for the current thread's DI
564 * block to complete before proceeding.
566 * The function works by setting the DI generation number for m's PV
567 * list to at least the DI generation number of the current thread.
568 * This forces a caller of pmap_delayed_invl_wait() to block until
569 * current thread calls pmap_delayed_invl_finished().
572 pmap_delayed_invl_page(vm_page_t m)
576 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
577 gen = curthread->td_md.md_invl_gen.gen;
580 m_gen = pmap_delayed_invl_genp(m);
588 static caddr_t crashdumpmap;
591 * Internal flags for pmap_enter()'s helper functions.
593 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
594 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
596 static void free_pv_chunk(struct pv_chunk *pc);
597 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
598 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
599 static int popcnt_pc_map_pq(uint64_t *map);
600 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
601 static void reserve_pv_entries(pmap_t pmap, int needed,
602 struct rwlock **lockp);
603 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
604 struct rwlock **lockp);
605 static bool pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
606 u_int flags, struct rwlock **lockp);
607 #if VM_NRESERVLEVEL > 0
608 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
609 struct rwlock **lockp);
611 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
612 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
615 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode);
616 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
617 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
618 vm_offset_t va, struct rwlock **lockp);
619 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
621 static bool pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
622 vm_prot_t prot, struct rwlock **lockp);
623 static int pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
624 u_int flags, vm_page_t m, struct rwlock **lockp);
625 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
626 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
627 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
628 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
629 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
631 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
632 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask);
633 #if VM_NRESERVLEVEL > 0
634 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
635 struct rwlock **lockp);
637 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
639 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
640 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
641 struct spglist *free, struct rwlock **lockp);
642 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
643 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
644 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
645 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
646 struct spglist *free);
647 static bool pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
648 pd_entry_t *pde, struct spglist *free,
649 struct rwlock **lockp);
650 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
651 vm_page_t m, struct rwlock **lockp);
652 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
654 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
656 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
657 struct rwlock **lockp);
658 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
659 struct rwlock **lockp);
660 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
661 struct rwlock **lockp);
663 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
664 struct spglist *free);
665 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
666 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
669 * Move the kernel virtual free pointer to the next
670 * 2MB. This is used to help improve performance
671 * by using a large (2MB) page for much of the kernel
672 * (.text, .data, .bss)
675 pmap_kmem_choose(vm_offset_t addr)
677 vm_offset_t newaddr = addr;
679 newaddr = roundup2(addr, NBPDR);
683 /********************/
684 /* Inline functions */
685 /********************/
687 /* Return a non-clipped PD index for a given VA */
688 static __inline vm_pindex_t
689 pmap_pde_pindex(vm_offset_t va)
691 return (va >> PDRSHIFT);
695 /* Return a pointer to the PML4 slot that corresponds to a VA */
696 static __inline pml4_entry_t *
697 pmap_pml4e(pmap_t pmap, vm_offset_t va)
700 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
703 /* Return a pointer to the PDP slot that corresponds to a VA */
704 static __inline pdp_entry_t *
705 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
709 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
710 return (&pdpe[pmap_pdpe_index(va)]);
713 /* Return a pointer to the PDP slot that corresponds to a VA */
714 static __inline pdp_entry_t *
715 pmap_pdpe(pmap_t pmap, vm_offset_t va)
720 PG_V = pmap_valid_bit(pmap);
721 pml4e = pmap_pml4e(pmap, va);
722 if ((*pml4e & PG_V) == 0)
724 return (pmap_pml4e_to_pdpe(pml4e, va));
727 /* Return a pointer to the PD slot that corresponds to a VA */
728 static __inline pd_entry_t *
729 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
733 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
734 return (&pde[pmap_pde_index(va)]);
737 /* Return a pointer to the PD slot that corresponds to a VA */
738 static __inline pd_entry_t *
739 pmap_pde(pmap_t pmap, vm_offset_t va)
744 PG_V = pmap_valid_bit(pmap);
745 pdpe = pmap_pdpe(pmap, va);
746 if (pdpe == NULL || (*pdpe & PG_V) == 0)
748 return (pmap_pdpe_to_pde(pdpe, va));
751 /* Return a pointer to the PT slot that corresponds to a VA */
752 static __inline pt_entry_t *
753 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
757 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
758 return (&pte[pmap_pte_index(va)]);
761 /* Return a pointer to the PT slot that corresponds to a VA */
762 static __inline pt_entry_t *
763 pmap_pte(pmap_t pmap, vm_offset_t va)
768 PG_V = pmap_valid_bit(pmap);
769 pde = pmap_pde(pmap, va);
770 if (pde == NULL || (*pde & PG_V) == 0)
772 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
773 return ((pt_entry_t *)pde);
774 return (pmap_pde_to_pte(pde, va));
778 pmap_resident_count_inc(pmap_t pmap, int count)
781 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
782 pmap->pm_stats.resident_count += count;
786 pmap_resident_count_dec(pmap_t pmap, int count)
789 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
790 KASSERT(pmap->pm_stats.resident_count >= count,
791 ("pmap %p resident count underflow %ld %d", pmap,
792 pmap->pm_stats.resident_count, count));
793 pmap->pm_stats.resident_count -= count;
796 PMAP_INLINE pt_entry_t *
797 vtopte(vm_offset_t va)
799 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
801 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
803 return (PTmap + ((va >> PAGE_SHIFT) & mask));
806 static __inline pd_entry_t *
807 vtopde(vm_offset_t va)
809 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
811 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
813 return (PDmap + ((va >> PDRSHIFT) & mask));
817 allocpages(vm_paddr_t *firstaddr, int n)
822 bzero((void *)ret, n * PAGE_SIZE);
823 *firstaddr += n * PAGE_SIZE;
827 CTASSERT(powerof2(NDMPML4E));
829 /* number of kernel PDP slots */
830 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
833 nkpt_init(vm_paddr_t addr)
840 pt_pages = howmany(addr, 1 << PDRSHIFT);
841 pt_pages += NKPDPE(pt_pages);
844 * Add some slop beyond the bare minimum required for bootstrapping
847 * This is quite important when allocating KVA for kernel modules.
848 * The modules are required to be linked in the negative 2GB of
849 * the address space. If we run out of KVA in this region then
850 * pmap_growkernel() will need to allocate page table pages to map
851 * the entire 512GB of KVA space which is an unnecessary tax on
854 * Secondly, device memory mapped as part of setting up the low-
855 * level console(s) is taken from KVA, starting at virtual_avail.
856 * This is because cninit() is called after pmap_bootstrap() but
857 * before vm_init() and pmap_init(). 20MB for a frame buffer is
860 pt_pages += 32; /* 64MB additional slop. */
866 create_pagetables(vm_paddr_t *firstaddr)
868 int i, j, ndm1g, nkpdpe;
874 /* Allocate page table pages for the direct map */
875 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
876 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
878 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
879 if (ndmpdpphys > NDMPML4E) {
881 * Each NDMPML4E allows 512 GB, so limit to that,
882 * and then readjust ndmpdp and ndmpdpphys.
884 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
885 Maxmem = atop(NDMPML4E * NBPML4);
886 ndmpdpphys = NDMPML4E;
887 ndmpdp = NDMPML4E * NPDEPG;
889 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
891 if ((amd_feature & AMDID_PAGE1GB) != 0)
892 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
894 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
895 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
898 KPML4phys = allocpages(firstaddr, 1);
899 KPDPphys = allocpages(firstaddr, NKPML4E);
902 * Allocate the initial number of kernel page table pages required to
903 * bootstrap. We defer this until after all memory-size dependent
904 * allocations are done (e.g. direct map), so that we don't have to
905 * build in too much slop in our estimate.
907 * Note that when NKPML4E > 1, we have an empty page underneath
908 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
909 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
911 nkpt_init(*firstaddr);
912 nkpdpe = NKPDPE(nkpt);
914 KPTphys = allocpages(firstaddr, nkpt);
915 KPDphys = allocpages(firstaddr, nkpdpe);
917 /* Fill in the underlying page table pages */
918 /* Nominally read-only (but really R/W) from zero to physfree */
919 /* XXX not fully used, underneath 2M pages */
920 pt_p = (pt_entry_t *)KPTphys;
921 for (i = 0; ptoa(i) < *firstaddr; i++)
922 pt_p[i] = ptoa(i) | X86_PG_RW | X86_PG_V | X86_PG_G;
924 /* Now map the page tables at their location within PTmap */
925 pd_p = (pd_entry_t *)KPDphys;
926 for (i = 0; i < nkpt; i++)
927 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
929 /* Map from zero to end of allocations under 2M pages */
930 /* This replaces some of the KPTphys entries above */
931 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
932 pd_p[i] = (i << PDRSHIFT) | X86_PG_RW | X86_PG_V | PG_PS |
935 /* And connect up the PD to the PDP (leaving room for L4 pages) */
936 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
937 for (i = 0; i < nkpdpe; i++)
938 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
942 * Now, set up the direct map region using 2MB and/or 1GB pages. If
943 * the end of physical memory is not aligned to a 1GB page boundary,
944 * then the residual physical memory is mapped with 2MB pages. Later,
945 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
946 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
947 * that are partially used.
949 pd_p = (pd_entry_t *)DMPDphys;
950 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
951 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
952 /* Preset PG_M and PG_A because demotion expects it. */
953 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | X86_PG_G |
954 X86_PG_M | X86_PG_A | pg_nx;
956 pdp_p = (pdp_entry_t *)DMPDPphys;
957 for (i = 0; i < ndm1g; i++) {
958 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
959 /* Preset PG_M and PG_A because demotion expects it. */
960 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | X86_PG_G |
961 X86_PG_M | X86_PG_A | pg_nx;
963 for (j = 0; i < ndmpdp; i++, j++) {
964 pdp_p[i] = DMPDphys + ptoa(j);
965 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_U;
968 /* And recursively map PML4 to itself in order to get PTmap */
969 p4_p = (pml4_entry_t *)KPML4phys;
970 p4_p[PML4PML4I] = KPML4phys;
971 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | PG_U;
973 /* Connect the Direct Map slot(s) up to the PML4. */
974 for (i = 0; i < ndmpdpphys; i++) {
975 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
976 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | PG_U;
979 /* Connect the KVA slots up to the PML4 */
980 for (i = 0; i < NKPML4E; i++) {
981 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
982 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V | PG_U;
987 * Bootstrap the system enough to run with virtual memory.
989 * On amd64 this is called after mapping has already been enabled
990 * and just syncs the pmap module with what has already been done.
991 * [We can't call it easily with mapping off since the kernel is not
992 * mapped with PA == VA, hence we would have to relocate every address
993 * from the linked base (virtual) address "KERNBASE" to the actual
994 * (physical) address starting relative to 0]
997 pmap_bootstrap(vm_paddr_t *firstaddr)
1004 * Create an initial set of page tables to run the kernel in.
1006 create_pagetables(firstaddr);
1009 * Add a physical memory segment (vm_phys_seg) corresponding to the
1010 * preallocated kernel page table pages so that vm_page structures
1011 * representing these pages will be created. The vm_page structures
1012 * are required for promotion of the corresponding kernel virtual
1013 * addresses to superpage mappings.
1015 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1017 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
1018 virtual_avail = pmap_kmem_choose(virtual_avail);
1020 virtual_end = VM_MAX_KERNEL_ADDRESS;
1023 /* XXX do %cr0 as well */
1024 load_cr4(rcr4() | CR4_PGE);
1025 load_cr3(KPML4phys);
1026 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1027 load_cr4(rcr4() | CR4_SMEP);
1030 * Initialize the kernel pmap (which is statically allocated).
1032 PMAP_LOCK_INIT(kernel_pmap);
1033 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1034 kernel_pmap->pm_cr3 = KPML4phys;
1035 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1036 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1037 kernel_pmap->pm_flags = pmap_flags;
1040 * Initialize the TLB invalidations generation number lock.
1042 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1045 * Reserve some special page table entries/VA space for temporary
1048 #define SYSMAP(c, p, v, n) \
1049 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1055 * Crashdump maps. The first page is reused as CMAP1 for the
1058 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1059 CADDR1 = crashdumpmap;
1064 * Initialize the PAT MSR.
1065 * pmap_init_pat() clears and sets CR4_PGE, which, as a
1066 * side-effect, invalidates stale PG_G TLB entries that might
1067 * have been created in our pre-boot environment.
1071 /* Initialize TLB Context Id. */
1072 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1073 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1074 /* Check for INVPCID support */
1075 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1077 for (i = 0; i < MAXCPU; i++) {
1078 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1079 kernel_pmap->pm_pcids[i].pm_gen = 1;
1081 PCPU_SET(pcid_next, PMAP_PCID_KERN + 1);
1082 PCPU_SET(pcid_gen, 1);
1084 * pcpu area for APs is zeroed during AP startup.
1085 * pc_pcid_next and pc_pcid_gen are initialized by AP
1086 * during pcpu setup.
1088 load_cr4(rcr4() | CR4_PCIDE);
1090 pmap_pcid_enabled = 0;
1095 * Setup the PAT MSR.
1100 int pat_table[PAT_INDEX_SIZE];
1105 /* Bail if this CPU doesn't implement PAT. */
1106 if ((cpu_feature & CPUID_PAT) == 0)
1109 /* Set default PAT index table. */
1110 for (i = 0; i < PAT_INDEX_SIZE; i++)
1112 pat_table[PAT_WRITE_BACK] = 0;
1113 pat_table[PAT_WRITE_THROUGH] = 1;
1114 pat_table[PAT_UNCACHEABLE] = 3;
1115 pat_table[PAT_WRITE_COMBINING] = 3;
1116 pat_table[PAT_WRITE_PROTECTED] = 3;
1117 pat_table[PAT_UNCACHED] = 3;
1119 /* Initialize default PAT entries. */
1120 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1121 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1122 PAT_VALUE(2, PAT_UNCACHED) |
1123 PAT_VALUE(3, PAT_UNCACHEABLE) |
1124 PAT_VALUE(4, PAT_WRITE_BACK) |
1125 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1126 PAT_VALUE(6, PAT_UNCACHED) |
1127 PAT_VALUE(7, PAT_UNCACHEABLE);
1131 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1132 * Program 5 and 6 as WP and WC.
1133 * Leave 4 and 7 as WB and UC.
1135 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1136 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1137 PAT_VALUE(6, PAT_WRITE_COMBINING);
1138 pat_table[PAT_UNCACHED] = 2;
1139 pat_table[PAT_WRITE_PROTECTED] = 5;
1140 pat_table[PAT_WRITE_COMBINING] = 6;
1143 * Just replace PAT Index 2 with WC instead of UC-.
1145 pat_msr &= ~PAT_MASK(2);
1146 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1147 pat_table[PAT_WRITE_COMBINING] = 2;
1152 load_cr4(cr4 & ~CR4_PGE);
1154 /* Disable caches (CD = 1, NW = 0). */
1156 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1158 /* Flushes caches and TLBs. */
1162 /* Update PAT and index table. */
1163 wrmsr(MSR_PAT, pat_msr);
1164 for (i = 0; i < PAT_INDEX_SIZE; i++)
1165 pat_index[i] = pat_table[i];
1167 /* Flush caches and TLBs again. */
1171 /* Restore caches and PGE. */
1177 * Initialize a vm_page's machine-dependent fields.
1180 pmap_page_init(vm_page_t m)
1183 TAILQ_INIT(&m->md.pv_list);
1184 m->md.pat_mode = PAT_WRITE_BACK;
1188 * Initialize the pmap module.
1189 * Called by vm_init, to initialize any structures that the pmap
1190 * system needs to map virtual memory.
1195 struct pmap_preinit_mapping *ppim;
1198 int error, i, pv_npg;
1201 * Initialize the vm page array entries for the kernel pmap's
1204 for (i = 0; i < nkpt; i++) {
1205 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1206 KASSERT(mpte >= vm_page_array &&
1207 mpte < &vm_page_array[vm_page_array_size],
1208 ("pmap_init: page table page is out of range"));
1209 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1210 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1214 * If the kernel is running on a virtual machine, then it must assume
1215 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1216 * be prepared for the hypervisor changing the vendor and family that
1217 * are reported by CPUID. Consequently, the workaround for AMD Family
1218 * 10h Erratum 383 is enabled if the processor's feature set does not
1219 * include at least one feature that is only supported by older Intel
1220 * or newer AMD processors.
1222 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1223 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1224 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1226 workaround_erratum383 = 1;
1229 * Are large page mappings enabled?
1231 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1232 if (pg_ps_enabled) {
1233 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1234 ("pmap_init: can't assign to pagesizes[1]"));
1235 pagesizes[1] = NBPDR;
1239 * Initialize the pv chunk list mutex.
1241 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1244 * Initialize the pool of pv list locks.
1246 for (i = 0; i < NPV_LIST_LOCKS; i++)
1247 rw_init(&pv_list_locks[i], "pmap pv list");
1250 * Calculate the size of the pv head table for superpages.
1252 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1255 * Allocate memory for the pv head table for superpages.
1257 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1259 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1261 for (i = 0; i < pv_npg; i++)
1262 TAILQ_INIT(&pv_table[i].pv_list);
1263 TAILQ_INIT(&pv_dummy.pv_list);
1265 pmap_initialized = 1;
1266 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1267 ppim = pmap_preinit_mapping + i;
1270 /* Make the direct map consistent */
1271 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1272 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1273 ppim->sz, ppim->mode);
1277 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1278 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1281 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1282 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1283 (vmem_addr_t *)&qframe);
1285 panic("qframe allocation failed");
1288 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1289 "2MB page mapping counters");
1291 static u_long pmap_pde_demotions;
1292 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1293 &pmap_pde_demotions, 0, "2MB page demotions");
1295 static u_long pmap_pde_mappings;
1296 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1297 &pmap_pde_mappings, 0, "2MB page mappings");
1299 static u_long pmap_pde_p_failures;
1300 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1301 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1303 static u_long pmap_pde_promotions;
1304 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1305 &pmap_pde_promotions, 0, "2MB page promotions");
1307 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1308 "1GB page mapping counters");
1310 static u_long pmap_pdpe_demotions;
1311 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1312 &pmap_pdpe_demotions, 0, "1GB page demotions");
1314 /***************************************************
1315 * Low level helper routines.....
1316 ***************************************************/
1319 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1321 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1323 switch (pmap->pm_type) {
1326 /* Verify that both PAT bits are not set at the same time */
1327 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1328 ("Invalid PAT bits in entry %#lx", entry));
1330 /* Swap the PAT bits if one of them is set */
1331 if ((entry & x86_pat_bits) != 0)
1332 entry ^= x86_pat_bits;
1336 * Nothing to do - the memory attributes are represented
1337 * the same way for regular pages and superpages.
1341 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1348 * Determine the appropriate bits to set in a PTE or PDE for a specified
1352 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1354 int cache_bits, pat_flag, pat_idx;
1356 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1357 panic("Unknown caching mode %d\n", mode);
1359 switch (pmap->pm_type) {
1362 /* The PAT bit is different for PTE's and PDE's. */
1363 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1365 /* Map the caching mode to a PAT index. */
1366 pat_idx = pat_index[mode];
1368 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1371 cache_bits |= pat_flag;
1373 cache_bits |= PG_NC_PCD;
1375 cache_bits |= PG_NC_PWT;
1379 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1383 panic("unsupported pmap type %d", pmap->pm_type);
1386 return (cache_bits);
1390 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1394 switch (pmap->pm_type) {
1397 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1400 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1403 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1410 pmap_ps_enabled(pmap_t pmap)
1413 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1417 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1420 switch (pmap->pm_type) {
1427 * This is a little bogus since the generation number is
1428 * supposed to be bumped up when a region of the address
1429 * space is invalidated in the page tables.
1431 * In this case the old PDE entry is valid but yet we want
1432 * to make sure that any mappings using the old entry are
1433 * invalidated in the TLB.
1435 * The reason this works as expected is because we rendezvous
1436 * "all" host cpus and force any vcpu context to exit as a
1439 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1442 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1444 pde_store(pde, newpde);
1448 * After changing the page size for the specified virtual address in the page
1449 * table, flush the corresponding entries from the processor's TLB. Only the
1450 * calling processor's TLB is affected.
1452 * The calling thread must be pinned to a processor.
1455 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1459 if (pmap_type_guest(pmap))
1462 KASSERT(pmap->pm_type == PT_X86,
1463 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1465 PG_G = pmap_global_bit(pmap);
1467 if ((newpde & PG_PS) == 0)
1468 /* Demotion: flush a specific 2MB page mapping. */
1470 else if ((newpde & PG_G) == 0)
1472 * Promotion: flush every 4KB page mapping from the TLB
1473 * because there are too many to flush individually.
1478 * Promotion: flush every 4KB page mapping from the TLB,
1479 * including any global (PG_G) mappings.
1487 * For SMP, these functions have to use the IPI mechanism for coherence.
1489 * N.B.: Before calling any of the following TLB invalidation functions,
1490 * the calling processor must ensure that all stores updating a non-
1491 * kernel page table are globally performed. Otherwise, another
1492 * processor could cache an old, pre-update entry without being
1493 * invalidated. This can happen one of two ways: (1) The pmap becomes
1494 * active on another processor after its pm_active field is checked by
1495 * one of the following functions but before a store updating the page
1496 * table is globally performed. (2) The pmap becomes active on another
1497 * processor before its pm_active field is checked but due to
1498 * speculative loads one of the following functions stills reads the
1499 * pmap as inactive on the other processor.
1501 * The kernel page table is exempt because its pm_active field is
1502 * immutable. The kernel page table is always active on every
1507 * Interrupt the cpus that are executing in the guest context.
1508 * This will force the vcpu to exit and the cached EPT mappings
1509 * will be invalidated by the host before the next vmresume.
1511 static __inline void
1512 pmap_invalidate_ept(pmap_t pmap)
1517 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1518 ("pmap_invalidate_ept: absurd pm_active"));
1521 * The TLB mappings associated with a vcpu context are not
1522 * flushed each time a different vcpu is chosen to execute.
1524 * This is in contrast with a process's vtop mappings that
1525 * are flushed from the TLB on each context switch.
1527 * Therefore we need to do more than just a TLB shootdown on
1528 * the active cpus in 'pmap->pm_active'. To do this we keep
1529 * track of the number of invalidations performed on this pmap.
1531 * Each vcpu keeps a cache of this counter and compares it
1532 * just before a vmresume. If the counter is out-of-date an
1533 * invept will be done to flush stale mappings from the TLB.
1535 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1538 * Force the vcpu to exit and trap back into the hypervisor.
1540 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1541 ipi_selected(pmap->pm_active, ipinum);
1546 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1551 if (pmap_type_guest(pmap)) {
1552 pmap_invalidate_ept(pmap);
1556 KASSERT(pmap->pm_type == PT_X86,
1557 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1560 if (pmap == kernel_pmap) {
1564 cpuid = PCPU_GET(cpuid);
1565 if (pmap == PCPU_GET(curpmap))
1567 else if (pmap_pcid_enabled)
1568 pmap->pm_pcids[cpuid].pm_gen = 0;
1569 if (pmap_pcid_enabled) {
1572 pmap->pm_pcids[i].pm_gen = 0;
1575 mask = &pmap->pm_active;
1577 smp_masked_invlpg(*mask, va);
1581 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1582 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1585 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1591 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1592 pmap_invalidate_all(pmap);
1596 if (pmap_type_guest(pmap)) {
1597 pmap_invalidate_ept(pmap);
1601 KASSERT(pmap->pm_type == PT_X86,
1602 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1605 cpuid = PCPU_GET(cpuid);
1606 if (pmap == kernel_pmap) {
1607 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1611 if (pmap == PCPU_GET(curpmap)) {
1612 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1614 } else if (pmap_pcid_enabled) {
1615 pmap->pm_pcids[cpuid].pm_gen = 0;
1617 if (pmap_pcid_enabled) {
1620 pmap->pm_pcids[i].pm_gen = 0;
1623 mask = &pmap->pm_active;
1625 smp_masked_invlpg_range(*mask, sva, eva);
1630 pmap_invalidate_all(pmap_t pmap)
1633 struct invpcid_descr d;
1636 if (pmap_type_guest(pmap)) {
1637 pmap_invalidate_ept(pmap);
1641 KASSERT(pmap->pm_type == PT_X86,
1642 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1645 if (pmap == kernel_pmap) {
1646 if (pmap_pcid_enabled && invpcid_works) {
1647 bzero(&d, sizeof(d));
1648 invpcid(&d, INVPCID_CTXGLOB);
1654 cpuid = PCPU_GET(cpuid);
1655 if (pmap == PCPU_GET(curpmap)) {
1656 if (pmap_pcid_enabled) {
1657 if (invpcid_works) {
1658 d.pcid = pmap->pm_pcids[cpuid].pm_pcid;
1661 invpcid(&d, INVPCID_CTX);
1663 load_cr3(pmap->pm_cr3 | pmap->pm_pcids
1664 [PCPU_GET(cpuid)].pm_pcid);
1669 } else if (pmap_pcid_enabled) {
1670 pmap->pm_pcids[cpuid].pm_gen = 0;
1672 if (pmap_pcid_enabled) {
1675 pmap->pm_pcids[i].pm_gen = 0;
1678 mask = &pmap->pm_active;
1680 smp_masked_invltlb(*mask, pmap);
1685 pmap_invalidate_cache(void)
1695 cpuset_t invalidate; /* processors that invalidate their TLB */
1700 u_int store; /* processor that updates the PDE */
1704 pmap_update_pde_action(void *arg)
1706 struct pde_action *act = arg;
1708 if (act->store == PCPU_GET(cpuid))
1709 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1713 pmap_update_pde_teardown(void *arg)
1715 struct pde_action *act = arg;
1717 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1718 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1722 * Change the page size for the specified virtual address in a way that
1723 * prevents any possibility of the TLB ever having two entries that map the
1724 * same virtual address using different page sizes. This is the recommended
1725 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1726 * machine check exception for a TLB state that is improperly diagnosed as a
1730 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1732 struct pde_action act;
1733 cpuset_t active, other_cpus;
1737 cpuid = PCPU_GET(cpuid);
1738 other_cpus = all_cpus;
1739 CPU_CLR(cpuid, &other_cpus);
1740 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1743 active = pmap->pm_active;
1745 if (CPU_OVERLAP(&active, &other_cpus)) {
1747 act.invalidate = active;
1751 act.newpde = newpde;
1752 CPU_SET(cpuid, &active);
1753 smp_rendezvous_cpus(active,
1754 smp_no_rendezvous_barrier, pmap_update_pde_action,
1755 pmap_update_pde_teardown, &act);
1757 pmap_update_pde_store(pmap, pde, newpde);
1758 if (CPU_ISSET(cpuid, &active))
1759 pmap_update_pde_invalidate(pmap, va, newpde);
1765 * Normal, non-SMP, invalidation functions.
1768 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1771 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1775 KASSERT(pmap->pm_type == PT_X86,
1776 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1778 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1780 else if (pmap_pcid_enabled)
1781 pmap->pm_pcids[0].pm_gen = 0;
1785 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1789 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1793 KASSERT(pmap->pm_type == PT_X86,
1794 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1796 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1797 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1799 } else if (pmap_pcid_enabled) {
1800 pmap->pm_pcids[0].pm_gen = 0;
1805 pmap_invalidate_all(pmap_t pmap)
1807 struct invpcid_descr d;
1809 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1813 KASSERT(pmap->pm_type == PT_X86,
1814 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
1816 if (pmap == kernel_pmap) {
1817 if (pmap_pcid_enabled && invpcid_works) {
1818 bzero(&d, sizeof(d));
1819 invpcid(&d, INVPCID_CTXGLOB);
1823 } else if (pmap == PCPU_GET(curpmap)) {
1824 if (pmap_pcid_enabled) {
1825 if (invpcid_works) {
1826 d.pcid = pmap->pm_pcids[0].pm_pcid;
1829 invpcid(&d, INVPCID_CTX);
1831 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[0].
1837 } else if (pmap_pcid_enabled) {
1838 pmap->pm_pcids[0].pm_gen = 0;
1843 pmap_invalidate_cache(void)
1850 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1853 pmap_update_pde_store(pmap, pde, newpde);
1854 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1855 pmap_update_pde_invalidate(pmap, va, newpde);
1857 pmap->pm_pcids[0].pm_gen = 0;
1862 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
1866 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
1867 * by a promotion that did not invalidate the 512 4KB page mappings
1868 * that might exist in the TLB. Consequently, at this point, the TLB
1869 * may hold both 4KB and 2MB page mappings for the address range [va,
1870 * va + NBPDR). Therefore, the entire range must be invalidated here.
1871 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
1872 * 4KB page mappings for the address range [va, va + NBPDR), and so a
1873 * single INVLPG suffices to invalidate the 2MB page mapping from the
1876 if ((pde & PG_PROMOTED) != 0)
1877 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
1879 pmap_invalidate_page(pmap, va);
1882 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
1885 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
1889 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
1891 KASSERT((sva & PAGE_MASK) == 0,
1892 ("pmap_invalidate_cache_range: sva not page-aligned"));
1893 KASSERT((eva & PAGE_MASK) == 0,
1894 ("pmap_invalidate_cache_range: eva not page-aligned"));
1897 if ((cpu_feature & CPUID_SS) != 0 && !force)
1898 ; /* If "Self Snoop" is supported and allowed, do nothing. */
1899 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
1900 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1902 * XXX: Some CPUs fault, hang, or trash the local APIC
1903 * registers if we use CLFLUSH on the local APIC
1904 * range. The local APIC is always uncached, so we
1905 * don't need to flush for that range anyway.
1907 if (pmap_kextract(sva) == lapic_paddr)
1911 * Otherwise, do per-cache line flush. Use the sfence
1912 * instruction to insure that previous stores are
1913 * included in the write-back. The processor
1914 * propagates flush to other processors in the cache
1918 for (; sva < eva; sva += cpu_clflush_line_size)
1921 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
1922 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1923 if (pmap_kextract(sva) == lapic_paddr)
1926 * Writes are ordered by CLFLUSH on Intel CPUs.
1928 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1930 for (; sva < eva; sva += cpu_clflush_line_size)
1932 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1937 * No targeted cache flush methods are supported by CPU,
1938 * or the supplied range is bigger than 2MB.
1939 * Globally invalidate cache.
1941 pmap_invalidate_cache();
1946 * Remove the specified set of pages from the data and instruction caches.
1948 * In contrast to pmap_invalidate_cache_range(), this function does not
1949 * rely on the CPU's self-snoop feature, because it is intended for use
1950 * when moving pages into a different cache domain.
1953 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1955 vm_offset_t daddr, eva;
1959 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
1960 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1961 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
1962 pmap_invalidate_cache();
1966 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
1968 for (i = 0; i < count; i++) {
1969 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
1970 eva = daddr + PAGE_SIZE;
1971 for (; daddr < eva; daddr += cpu_clflush_line_size) {
1980 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
1986 * Routine: pmap_extract
1988 * Extract the physical page address associated
1989 * with the given map/virtual_address pair.
1992 pmap_extract(pmap_t pmap, vm_offset_t va)
1996 pt_entry_t *pte, PG_V;
2000 PG_V = pmap_valid_bit(pmap);
2002 pdpe = pmap_pdpe(pmap, va);
2003 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2004 if ((*pdpe & PG_PS) != 0)
2005 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
2007 pde = pmap_pdpe_to_pde(pdpe, va);
2008 if ((*pde & PG_V) != 0) {
2009 if ((*pde & PG_PS) != 0) {
2010 pa = (*pde & PG_PS_FRAME) |
2013 pte = pmap_pde_to_pte(pde, va);
2014 pa = (*pte & PG_FRAME) |
2025 * Routine: pmap_extract_and_hold
2027 * Atomically extract and hold the physical page
2028 * with the given pmap and virtual address pair
2029 * if that mapping permits the given protection.
2032 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
2034 pd_entry_t pde, *pdep;
2035 pt_entry_t pte, PG_RW, PG_V;
2041 PG_RW = pmap_rw_bit(pmap);
2042 PG_V = pmap_valid_bit(pmap);
2045 pdep = pmap_pde(pmap, va);
2046 if (pdep != NULL && (pde = *pdep)) {
2048 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2049 if (vm_page_pa_tryrelock(pmap, (pde &
2050 PG_PS_FRAME) | (va & PDRMASK), &pa))
2052 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
2057 pte = *pmap_pde_to_pte(pdep, va);
2059 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2060 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2063 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
2074 pmap_kextract(vm_offset_t va)
2079 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2080 pa = DMAP_TO_PHYS(va);
2084 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2087 * Beware of a concurrent promotion that changes the
2088 * PDE at this point! For example, vtopte() must not
2089 * be used to access the PTE because it would use the
2090 * new PDE. It is, however, safe to use the old PDE
2091 * because the page table page is preserved by the
2094 pa = *pmap_pde_to_pte(&pde, va);
2095 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2101 /***************************************************
2102 * Low level mapping routines.....
2103 ***************************************************/
2106 * Add a wired page to the kva.
2107 * Note: not SMP coherent.
2110 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2115 pte_store(pte, pa | X86_PG_RW | X86_PG_V | X86_PG_G);
2118 static __inline void
2119 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2125 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2126 pte_store(pte, pa | X86_PG_RW | X86_PG_V | X86_PG_G | cache_bits);
2130 * Remove a page from the kernel pagetables.
2131 * Note: not SMP coherent.
2134 pmap_kremove(vm_offset_t va)
2143 * Used to map a range of physical addresses into kernel
2144 * virtual address space.
2146 * The value passed in '*virt' is a suggested virtual address for
2147 * the mapping. Architectures which can support a direct-mapped
2148 * physical to virtual region can return the appropriate address
2149 * within that region, leaving '*virt' unchanged. Other
2150 * architectures should map the pages starting at '*virt' and
2151 * update '*virt' with the first usable address after the mapped
2155 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2157 return PHYS_TO_DMAP(start);
2162 * Add a list of wired pages to the kva
2163 * this routine is only used for temporary
2164 * kernel mappings that do not need to have
2165 * page modification or references recorded.
2166 * Note that old mappings are simply written
2167 * over. The page *must* be wired.
2168 * Note: SMP coherent. Uses a ranged shootdown IPI.
2171 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2173 pt_entry_t *endpte, oldpte, pa, *pte;
2179 endpte = pte + count;
2180 while (pte < endpte) {
2182 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2183 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2184 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2186 pte_store(pte, pa | X86_PG_G | X86_PG_RW | X86_PG_V);
2190 if (__predict_false((oldpte & X86_PG_V) != 0))
2191 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2196 * This routine tears out page mappings from the
2197 * kernel -- it is meant only for temporary mappings.
2198 * Note: SMP coherent. Uses a ranged shootdown IPI.
2201 pmap_qremove(vm_offset_t sva, int count)
2206 while (count-- > 0) {
2207 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2211 pmap_invalidate_range(kernel_pmap, sva, va);
2214 /***************************************************
2215 * Page table page management routines.....
2216 ***************************************************/
2217 static __inline void
2218 pmap_free_zero_pages(struct spglist *free)
2223 for (count = 0; (m = SLIST_FIRST(free)) != NULL; count++) {
2224 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2225 /* Preserve the page's PG_ZERO setting. */
2226 vm_page_free_toq(m);
2228 atomic_subtract_int(&vm_cnt.v_wire_count, count);
2232 * Schedule the specified unused page table page to be freed. Specifically,
2233 * add the page to the specified list of pages that will be released to the
2234 * physical memory manager after the TLB has been updated.
2236 static __inline void
2237 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2238 boolean_t set_PG_ZERO)
2242 m->flags |= PG_ZERO;
2244 m->flags &= ~PG_ZERO;
2245 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2249 * Inserts the specified page table page into the specified pmap's collection
2250 * of idle page table pages. Each of a pmap's page table pages is responsible
2251 * for mapping a distinct range of virtual addresses. The pmap's collection is
2252 * ordered by this virtual address range.
2255 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2258 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2259 return (vm_radix_insert(&pmap->pm_root, mpte));
2263 * Removes the page table page mapping the specified virtual address from the
2264 * specified pmap's collection of idle page table pages, and returns it.
2265 * Otherwise, returns NULL if there is no page table page corresponding to the
2266 * specified virtual address.
2268 static __inline vm_page_t
2269 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
2272 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2273 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
2277 * Decrements a page table page's wire count, which is used to record the
2278 * number of valid page table entries within the page. If the wire count
2279 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2280 * page table page was unmapped and FALSE otherwise.
2282 static inline boolean_t
2283 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2287 if (m->wire_count == 0) {
2288 _pmap_unwire_ptp(pmap, va, m, free);
2295 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2298 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2300 * unmap the page table page
2302 if (m->pindex >= (NUPDE + NUPDPE)) {
2305 pml4 = pmap_pml4e(pmap, va);
2307 } else if (m->pindex >= NUPDE) {
2310 pdp = pmap_pdpe(pmap, va);
2315 pd = pmap_pde(pmap, va);
2318 pmap_resident_count_dec(pmap, 1);
2319 if (m->pindex < NUPDE) {
2320 /* We just released a PT, unhold the matching PD */
2323 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2324 pmap_unwire_ptp(pmap, va, pdpg, free);
2326 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2327 /* We just released a PD, unhold the matching PDP */
2330 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2331 pmap_unwire_ptp(pmap, va, pdppg, free);
2335 * Put page on a list so that it is released after
2336 * *ALL* TLB shootdown is done
2338 pmap_add_delayed_free_list(m, free, TRUE);
2342 * After removing a page table entry, this routine is used to
2343 * conditionally free the page, and manage the hold/wire counts.
2346 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2347 struct spglist *free)
2351 if (va >= VM_MAXUSER_ADDRESS)
2353 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2354 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2355 return (pmap_unwire_ptp(pmap, va, mpte, free));
2359 pmap_pinit0(pmap_t pmap)
2363 PMAP_LOCK_INIT(pmap);
2364 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2365 pmap->pm_cr3 = KPML4phys;
2366 pmap->pm_root.rt_root = 0;
2367 CPU_ZERO(&pmap->pm_active);
2368 TAILQ_INIT(&pmap->pm_pvchunk);
2369 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2370 pmap->pm_flags = pmap_flags;
2372 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2373 pmap->pm_pcids[i].pm_gen = 0;
2375 PCPU_SET(curpmap, kernel_pmap);
2376 pmap_activate(curthread);
2377 CPU_FILL(&kernel_pmap->pm_active);
2381 pmap_pinit_pml4(vm_page_t pml4pg)
2383 pml4_entry_t *pm_pml4;
2386 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2388 /* Wire in kernel global address entries. */
2389 for (i = 0; i < NKPML4E; i++) {
2390 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2393 for (i = 0; i < ndmpdpphys; i++) {
2394 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2398 /* install self-referential address mapping entry(s) */
2399 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2400 X86_PG_A | X86_PG_M;
2404 * Initialize a preallocated and zeroed pmap structure,
2405 * such as one in a vmspace structure.
2408 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2411 vm_paddr_t pml4phys;
2415 * allocate the page directory page
2417 while ((pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2418 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL)
2421 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2422 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2424 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2425 pmap->pm_pcids[i].pm_gen = 0;
2427 pmap->pm_cr3 = ~0; /* initialize to an invalid value */
2429 if ((pml4pg->flags & PG_ZERO) == 0)
2430 pagezero(pmap->pm_pml4);
2433 * Do not install the host kernel mappings in the nested page
2434 * tables. These mappings are meaningless in the guest physical
2437 if ((pmap->pm_type = pm_type) == PT_X86) {
2438 pmap->pm_cr3 = pml4phys;
2439 pmap_pinit_pml4(pml4pg);
2442 pmap->pm_root.rt_root = 0;
2443 CPU_ZERO(&pmap->pm_active);
2444 TAILQ_INIT(&pmap->pm_pvchunk);
2445 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2446 pmap->pm_flags = flags;
2447 pmap->pm_eptgen = 0;
2453 pmap_pinit(pmap_t pmap)
2456 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2460 * This routine is called if the desired page table page does not exist.
2462 * If page table page allocation fails, this routine may sleep before
2463 * returning NULL. It sleeps only if a lock pointer was given.
2465 * Note: If a page allocation fails at page table level two or three,
2466 * one or two pages may be held during the wait, only to be released
2467 * afterwards. This conservative approach is easily argued to avoid
2471 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2473 vm_page_t m, pdppg, pdpg;
2474 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2476 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2478 PG_A = pmap_accessed_bit(pmap);
2479 PG_M = pmap_modified_bit(pmap);
2480 PG_V = pmap_valid_bit(pmap);
2481 PG_RW = pmap_rw_bit(pmap);
2484 * Allocate a page table page.
2486 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2487 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2488 if (lockp != NULL) {
2489 RELEASE_PV_LIST_LOCK(lockp);
2491 PMAP_ASSERT_NOT_IN_DI();
2497 * Indicate the need to retry. While waiting, the page table
2498 * page may have been allocated.
2502 if ((m->flags & PG_ZERO) == 0)
2506 * Map the pagetable page into the process address space, if
2507 * it isn't already there.
2510 if (ptepindex >= (NUPDE + NUPDPE)) {
2512 vm_pindex_t pml4index;
2514 /* Wire up a new PDPE page */
2515 pml4index = ptepindex - (NUPDE + NUPDPE);
2516 pml4 = &pmap->pm_pml4[pml4index];
2517 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2519 } else if (ptepindex >= NUPDE) {
2520 vm_pindex_t pml4index;
2521 vm_pindex_t pdpindex;
2525 /* Wire up a new PDE page */
2526 pdpindex = ptepindex - NUPDE;
2527 pml4index = pdpindex >> NPML4EPGSHIFT;
2529 pml4 = &pmap->pm_pml4[pml4index];
2530 if ((*pml4 & PG_V) == 0) {
2531 /* Have to allocate a new pdp, recurse */
2532 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2535 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2536 vm_page_free_zero(m);
2540 /* Add reference to pdp page */
2541 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2542 pdppg->wire_count++;
2544 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2546 /* Now find the pdp page */
2547 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2548 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2551 vm_pindex_t pml4index;
2552 vm_pindex_t pdpindex;
2557 /* Wire up a new PTE page */
2558 pdpindex = ptepindex >> NPDPEPGSHIFT;
2559 pml4index = pdpindex >> NPML4EPGSHIFT;
2561 /* First, find the pdp and check that its valid. */
2562 pml4 = &pmap->pm_pml4[pml4index];
2563 if ((*pml4 & PG_V) == 0) {
2564 /* Have to allocate a new pd, recurse */
2565 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2568 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2569 vm_page_free_zero(m);
2572 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2573 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2575 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2576 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2577 if ((*pdp & PG_V) == 0) {
2578 /* Have to allocate a new pd, recurse */
2579 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2582 atomic_subtract_int(&vm_cnt.v_wire_count,
2584 vm_page_free_zero(m);
2588 /* Add reference to the pd page */
2589 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2593 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2595 /* Now we know where the page directory page is */
2596 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2597 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2600 pmap_resident_count_inc(pmap, 1);
2606 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2608 vm_pindex_t pdpindex, ptepindex;
2609 pdp_entry_t *pdpe, PG_V;
2612 PG_V = pmap_valid_bit(pmap);
2615 pdpe = pmap_pdpe(pmap, va);
2616 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2617 /* Add a reference to the pd page. */
2618 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2621 /* Allocate a pd page. */
2622 ptepindex = pmap_pde_pindex(va);
2623 pdpindex = ptepindex >> NPDPEPGSHIFT;
2624 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2625 if (pdpg == NULL && lockp != NULL)
2632 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2634 vm_pindex_t ptepindex;
2635 pd_entry_t *pd, PG_V;
2638 PG_V = pmap_valid_bit(pmap);
2641 * Calculate pagetable page index
2643 ptepindex = pmap_pde_pindex(va);
2646 * Get the page directory entry
2648 pd = pmap_pde(pmap, va);
2651 * This supports switching from a 2MB page to a
2654 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2655 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2657 * Invalidation of the 2MB page mapping may have caused
2658 * the deallocation of the underlying PD page.
2665 * If the page table page is mapped, we just increment the
2666 * hold count, and activate it.
2668 if (pd != NULL && (*pd & PG_V) != 0) {
2669 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2673 * Here if the pte page isn't mapped, or if it has been
2676 m = _pmap_allocpte(pmap, ptepindex, lockp);
2677 if (m == NULL && lockp != NULL)
2684 /***************************************************
2685 * Pmap allocation/deallocation routines.
2686 ***************************************************/
2689 * Release any resources held by the given physical map.
2690 * Called when a pmap initialized by pmap_pinit is being released.
2691 * Should only be called if the map contains no valid mappings.
2694 pmap_release(pmap_t pmap)
2699 KASSERT(pmap->pm_stats.resident_count == 0,
2700 ("pmap_release: pmap resident count %ld != 0",
2701 pmap->pm_stats.resident_count));
2702 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2703 ("pmap_release: pmap has reserved page table page(s)"));
2704 KASSERT(CPU_EMPTY(&pmap->pm_active),
2705 ("releasing active pmap %p", pmap));
2707 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2709 for (i = 0; i < NKPML4E; i++) /* KVA */
2710 pmap->pm_pml4[KPML4BASE + i] = 0;
2711 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
2712 pmap->pm_pml4[DMPML4I + i] = 0;
2713 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
2716 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2717 vm_page_free_zero(m);
2721 kvm_size(SYSCTL_HANDLER_ARGS)
2723 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2725 return sysctl_handle_long(oidp, &ksize, 0, req);
2727 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2728 0, 0, kvm_size, "LU", "Size of KVM");
2731 kvm_free(SYSCTL_HANDLER_ARGS)
2733 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2735 return sysctl_handle_long(oidp, &kfree, 0, req);
2737 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2738 0, 0, kvm_free, "LU", "Amount of KVM free");
2741 * grow the number of kernel page table entries, if needed
2744 pmap_growkernel(vm_offset_t addr)
2748 pd_entry_t *pde, newpdir;
2751 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2754 * Return if "addr" is within the range of kernel page table pages
2755 * that were preallocated during pmap bootstrap. Moreover, leave
2756 * "kernel_vm_end" and the kernel page table as they were.
2758 * The correctness of this action is based on the following
2759 * argument: vm_map_insert() allocates contiguous ranges of the
2760 * kernel virtual address space. It calls this function if a range
2761 * ends after "kernel_vm_end". If the kernel is mapped between
2762 * "kernel_vm_end" and "addr", then the range cannot begin at
2763 * "kernel_vm_end". In fact, its beginning address cannot be less
2764 * than the kernel. Thus, there is no immediate need to allocate
2765 * any new kernel page table pages between "kernel_vm_end" and
2768 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
2771 addr = roundup2(addr, NBPDR);
2772 if (addr - 1 >= kernel_map->max_offset)
2773 addr = kernel_map->max_offset;
2774 while (kernel_vm_end < addr) {
2775 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
2776 if ((*pdpe & X86_PG_V) == 0) {
2777 /* We need a new PDP entry */
2778 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
2779 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
2780 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2782 panic("pmap_growkernel: no memory to grow kernel");
2783 if ((nkpg->flags & PG_ZERO) == 0)
2784 pmap_zero_page(nkpg);
2785 paddr = VM_PAGE_TO_PHYS(nkpg);
2786 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
2787 X86_PG_A | X86_PG_M);
2788 continue; /* try again */
2790 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
2791 if ((*pde & X86_PG_V) != 0) {
2792 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2793 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2794 kernel_vm_end = kernel_map->max_offset;
2800 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
2801 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
2804 panic("pmap_growkernel: no memory to grow kernel");
2805 if ((nkpg->flags & PG_ZERO) == 0)
2806 pmap_zero_page(nkpg);
2807 paddr = VM_PAGE_TO_PHYS(nkpg);
2808 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
2809 pde_store(pde, newpdir);
2811 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2812 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2813 kernel_vm_end = kernel_map->max_offset;
2820 /***************************************************
2821 * page management routines.
2822 ***************************************************/
2824 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
2825 CTASSERT(_NPCM == 3);
2826 CTASSERT(_NPCPV == 168);
2828 static __inline struct pv_chunk *
2829 pv_to_chunk(pv_entry_t pv)
2832 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
2835 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
2837 #define PC_FREE0 0xfffffffffffffffful
2838 #define PC_FREE1 0xfffffffffffffffful
2839 #define PC_FREE2 0x000000fffffffffful
2841 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
2844 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2846 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2847 "Current number of pv entry chunks");
2848 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2849 "Current number of pv entry chunks allocated");
2850 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2851 "Current number of pv entry chunks frees");
2852 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
2853 "Number of times tried to get a chunk page but failed.");
2855 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
2856 static int pv_entry_spare;
2858 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2859 "Current number of pv entry frees");
2860 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
2861 "Current number of pv entry allocs");
2862 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2863 "Current number of pv entries");
2864 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2865 "Current number of spare pv entries");
2869 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
2874 pmap_invalidate_all(pmap);
2875 if (pmap != locked_pmap)
2878 pmap_delayed_invl_finished();
2882 * We are in a serious low memory condition. Resort to
2883 * drastic measures to free some pages so we can allocate
2884 * another pv entry chunk.
2886 * Returns NULL if PV entries were reclaimed from the specified pmap.
2888 * We do not, however, unmap 2mpages because subsequent accesses will
2889 * allocate per-page pv entries until repromotion occurs, thereby
2890 * exacerbating the shortage of free pv entries.
2893 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
2895 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
2896 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
2897 struct md_page *pvh;
2899 pmap_t next_pmap, pmap;
2900 pt_entry_t *pte, tpte;
2901 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
2905 struct spglist free;
2907 int bit, field, freed;
2909 static int active_reclaims = 0;
2911 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2912 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
2915 PG_G = PG_A = PG_M = PG_RW = 0;
2917 bzero(&pc_marker_b, sizeof(pc_marker_b));
2918 bzero(&pc_marker_end, sizeof(pc_marker_end));
2919 pc_marker = (struct pv_chunk *)&pc_marker_b;
2920 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
2923 * A delayed invalidation block should already be active if
2924 * pmap_advise() or pmap_remove() called this function by way
2925 * of pmap_demote_pde_locked().
2927 start_di = pmap_not_in_di();
2929 mtx_lock(&pv_chunks_mutex);
2931 TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
2932 TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
2933 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
2934 SLIST_EMPTY(&free)) {
2935 next_pmap = pc->pc_pmap;
2936 if (next_pmap == NULL) {
2938 * The next chunk is a marker. However, it is
2939 * not our marker, so active_reclaims must be
2940 * > 1. Consequently, the next_chunk code
2941 * will not rotate the pv_chunks list.
2945 mtx_unlock(&pv_chunks_mutex);
2948 * A pv_chunk can only be removed from the pc_lru list
2949 * when both pc_chunks_mutex is owned and the
2950 * corresponding pmap is locked.
2952 if (pmap != next_pmap) {
2953 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
2956 /* Avoid deadlock and lock recursion. */
2957 if (pmap > locked_pmap) {
2958 RELEASE_PV_LIST_LOCK(lockp);
2961 pmap_delayed_invl_started();
2962 mtx_lock(&pv_chunks_mutex);
2964 } else if (pmap != locked_pmap) {
2965 if (PMAP_TRYLOCK(pmap)) {
2967 pmap_delayed_invl_started();
2968 mtx_lock(&pv_chunks_mutex);
2971 pmap = NULL; /* pmap is not locked */
2972 mtx_lock(&pv_chunks_mutex);
2973 pc = TAILQ_NEXT(pc_marker, pc_lru);
2975 pc->pc_pmap != next_pmap)
2979 } else if (start_di)
2980 pmap_delayed_invl_started();
2981 PG_G = pmap_global_bit(pmap);
2982 PG_A = pmap_accessed_bit(pmap);
2983 PG_M = pmap_modified_bit(pmap);
2984 PG_RW = pmap_rw_bit(pmap);
2988 * Destroy every non-wired, 4 KB page mapping in the chunk.
2991 for (field = 0; field < _NPCM; field++) {
2992 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2993 inuse != 0; inuse &= ~(1UL << bit)) {
2995 pv = &pc->pc_pventry[field * 64 + bit];
2997 pde = pmap_pde(pmap, va);
2998 if ((*pde & PG_PS) != 0)
3000 pte = pmap_pde_to_pte(pde, va);
3001 if ((*pte & PG_W) != 0)
3003 tpte = pte_load_clear(pte);
3004 if ((tpte & PG_G) != 0)
3005 pmap_invalidate_page(pmap, va);
3006 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3007 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3009 if ((tpte & PG_A) != 0)
3010 vm_page_aflag_set(m, PGA_REFERENCED);
3011 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3012 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3014 if (TAILQ_EMPTY(&m->md.pv_list) &&
3015 (m->flags & PG_FICTITIOUS) == 0) {
3016 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3017 if (TAILQ_EMPTY(&pvh->pv_list)) {
3018 vm_page_aflag_clear(m,
3022 pmap_delayed_invl_page(m);
3023 pc->pc_map[field] |= 1UL << bit;
3024 pmap_unuse_pt(pmap, va, *pde, &free);
3029 mtx_lock(&pv_chunks_mutex);
3032 /* Every freed mapping is for a 4 KB page. */
3033 pmap_resident_count_dec(pmap, freed);
3034 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
3035 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
3036 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
3037 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3038 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
3039 pc->pc_map[2] == PC_FREE2) {
3040 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3041 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3042 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3043 /* Entire chunk is free; return it. */
3044 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3045 dump_drop_page(m_pc->phys_addr);
3046 mtx_lock(&pv_chunks_mutex);
3047 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3050 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3051 mtx_lock(&pv_chunks_mutex);
3052 /* One freed pv entry in locked_pmap is sufficient. */
3053 if (pmap == locked_pmap)
3056 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3057 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
3058 if (active_reclaims == 1 && pmap != NULL) {
3060 * Rotate the pv chunks list so that we do not
3061 * scan the same pv chunks that could not be
3062 * freed (because they contained a wired
3063 * and/or superpage mapping) on every
3064 * invocation of reclaim_pv_chunk().
3066 while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
3067 MPASS(pc->pc_pmap != NULL);
3068 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3069 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3073 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3074 TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
3076 mtx_unlock(&pv_chunks_mutex);
3077 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
3078 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
3079 m_pc = SLIST_FIRST(&free);
3080 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3081 /* Recycle a freed page table page. */
3082 m_pc->wire_count = 1;
3084 pmap_free_zero_pages(&free);
3089 * free the pv_entry back to the free list
3092 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3094 struct pv_chunk *pc;
3095 int idx, field, bit;
3097 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3098 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3099 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3100 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3101 pc = pv_to_chunk(pv);
3102 idx = pv - &pc->pc_pventry[0];
3105 pc->pc_map[field] |= 1ul << bit;
3106 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3107 pc->pc_map[2] != PC_FREE2) {
3108 /* 98% of the time, pc is already at the head of the list. */
3109 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3110 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3111 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3115 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3120 free_pv_chunk(struct pv_chunk *pc)
3124 mtx_lock(&pv_chunks_mutex);
3125 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3126 mtx_unlock(&pv_chunks_mutex);
3127 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3128 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3129 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3130 /* entire chunk is free, return it */
3131 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3132 dump_drop_page(m->phys_addr);
3133 vm_page_unwire(m, PQ_NONE);
3138 * Returns a new PV entry, allocating a new PV chunk from the system when
3139 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3140 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3143 * The given PV list lock may be released.
3146 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3150 struct pv_chunk *pc;
3153 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3154 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3156 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3158 for (field = 0; field < _NPCM; field++) {
3159 if (pc->pc_map[field]) {
3160 bit = bsfq(pc->pc_map[field]);
3164 if (field < _NPCM) {
3165 pv = &pc->pc_pventry[field * 64 + bit];
3166 pc->pc_map[field] &= ~(1ul << bit);
3167 /* If this was the last item, move it to tail */
3168 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3169 pc->pc_map[2] == 0) {
3170 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3171 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3174 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3175 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3179 /* No free items, allocate another chunk */
3180 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3183 if (lockp == NULL) {
3184 PV_STAT(pc_chunk_tryfail++);
3187 m = reclaim_pv_chunk(pmap, lockp);
3191 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3192 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3193 dump_add_page(m->phys_addr);
3194 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3196 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3197 pc->pc_map[1] = PC_FREE1;
3198 pc->pc_map[2] = PC_FREE2;
3199 mtx_lock(&pv_chunks_mutex);
3200 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3201 mtx_unlock(&pv_chunks_mutex);
3202 pv = &pc->pc_pventry[0];
3203 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3204 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3205 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3210 * Returns the number of one bits within the given PV chunk map.
3212 * The erratas for Intel processors state that "POPCNT Instruction May
3213 * Take Longer to Execute Than Expected". It is believed that the
3214 * issue is the spurious dependency on the destination register.
3215 * Provide a hint to the register rename logic that the destination
3216 * value is overwritten, by clearing it, as suggested in the
3217 * optimization manual. It should be cheap for unaffected processors
3220 * Reference numbers for erratas are
3221 * 4th Gen Core: HSD146
3222 * 5th Gen Core: BDM85
3223 * 6th Gen Core: SKL029
3226 popcnt_pc_map_pq(uint64_t *map)
3230 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3231 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3232 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3233 : "=&r" (result), "=&r" (tmp)
3234 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3239 * Ensure that the number of spare PV entries in the specified pmap meets or
3240 * exceeds the given count, "needed".
3242 * The given PV list lock may be released.
3245 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3247 struct pch new_tail;
3248 struct pv_chunk *pc;
3252 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3253 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3256 * Newly allocated PV chunks must be stored in a private list until
3257 * the required number of PV chunks have been allocated. Otherwise,
3258 * reclaim_pv_chunk() could recycle one of these chunks. In
3259 * contrast, these chunks must be added to the pmap upon allocation.
3261 TAILQ_INIT(&new_tail);
3264 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3266 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3267 bit_count((bitstr_t *)pc->pc_map, 0,
3268 sizeof(pc->pc_map) * NBBY, &free);
3271 free = popcnt_pc_map_pq(pc->pc_map);
3275 if (avail >= needed)
3278 for (; avail < needed; avail += _NPCPV) {
3279 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3282 m = reclaim_pv_chunk(pmap, lockp);
3286 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3287 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3288 dump_add_page(m->phys_addr);
3289 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3291 pc->pc_map[0] = PC_FREE0;
3292 pc->pc_map[1] = PC_FREE1;
3293 pc->pc_map[2] = PC_FREE2;
3294 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3295 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3296 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3298 if (!TAILQ_EMPTY(&new_tail)) {
3299 mtx_lock(&pv_chunks_mutex);
3300 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3301 mtx_unlock(&pv_chunks_mutex);
3306 * First find and then remove the pv entry for the specified pmap and virtual
3307 * address from the specified pv list. Returns the pv entry if found and NULL
3308 * otherwise. This operation can be performed on pv lists for either 4KB or
3309 * 2MB page mappings.
3311 static __inline pv_entry_t
3312 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3316 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3317 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3318 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3327 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3328 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3329 * entries for each of the 4KB page mappings.
3332 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3333 struct rwlock **lockp)
3335 struct md_page *pvh;
3336 struct pv_chunk *pc;
3338 vm_offset_t va_last;
3342 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3343 KASSERT((pa & PDRMASK) == 0,
3344 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3345 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3348 * Transfer the 2mpage's pv entry for this mapping to the first
3349 * page's pv list. Once this transfer begins, the pv list lock
3350 * must not be released until the last pv entry is reinstantiated.
3352 pvh = pa_to_pvh(pa);
3353 va = trunc_2mpage(va);
3354 pv = pmap_pvh_remove(pvh, pmap, va);
3355 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3356 m = PHYS_TO_VM_PAGE(pa);
3357 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3359 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3360 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3361 va_last = va + NBPDR - PAGE_SIZE;
3363 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3364 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3365 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3366 for (field = 0; field < _NPCM; field++) {
3367 while (pc->pc_map[field]) {
3368 bit = bsfq(pc->pc_map[field]);
3369 pc->pc_map[field] &= ~(1ul << bit);
3370 pv = &pc->pc_pventry[field * 64 + bit];
3374 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3375 ("pmap_pv_demote_pde: page %p is not managed", m));
3376 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3382 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3383 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3386 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3387 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3388 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3390 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3391 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3394 #if VM_NRESERVLEVEL > 0
3396 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3397 * replace the many pv entries for the 4KB page mappings by a single pv entry
3398 * for the 2MB page mapping.
3401 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3402 struct rwlock **lockp)
3404 struct md_page *pvh;
3406 vm_offset_t va_last;
3409 KASSERT((pa & PDRMASK) == 0,
3410 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3411 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3414 * Transfer the first page's pv entry for this mapping to the 2mpage's
3415 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3416 * a transfer avoids the possibility that get_pv_entry() calls
3417 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3418 * mappings that is being promoted.
3420 m = PHYS_TO_VM_PAGE(pa);
3421 va = trunc_2mpage(va);
3422 pv = pmap_pvh_remove(&m->md, pmap, va);
3423 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3424 pvh = pa_to_pvh(pa);
3425 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3427 /* Free the remaining NPTEPG - 1 pv entries. */
3428 va_last = va + NBPDR - PAGE_SIZE;
3432 pmap_pvh_free(&m->md, pmap, va);
3433 } while (va < va_last);
3435 #endif /* VM_NRESERVLEVEL > 0 */
3438 * First find and then destroy the pv entry for the specified pmap and virtual
3439 * address. This operation can be performed on pv lists for either 4KB or 2MB
3443 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3447 pv = pmap_pvh_remove(pvh, pmap, va);
3448 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3449 free_pv_entry(pmap, pv);
3453 * Conditionally create the PV entry for a 4KB page mapping if the required
3454 * memory can be allocated without resorting to reclamation.
3457 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3458 struct rwlock **lockp)
3462 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3463 /* Pass NULL instead of the lock pointer to disable reclamation. */
3464 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3466 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3467 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3475 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3476 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3477 * false if the PV entry cannot be allocated without resorting to reclamation.
3480 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
3481 struct rwlock **lockp)
3483 struct md_page *pvh;
3487 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3488 /* Pass NULL instead of the lock pointer to disable reclamation. */
3489 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3490 NULL : lockp)) == NULL)
3493 pa = pde & PG_PS_FRAME;
3494 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3495 pvh = pa_to_pvh(pa);
3496 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3502 * Fills a page table page with mappings to consecutive physical pages.
3505 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3509 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3511 newpte += PAGE_SIZE;
3516 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3517 * mapping is invalidated.
3520 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3522 struct rwlock *lock;
3526 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3533 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3534 struct rwlock **lockp)
3536 pd_entry_t newpde, oldpde;
3537 pt_entry_t *firstpte, newpte;
3538 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3541 struct spglist free;
3545 PG_G = pmap_global_bit(pmap);
3546 PG_A = pmap_accessed_bit(pmap);
3547 PG_M = pmap_modified_bit(pmap);
3548 PG_RW = pmap_rw_bit(pmap);
3549 PG_V = pmap_valid_bit(pmap);
3550 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3552 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3554 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3555 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3556 if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
3558 KASSERT((oldpde & PG_W) == 0,
3559 ("pmap_demote_pde: page table page for a wired mapping"
3563 * Invalidate the 2MB page mapping and return "failure" if the
3564 * mapping was never accessed or the allocation of the new
3565 * page table page fails. If the 2MB page mapping belongs to
3566 * the direct map region of the kernel's address space, then
3567 * the page allocation request specifies the highest possible
3568 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3569 * normal. Page table pages are preallocated for every other
3570 * part of the kernel address space, so the direct map region
3571 * is the only part of the kernel address space that must be
3574 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3575 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3576 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3577 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3579 sva = trunc_2mpage(va);
3580 pmap_remove_pde(pmap, pde, sva, &free, lockp);
3581 if ((oldpde & PG_G) == 0)
3582 pmap_invalidate_pde_page(pmap, sva, oldpde);
3583 pmap_free_zero_pages(&free);
3584 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3585 " in pmap %p", va, pmap);
3588 if (va < VM_MAXUSER_ADDRESS)
3589 pmap_resident_count_inc(pmap, 1);
3591 mptepa = VM_PAGE_TO_PHYS(mpte);
3592 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3593 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3594 KASSERT((oldpde & PG_A) != 0,
3595 ("pmap_demote_pde: oldpde is missing PG_A"));
3596 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3597 ("pmap_demote_pde: oldpde is missing PG_M"));
3598 newpte = oldpde & ~PG_PS;
3599 newpte = pmap_swap_pat(pmap, newpte);
3602 * If the page table page is new, initialize it.
3604 if (mpte->wire_count == 1) {
3605 mpte->wire_count = NPTEPG;
3606 pmap_fill_ptp(firstpte, newpte);
3608 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3609 ("pmap_demote_pde: firstpte and newpte map different physical"
3613 * If the mapping has changed attributes, update the page table
3616 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3617 pmap_fill_ptp(firstpte, newpte);
3620 * The spare PV entries must be reserved prior to demoting the
3621 * mapping, that is, prior to changing the PDE. Otherwise, the state
3622 * of the PDE and the PV lists will be inconsistent, which can result
3623 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3624 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3625 * PV entry for the 2MB page mapping that is being demoted.
3627 if ((oldpde & PG_MANAGED) != 0)
3628 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3631 * Demote the mapping. This pmap is locked. The old PDE has
3632 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3633 * set. Thus, there is no danger of a race with another
3634 * processor changing the setting of PG_A and/or PG_M between
3635 * the read above and the store below.
3637 if (workaround_erratum383)
3638 pmap_update_pde(pmap, va, pde, newpde);
3640 pde_store(pde, newpde);
3643 * Invalidate a stale recursive mapping of the page table page.
3645 if (va >= VM_MAXUSER_ADDRESS)
3646 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3649 * Demote the PV entry.
3651 if ((oldpde & PG_MANAGED) != 0)
3652 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3654 atomic_add_long(&pmap_pde_demotions, 1);
3655 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3656 " in pmap %p", va, pmap);
3661 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3664 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3670 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3671 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3672 mpte = pmap_remove_pt_page(pmap, va);
3674 panic("pmap_remove_kernel_pde: Missing pt page.");
3676 mptepa = VM_PAGE_TO_PHYS(mpte);
3677 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3680 * Initialize the page table page.
3682 pagezero((void *)PHYS_TO_DMAP(mptepa));
3685 * Demote the mapping.
3687 if (workaround_erratum383)
3688 pmap_update_pde(pmap, va, pde, newpde);
3690 pde_store(pde, newpde);
3693 * Invalidate a stale recursive mapping of the page table page.
3695 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3699 * pmap_remove_pde: do the things to unmap a superpage in a process
3702 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
3703 struct spglist *free, struct rwlock **lockp)
3705 struct md_page *pvh;
3707 vm_offset_t eva, va;
3709 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3711 PG_G = pmap_global_bit(pmap);
3712 PG_A = pmap_accessed_bit(pmap);
3713 PG_M = pmap_modified_bit(pmap);
3714 PG_RW = pmap_rw_bit(pmap);
3716 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3717 KASSERT((sva & PDRMASK) == 0,
3718 ("pmap_remove_pde: sva is not 2mpage aligned"));
3719 oldpde = pte_load_clear(pdq);
3721 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
3722 if ((oldpde & PG_G) != 0)
3723 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
3724 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
3725 if (oldpde & PG_MANAGED) {
3726 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
3727 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
3728 pmap_pvh_free(pvh, pmap, sva);
3730 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3731 va < eva; va += PAGE_SIZE, m++) {
3732 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3735 vm_page_aflag_set(m, PGA_REFERENCED);
3736 if (TAILQ_EMPTY(&m->md.pv_list) &&
3737 TAILQ_EMPTY(&pvh->pv_list))
3738 vm_page_aflag_clear(m, PGA_WRITEABLE);
3739 pmap_delayed_invl_page(m);
3742 if (pmap == kernel_pmap) {
3743 pmap_remove_kernel_pde(pmap, pdq, sva);
3745 mpte = pmap_remove_pt_page(pmap, sva);
3747 pmap_resident_count_dec(pmap, 1);
3748 KASSERT(mpte->wire_count == NPTEPG,
3749 ("pmap_remove_pde: pte page wire count error"));
3750 mpte->wire_count = 0;
3751 pmap_add_delayed_free_list(mpte, free, FALSE);
3754 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
3758 * pmap_remove_pte: do the things to unmap a page in a process
3761 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
3762 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
3764 struct md_page *pvh;
3765 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
3768 PG_A = pmap_accessed_bit(pmap);
3769 PG_M = pmap_modified_bit(pmap);
3770 PG_RW = pmap_rw_bit(pmap);
3772 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3773 oldpte = pte_load_clear(ptq);
3775 pmap->pm_stats.wired_count -= 1;
3776 pmap_resident_count_dec(pmap, 1);
3777 if (oldpte & PG_MANAGED) {
3778 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
3779 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3782 vm_page_aflag_set(m, PGA_REFERENCED);
3783 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3784 pmap_pvh_free(&m->md, pmap, va);
3785 if (TAILQ_EMPTY(&m->md.pv_list) &&
3786 (m->flags & PG_FICTITIOUS) == 0) {
3787 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3788 if (TAILQ_EMPTY(&pvh->pv_list))
3789 vm_page_aflag_clear(m, PGA_WRITEABLE);
3791 pmap_delayed_invl_page(m);
3793 return (pmap_unuse_pt(pmap, va, ptepde, free));
3797 * Remove a single page from a process address space
3800 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
3801 struct spglist *free)
3803 struct rwlock *lock;
3804 pt_entry_t *pte, PG_V;
3806 PG_V = pmap_valid_bit(pmap);
3807 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3808 if ((*pde & PG_V) == 0)
3810 pte = pmap_pde_to_pte(pde, va);
3811 if ((*pte & PG_V) == 0)
3814 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
3817 pmap_invalidate_page(pmap, va);
3821 * Removes the specified range of addresses from the page table page.
3824 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
3825 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
3827 pt_entry_t PG_G, *pte;
3831 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3832 PG_G = pmap_global_bit(pmap);
3835 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
3839 pmap_invalidate_range(pmap, va, sva);
3844 if ((*pte & PG_G) == 0)
3848 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
3854 pmap_invalidate_range(pmap, va, sva);
3859 * Remove the given range of addresses from the specified map.
3861 * It is assumed that the start and end are properly
3862 * rounded to the page size.
3865 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3867 struct rwlock *lock;
3868 vm_offset_t va_next;
3869 pml4_entry_t *pml4e;
3871 pd_entry_t ptpaddr, *pde;
3872 pt_entry_t PG_G, PG_V;
3873 struct spglist free;
3876 PG_G = pmap_global_bit(pmap);
3877 PG_V = pmap_valid_bit(pmap);
3880 * Perform an unsynchronized read. This is, however, safe.
3882 if (pmap->pm_stats.resident_count == 0)
3888 pmap_delayed_invl_started();
3892 * special handling of removing one page. a very
3893 * common operation and easy to short circuit some
3896 if (sva + PAGE_SIZE == eva) {
3897 pde = pmap_pde(pmap, sva);
3898 if (pde && (*pde & PG_PS) == 0) {
3899 pmap_remove_page(pmap, sva, pde, &free);
3905 for (; sva < eva; sva = va_next) {
3907 if (pmap->pm_stats.resident_count == 0)
3910 pml4e = pmap_pml4e(pmap, sva);
3911 if ((*pml4e & PG_V) == 0) {
3912 va_next = (sva + NBPML4) & ~PML4MASK;
3918 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
3919 if ((*pdpe & PG_V) == 0) {
3920 va_next = (sva + NBPDP) & ~PDPMASK;
3927 * Calculate index for next page table.
3929 va_next = (sva + NBPDR) & ~PDRMASK;
3933 pde = pmap_pdpe_to_pde(pdpe, sva);
3937 * Weed out invalid mappings.
3943 * Check for large page.
3945 if ((ptpaddr & PG_PS) != 0) {
3947 * Are we removing the entire large page? If not,
3948 * demote the mapping and fall through.
3950 if (sva + NBPDR == va_next && eva >= va_next) {
3952 * The TLB entry for a PG_G mapping is
3953 * invalidated by pmap_remove_pde().
3955 if ((ptpaddr & PG_G) == 0)
3957 pmap_remove_pde(pmap, pde, sva, &free, &lock);
3959 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
3961 /* The large page mapping was destroyed. */
3968 * Limit our scan to either the end of the va represented
3969 * by the current page table page, or to the end of the
3970 * range being removed.
3975 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
3982 pmap_invalidate_all(pmap);
3984 pmap_delayed_invl_finished();
3985 pmap_free_zero_pages(&free);
3989 * Routine: pmap_remove_all
3991 * Removes this physical page from
3992 * all physical maps in which it resides.
3993 * Reflects back modify bits to the pager.
3996 * Original versions of this routine were very
3997 * inefficient because they iteratively called
3998 * pmap_remove (slow...)
4002 pmap_remove_all(vm_page_t m)
4004 struct md_page *pvh;
4007 struct rwlock *lock;
4008 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
4011 struct spglist free;
4012 int pvh_gen, md_gen;
4014 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4015 ("pmap_remove_all: page %p is not managed", m));
4017 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4018 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
4019 pa_to_pvh(VM_PAGE_TO_PHYS(m));
4022 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
4024 if (!PMAP_TRYLOCK(pmap)) {
4025 pvh_gen = pvh->pv_gen;
4029 if (pvh_gen != pvh->pv_gen) {
4036 pde = pmap_pde(pmap, va);
4037 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
4040 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4042 if (!PMAP_TRYLOCK(pmap)) {
4043 pvh_gen = pvh->pv_gen;
4044 md_gen = m->md.pv_gen;
4048 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
4054 PG_A = pmap_accessed_bit(pmap);
4055 PG_M = pmap_modified_bit(pmap);
4056 PG_RW = pmap_rw_bit(pmap);
4057 pmap_resident_count_dec(pmap, 1);
4058 pde = pmap_pde(pmap, pv->pv_va);
4059 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
4060 " a 2mpage in page %p's pv list", m));
4061 pte = pmap_pde_to_pte(pde, pv->pv_va);
4062 tpte = pte_load_clear(pte);
4064 pmap->pm_stats.wired_count--;
4066 vm_page_aflag_set(m, PGA_REFERENCED);
4069 * Update the vm_page_t clean and reference bits.
4071 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4073 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
4074 pmap_invalidate_page(pmap, pv->pv_va);
4075 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4077 free_pv_entry(pmap, pv);
4080 vm_page_aflag_clear(m, PGA_WRITEABLE);
4082 pmap_delayed_invl_wait(m);
4083 pmap_free_zero_pages(&free);
4087 * pmap_protect_pde: do the things to protect a 2mpage in a process
4090 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
4092 pd_entry_t newpde, oldpde;
4093 vm_offset_t eva, va;
4095 boolean_t anychanged;
4096 pt_entry_t PG_G, PG_M, PG_RW;
4098 PG_G = pmap_global_bit(pmap);
4099 PG_M = pmap_modified_bit(pmap);
4100 PG_RW = pmap_rw_bit(pmap);
4102 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4103 KASSERT((sva & PDRMASK) == 0,
4104 ("pmap_protect_pde: sva is not 2mpage aligned"));
4107 oldpde = newpde = *pde;
4108 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4109 (PG_MANAGED | PG_M | PG_RW)) {
4111 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4112 va < eva; va += PAGE_SIZE, m++)
4115 if ((prot & VM_PROT_WRITE) == 0)
4116 newpde &= ~(PG_RW | PG_M);
4117 if ((prot & VM_PROT_EXECUTE) == 0)
4119 if (newpde != oldpde) {
4121 * As an optimization to future operations on this PDE, clear
4122 * PG_PROMOTED. The impending invalidation will remove any
4123 * lingering 4KB page mappings from the TLB.
4125 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
4127 if ((oldpde & PG_G) != 0)
4128 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4132 return (anychanged);
4136 * Set the physical protection on the
4137 * specified range of this map as requested.
4140 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4142 vm_offset_t va_next;
4143 pml4_entry_t *pml4e;
4145 pd_entry_t ptpaddr, *pde;
4146 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4147 boolean_t anychanged;
4149 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4150 if (prot == VM_PROT_NONE) {
4151 pmap_remove(pmap, sva, eva);
4155 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4156 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4159 PG_G = pmap_global_bit(pmap);
4160 PG_M = pmap_modified_bit(pmap);
4161 PG_V = pmap_valid_bit(pmap);
4162 PG_RW = pmap_rw_bit(pmap);
4166 * Although this function delays and batches the invalidation
4167 * of stale TLB entries, it does not need to call
4168 * pmap_delayed_invl_started() and
4169 * pmap_delayed_invl_finished(), because it does not
4170 * ordinarily destroy mappings. Stale TLB entries from
4171 * protection-only changes need only be invalidated before the
4172 * pmap lock is released, because protection-only changes do
4173 * not destroy PV entries. Even operations that iterate over
4174 * a physical page's PV list of mappings, like
4175 * pmap_remove_write(), acquire the pmap lock for each
4176 * mapping. Consequently, for protection-only changes, the
4177 * pmap lock suffices to synchronize both page table and TLB
4180 * This function only destroys a mapping if pmap_demote_pde()
4181 * fails. In that case, stale TLB entries are immediately
4186 for (; sva < eva; sva = va_next) {
4188 pml4e = pmap_pml4e(pmap, sva);
4189 if ((*pml4e & PG_V) == 0) {
4190 va_next = (sva + NBPML4) & ~PML4MASK;
4196 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4197 if ((*pdpe & PG_V) == 0) {
4198 va_next = (sva + NBPDP) & ~PDPMASK;
4204 va_next = (sva + NBPDR) & ~PDRMASK;
4208 pde = pmap_pdpe_to_pde(pdpe, sva);
4212 * Weed out invalid mappings.
4218 * Check for large page.
4220 if ((ptpaddr & PG_PS) != 0) {
4222 * Are we protecting the entire large page? If not,
4223 * demote the mapping and fall through.
4225 if (sva + NBPDR == va_next && eva >= va_next) {
4227 * The TLB entry for a PG_G mapping is
4228 * invalidated by pmap_protect_pde().
4230 if (pmap_protect_pde(pmap, pde, sva, prot))
4233 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4235 * The large page mapping was destroyed.
4244 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4246 pt_entry_t obits, pbits;
4250 obits = pbits = *pte;
4251 if ((pbits & PG_V) == 0)
4254 if ((prot & VM_PROT_WRITE) == 0) {
4255 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4256 (PG_MANAGED | PG_M | PG_RW)) {
4257 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4260 pbits &= ~(PG_RW | PG_M);
4262 if ((prot & VM_PROT_EXECUTE) == 0)
4265 if (pbits != obits) {
4266 if (!atomic_cmpset_long(pte, obits, pbits))
4269 pmap_invalidate_page(pmap, sva);
4276 pmap_invalidate_all(pmap);
4280 #if VM_NRESERVLEVEL > 0
4282 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4283 * single page table page (PTP) to a single 2MB page mapping. For promotion
4284 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4285 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4286 * identical characteristics.
4289 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4290 struct rwlock **lockp)
4293 pt_entry_t *firstpte, oldpte, pa, *pte;
4294 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4298 PG_A = pmap_accessed_bit(pmap);
4299 PG_G = pmap_global_bit(pmap);
4300 PG_M = pmap_modified_bit(pmap);
4301 PG_V = pmap_valid_bit(pmap);
4302 PG_RW = pmap_rw_bit(pmap);
4303 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4305 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4308 * Examine the first PTE in the specified PTP. Abort if this PTE is
4309 * either invalid, unused, or does not map the first 4KB physical page
4310 * within a 2MB page.
4312 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4315 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4316 atomic_add_long(&pmap_pde_p_failures, 1);
4317 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4318 " in pmap %p", va, pmap);
4321 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4323 * When PG_M is already clear, PG_RW can be cleared without
4324 * a TLB invalidation.
4326 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4332 * Examine each of the other PTEs in the specified PTP. Abort if this
4333 * PTE maps an unexpected 4KB physical page or does not have identical
4334 * characteristics to the first PTE.
4336 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4337 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4340 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4341 atomic_add_long(&pmap_pde_p_failures, 1);
4342 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4343 " in pmap %p", va, pmap);
4346 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4348 * When PG_M is already clear, PG_RW can be cleared
4349 * without a TLB invalidation.
4351 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4354 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4355 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4356 (va & ~PDRMASK), pmap);
4358 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4359 atomic_add_long(&pmap_pde_p_failures, 1);
4360 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4361 " in pmap %p", va, pmap);
4368 * Save the page table page in its current state until the PDE
4369 * mapping the superpage is demoted by pmap_demote_pde() or
4370 * destroyed by pmap_remove_pde().
4372 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4373 KASSERT(mpte >= vm_page_array &&
4374 mpte < &vm_page_array[vm_page_array_size],
4375 ("pmap_promote_pde: page table page is out of range"));
4376 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4377 ("pmap_promote_pde: page table page's pindex is wrong"));
4378 if (pmap_insert_pt_page(pmap, mpte)) {
4379 atomic_add_long(&pmap_pde_p_failures, 1);
4381 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4387 * Promote the pv entries.
4389 if ((newpde & PG_MANAGED) != 0)
4390 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4393 * Propagate the PAT index to its proper position.
4395 newpde = pmap_swap_pat(pmap, newpde);
4398 * Map the superpage.
4400 if (workaround_erratum383)
4401 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4403 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
4405 atomic_add_long(&pmap_pde_promotions, 1);
4406 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4407 " in pmap %p", va, pmap);
4409 #endif /* VM_NRESERVLEVEL > 0 */
4412 * Insert the given physical page (p) at
4413 * the specified virtual address (v) in the
4414 * target physical map with the protection requested.
4416 * If specified, the page will be wired down, meaning
4417 * that the related pte can not be reclaimed.
4419 * NB: This is the only routine which MAY NOT lazy-evaluate
4420 * or lose information. That is, this routine must actually
4421 * insert this page into the given map NOW.
4423 * When destroying both a page table and PV entry, this function
4424 * performs the TLB invalidation before releasing the PV list
4425 * lock, so we do not need pmap_delayed_invl_page() calls here.
4428 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4429 u_int flags, int8_t psind)
4431 struct rwlock *lock;
4433 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4434 pt_entry_t newpte, origpte;
4441 PG_A = pmap_accessed_bit(pmap);
4442 PG_G = pmap_global_bit(pmap);
4443 PG_M = pmap_modified_bit(pmap);
4444 PG_V = pmap_valid_bit(pmap);
4445 PG_RW = pmap_rw_bit(pmap);
4447 va = trunc_page(va);
4448 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4449 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4450 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4452 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4453 va >= kmi.clean_eva,
4454 ("pmap_enter: managed mapping within the clean submap"));
4455 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4456 VM_OBJECT_ASSERT_LOCKED(m->object);
4457 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
4458 ("pmap_enter: flags %u has reserved bits set", flags));
4459 pa = VM_PAGE_TO_PHYS(m);
4460 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4461 if ((flags & VM_PROT_WRITE) != 0)
4463 if ((prot & VM_PROT_WRITE) != 0)
4465 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4466 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4467 if ((prot & VM_PROT_EXECUTE) == 0)
4469 if ((flags & PMAP_ENTER_WIRED) != 0)
4471 if (va < VM_MAXUSER_ADDRESS)
4473 if (pmap == kernel_pmap)
4475 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
4478 * Set modified bit gratuitously for writeable mappings if
4479 * the page is unmanaged. We do not want to take a fault
4480 * to do the dirty bit accounting for these mappings.
4482 if ((m->oflags & VPO_UNMANAGED) != 0) {
4483 if ((newpte & PG_RW) != 0)
4486 newpte |= PG_MANAGED;
4491 /* Assert the required virtual and physical alignment. */
4492 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
4493 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4494 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
4500 * In the case that a page table page is not
4501 * resident, we are creating it here.
4504 pde = pmap_pde(pmap, va);
4505 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4506 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4507 pte = pmap_pde_to_pte(pde, va);
4508 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4509 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4512 } else if (va < VM_MAXUSER_ADDRESS) {
4514 * Here if the pte page isn't mapped, or if it has been
4517 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4518 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4519 nosleep ? NULL : &lock);
4520 if (mpte == NULL && nosleep) {
4521 rv = KERN_RESOURCE_SHORTAGE;
4526 panic("pmap_enter: invalid page directory va=%#lx", va);
4531 * Is the specified virtual address already mapped?
4533 if ((origpte & PG_V) != 0) {
4535 * Wiring change, just update stats. We don't worry about
4536 * wiring PT pages as they remain resident as long as there
4537 * are valid mappings in them. Hence, if a user page is wired,
4538 * the PT page will be also.
4540 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4541 pmap->pm_stats.wired_count++;
4542 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4543 pmap->pm_stats.wired_count--;
4546 * Remove the extra PT page reference.
4550 KASSERT(mpte->wire_count > 0,
4551 ("pmap_enter: missing reference to page table page,"
4556 * Has the physical page changed?
4558 opa = origpte & PG_FRAME;
4561 * No, might be a protection or wiring change.
4563 if ((origpte & PG_MANAGED) != 0 &&
4564 (newpte & PG_RW) != 0)
4565 vm_page_aflag_set(m, PGA_WRITEABLE);
4566 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4572 * Increment the counters.
4574 if ((newpte & PG_W) != 0)
4575 pmap->pm_stats.wired_count++;
4576 pmap_resident_count_inc(pmap, 1);
4580 * Enter on the PV list if part of our managed memory.
4582 if ((newpte & PG_MANAGED) != 0) {
4583 pv = get_pv_entry(pmap, &lock);
4585 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4586 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4588 if ((newpte & PG_RW) != 0)
4589 vm_page_aflag_set(m, PGA_WRITEABLE);
4595 if ((origpte & PG_V) != 0) {
4597 origpte = pte_load_store(pte, newpte);
4598 opa = origpte & PG_FRAME;
4600 if ((origpte & PG_MANAGED) != 0) {
4601 om = PHYS_TO_VM_PAGE(opa);
4602 if ((origpte & (PG_M | PG_RW)) == (PG_M |
4605 if ((origpte & PG_A) != 0)
4606 vm_page_aflag_set(om, PGA_REFERENCED);
4607 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4608 pmap_pvh_free(&om->md, pmap, va);
4609 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4610 TAILQ_EMPTY(&om->md.pv_list) &&
4611 ((om->flags & PG_FICTITIOUS) != 0 ||
4612 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4613 vm_page_aflag_clear(om, PGA_WRITEABLE);
4615 } else if ((newpte & PG_M) == 0 && (origpte & (PG_M |
4616 PG_RW)) == (PG_M | PG_RW)) {
4617 if ((origpte & PG_MANAGED) != 0)
4621 * Although the PTE may still have PG_RW set, TLB
4622 * invalidation may nonetheless be required because
4623 * the PTE no longer has PG_M set.
4625 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4627 * This PTE change does not require TLB invalidation.
4631 if ((origpte & PG_A) != 0)
4632 pmap_invalidate_page(pmap, va);
4634 pte_store(pte, newpte);
4638 #if VM_NRESERVLEVEL > 0
4640 * If both the page table page and the reservation are fully
4641 * populated, then attempt promotion.
4643 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4644 pmap_ps_enabled(pmap) &&
4645 (m->flags & PG_FICTITIOUS) == 0 &&
4646 vm_reserv_level_iffullpop(m) == 0)
4647 pmap_promote_pde(pmap, pde, va, &lock);
4659 * Tries to create a read- and/or execute-only 2MB page mapping. Returns true
4660 * if successful. Returns false if (1) a page table page cannot be allocated
4661 * without sleeping, (2) a mapping already exists at the specified virtual
4662 * address, or (3) a PV entry cannot be allocated without reclaiming another
4666 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4667 struct rwlock **lockp)
4672 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4673 PG_V = pmap_valid_bit(pmap);
4674 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
4676 if ((m->oflags & VPO_UNMANAGED) == 0)
4677 newpde |= PG_MANAGED;
4678 if ((prot & VM_PROT_EXECUTE) == 0)
4680 if (va < VM_MAXUSER_ADDRESS)
4682 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
4683 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
4688 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
4689 * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
4690 * otherwise. Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
4691 * a mapping already exists at the specified virtual address. Returns
4692 * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
4693 * page allocation failed. Returns KERN_RESOURCE_SHORTAGE if
4694 * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
4696 * The parameter "m" is only used when creating a managed, writeable mapping.
4699 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
4700 vm_page_t m, struct rwlock **lockp)
4702 struct spglist free;
4703 pd_entry_t oldpde, *pde;
4704 pt_entry_t PG_G, PG_RW, PG_V;
4707 PG_G = pmap_global_bit(pmap);
4708 PG_RW = pmap_rw_bit(pmap);
4709 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
4710 ("pmap_enter_pde: newpde is missing PG_M"));
4711 PG_V = pmap_valid_bit(pmap);
4712 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4714 if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
4715 NULL : lockp)) == NULL) {
4716 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4717 " in pmap %p", va, pmap);
4718 return (KERN_RESOURCE_SHORTAGE);
4720 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4721 pde = &pde[pmap_pde_index(va)];
4723 if ((oldpde & PG_V) != 0) {
4724 KASSERT(pdpg->wire_count > 1,
4725 ("pmap_enter_pde: pdpg's wire count is too low"));
4726 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
4728 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4729 " in pmap %p", va, pmap);
4730 return (KERN_FAILURE);
4732 /* Break the existing mapping(s). */
4734 if ((oldpde & PG_PS) != 0) {
4736 * The reference to the PD page that was acquired by
4737 * pmap_allocpde() ensures that it won't be freed.
4738 * However, if the PDE resulted from a promotion, then
4739 * a reserved PT page could be freed.
4741 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
4742 if ((oldpde & PG_G) == 0)
4743 pmap_invalidate_pde_page(pmap, va, oldpde);
4745 pmap_delayed_invl_started();
4746 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
4748 pmap_invalidate_all(pmap);
4749 pmap_delayed_invl_finished();
4751 pmap_free_zero_pages(&free);
4752 if (va >= VM_MAXUSER_ADDRESS) {
4753 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4754 if (pmap_insert_pt_page(pmap, mt)) {
4756 * XXX Currently, this can't happen because
4757 * we do not perform pmap_enter(psind == 1)
4758 * on the kernel pmap.
4760 panic("pmap_enter_pde: trie insert failed");
4763 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
4766 if ((newpde & PG_MANAGED) != 0) {
4768 * Abort this mapping if its PV entry could not be created.
4770 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
4772 if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
4774 * Although "va" is not mapped, paging-
4775 * structure caches could nonetheless have
4776 * entries that refer to the freed page table
4777 * pages. Invalidate those entries.
4779 pmap_invalidate_page(pmap, va);
4780 pmap_free_zero_pages(&free);
4782 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4783 " in pmap %p", va, pmap);
4784 return (KERN_RESOURCE_SHORTAGE);
4786 if ((newpde & PG_RW) != 0) {
4787 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
4788 vm_page_aflag_set(mt, PGA_WRITEABLE);
4793 * Increment counters.
4795 if ((newpde & PG_W) != 0)
4796 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
4797 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
4800 * Map the superpage. (This is not a promoted mapping; there will not
4801 * be any lingering 4KB page mappings in the TLB.)
4803 pde_store(pde, newpde);
4805 atomic_add_long(&pmap_pde_mappings, 1);
4806 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
4807 " in pmap %p", va, pmap);
4808 return (KERN_SUCCESS);
4812 * Maps a sequence of resident pages belonging to the same object.
4813 * The sequence begins with the given page m_start. This page is
4814 * mapped at the given virtual address start. Each subsequent page is
4815 * mapped at a virtual address that is offset from start by the same
4816 * amount as the page is offset from m_start within the object. The
4817 * last page in the sequence is the page with the largest offset from
4818 * m_start that can be mapped at a virtual address less than the given
4819 * virtual address end. Not every virtual page between start and end
4820 * is mapped; only those for which a resident page exists with the
4821 * corresponding offset from m_start are mapped.
4824 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
4825 vm_page_t m_start, vm_prot_t prot)
4827 struct rwlock *lock;
4830 vm_pindex_t diff, psize;
4832 VM_OBJECT_ASSERT_LOCKED(m_start->object);
4834 psize = atop(end - start);
4839 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
4840 va = start + ptoa(diff);
4841 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
4842 m->psind == 1 && pmap_ps_enabled(pmap) &&
4843 pmap_enter_2mpage(pmap, va, m, prot, &lock))
4844 m = &m[NBPDR / PAGE_SIZE - 1];
4846 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
4848 m = TAILQ_NEXT(m, listq);
4856 * this code makes some *MAJOR* assumptions:
4857 * 1. Current pmap & pmap exists.
4860 * 4. No page table pages.
4861 * but is *MUCH* faster than pmap_enter...
4865 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
4867 struct rwlock *lock;
4871 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
4878 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
4879 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
4881 struct spglist free;
4882 pt_entry_t *pte, PG_V;
4885 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
4886 (m->oflags & VPO_UNMANAGED) != 0,
4887 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
4888 PG_V = pmap_valid_bit(pmap);
4889 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4892 * In the case that a page table page is not
4893 * resident, we are creating it here.
4895 if (va < VM_MAXUSER_ADDRESS) {
4896 vm_pindex_t ptepindex;
4900 * Calculate pagetable page index
4902 ptepindex = pmap_pde_pindex(va);
4903 if (mpte && (mpte->pindex == ptepindex)) {
4907 * Get the page directory entry
4909 ptepa = pmap_pde(pmap, va);
4912 * If the page table page is mapped, we just increment
4913 * the hold count, and activate it. Otherwise, we
4914 * attempt to allocate a page table page. If this
4915 * attempt fails, we don't retry. Instead, we give up.
4917 if (ptepa && (*ptepa & PG_V) != 0) {
4920 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
4924 * Pass NULL instead of the PV list lock
4925 * pointer, because we don't intend to sleep.
4927 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
4932 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
4933 pte = &pte[pmap_pte_index(va)];
4947 * Enter on the PV list if part of our managed memory.
4949 if ((m->oflags & VPO_UNMANAGED) == 0 &&
4950 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
4953 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
4955 * Although "va" is not mapped, paging-
4956 * structure caches could nonetheless have
4957 * entries that refer to the freed page table
4958 * pages. Invalidate those entries.
4960 pmap_invalidate_page(pmap, va);
4961 pmap_free_zero_pages(&free);
4969 * Increment counters
4971 pmap_resident_count_inc(pmap, 1);
4973 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
4974 if ((prot & VM_PROT_EXECUTE) == 0)
4978 * Now validate mapping with RO protection
4980 if ((m->oflags & VPO_UNMANAGED) != 0)
4981 pte_store(pte, pa | PG_V | PG_U);
4983 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
4988 * Make a temporary mapping for a physical address. This is only intended
4989 * to be used for panic dumps.
4992 pmap_kenter_temporary(vm_paddr_t pa, int i)
4996 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
4997 pmap_kenter(va, pa);
4999 return ((void *)crashdumpmap);
5003 * This code maps large physical mmap regions into the
5004 * processor address space. Note that some shortcuts
5005 * are taken, but the code works.
5008 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
5009 vm_pindex_t pindex, vm_size_t size)
5012 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5013 vm_paddr_t pa, ptepa;
5017 PG_A = pmap_accessed_bit(pmap);
5018 PG_M = pmap_modified_bit(pmap);
5019 PG_V = pmap_valid_bit(pmap);
5020 PG_RW = pmap_rw_bit(pmap);
5022 VM_OBJECT_ASSERT_WLOCKED(object);
5023 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
5024 ("pmap_object_init_pt: non-device object"));
5025 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
5026 if (!pmap_ps_enabled(pmap))
5028 if (!vm_object_populate(object, pindex, pindex + atop(size)))
5030 p = vm_page_lookup(object, pindex);
5031 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5032 ("pmap_object_init_pt: invalid page %p", p));
5033 pat_mode = p->md.pat_mode;
5036 * Abort the mapping if the first page is not physically
5037 * aligned to a 2MB page boundary.
5039 ptepa = VM_PAGE_TO_PHYS(p);
5040 if (ptepa & (NBPDR - 1))
5044 * Skip the first page. Abort the mapping if the rest of
5045 * the pages are not physically contiguous or have differing
5046 * memory attributes.
5048 p = TAILQ_NEXT(p, listq);
5049 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
5051 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5052 ("pmap_object_init_pt: invalid page %p", p));
5053 if (pa != VM_PAGE_TO_PHYS(p) ||
5054 pat_mode != p->md.pat_mode)
5056 p = TAILQ_NEXT(p, listq);
5060 * Map using 2MB pages. Since "ptepa" is 2M aligned and
5061 * "size" is a multiple of 2M, adding the PAT setting to "pa"
5062 * will not affect the termination of this loop.
5065 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
5066 pa < ptepa + size; pa += NBPDR) {
5067 pdpg = pmap_allocpde(pmap, addr, NULL);
5070 * The creation of mappings below is only an
5071 * optimization. If a page directory page
5072 * cannot be allocated without blocking,
5073 * continue on to the next mapping rather than
5079 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5080 pde = &pde[pmap_pde_index(addr)];
5081 if ((*pde & PG_V) == 0) {
5082 pde_store(pde, pa | PG_PS | PG_M | PG_A |
5083 PG_U | PG_RW | PG_V);
5084 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5085 atomic_add_long(&pmap_pde_mappings, 1);
5087 /* Continue on if the PDE is already valid. */
5089 KASSERT(pdpg->wire_count > 0,
5090 ("pmap_object_init_pt: missing reference "
5091 "to page directory page, va: 0x%lx", addr));
5100 * Clear the wired attribute from the mappings for the specified range of
5101 * addresses in the given pmap. Every valid mapping within that range
5102 * must have the wired attribute set. In contrast, invalid mappings
5103 * cannot have the wired attribute set, so they are ignored.
5105 * The wired attribute of the page table entry is not a hardware
5106 * feature, so there is no need to invalidate any TLB entries.
5107 * Since pmap_demote_pde() for the wired entry must never fail,
5108 * pmap_delayed_invl_started()/finished() calls around the
5109 * function are not needed.
5112 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5114 vm_offset_t va_next;
5115 pml4_entry_t *pml4e;
5118 pt_entry_t *pte, PG_V;
5120 PG_V = pmap_valid_bit(pmap);
5122 for (; sva < eva; sva = va_next) {
5123 pml4e = pmap_pml4e(pmap, sva);
5124 if ((*pml4e & PG_V) == 0) {
5125 va_next = (sva + NBPML4) & ~PML4MASK;
5130 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5131 if ((*pdpe & PG_V) == 0) {
5132 va_next = (sva + NBPDP) & ~PDPMASK;
5137 va_next = (sva + NBPDR) & ~PDRMASK;
5140 pde = pmap_pdpe_to_pde(pdpe, sva);
5141 if ((*pde & PG_V) == 0)
5143 if ((*pde & PG_PS) != 0) {
5144 if ((*pde & PG_W) == 0)
5145 panic("pmap_unwire: pde %#jx is missing PG_W",
5149 * Are we unwiring the entire large page? If not,
5150 * demote the mapping and fall through.
5152 if (sva + NBPDR == va_next && eva >= va_next) {
5153 atomic_clear_long(pde, PG_W);
5154 pmap->pm_stats.wired_count -= NBPDR /
5157 } else if (!pmap_demote_pde(pmap, pde, sva))
5158 panic("pmap_unwire: demotion failed");
5162 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
5164 if ((*pte & PG_V) == 0)
5166 if ((*pte & PG_W) == 0)
5167 panic("pmap_unwire: pte %#jx is missing PG_W",
5171 * PG_W must be cleared atomically. Although the pmap
5172 * lock synchronizes access to PG_W, another processor
5173 * could be setting PG_M and/or PG_A concurrently.
5175 atomic_clear_long(pte, PG_W);
5176 pmap->pm_stats.wired_count--;
5183 * Copy the range specified by src_addr/len
5184 * from the source map to the range dst_addr/len
5185 * in the destination map.
5187 * This routine is only advisory and need not do anything.
5191 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5192 vm_offset_t src_addr)
5194 struct rwlock *lock;
5195 struct spglist free;
5197 vm_offset_t end_addr = src_addr + len;
5198 vm_offset_t va_next;
5199 vm_page_t dst_pdpg, dstmpte, srcmpte;
5200 pt_entry_t PG_A, PG_M, PG_V;
5202 if (dst_addr != src_addr)
5205 if (dst_pmap->pm_type != src_pmap->pm_type)
5209 * EPT page table entries that require emulation of A/D bits are
5210 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5211 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5212 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5213 * implementations flag an EPT misconfiguration for exec-only
5214 * mappings we skip this function entirely for emulated pmaps.
5216 if (pmap_emulate_ad_bits(dst_pmap))
5220 if (dst_pmap < src_pmap) {
5221 PMAP_LOCK(dst_pmap);
5222 PMAP_LOCK(src_pmap);
5224 PMAP_LOCK(src_pmap);
5225 PMAP_LOCK(dst_pmap);
5228 PG_A = pmap_accessed_bit(dst_pmap);
5229 PG_M = pmap_modified_bit(dst_pmap);
5230 PG_V = pmap_valid_bit(dst_pmap);
5232 for (addr = src_addr; addr < end_addr; addr = va_next) {
5233 pt_entry_t *src_pte, *dst_pte;
5234 pml4_entry_t *pml4e;
5236 pd_entry_t srcptepaddr, *pde;
5238 KASSERT(addr < UPT_MIN_ADDRESS,
5239 ("pmap_copy: invalid to pmap_copy page tables"));
5241 pml4e = pmap_pml4e(src_pmap, addr);
5242 if ((*pml4e & PG_V) == 0) {
5243 va_next = (addr + NBPML4) & ~PML4MASK;
5249 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5250 if ((*pdpe & PG_V) == 0) {
5251 va_next = (addr + NBPDP) & ~PDPMASK;
5257 va_next = (addr + NBPDR) & ~PDRMASK;
5261 pde = pmap_pdpe_to_pde(pdpe, addr);
5263 if (srcptepaddr == 0)
5266 if (srcptepaddr & PG_PS) {
5267 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5269 dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
5270 if (dst_pdpg == NULL)
5272 pde = (pd_entry_t *)
5273 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
5274 pde = &pde[pmap_pde_index(addr)];
5275 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5276 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
5277 PMAP_ENTER_NORECLAIM, &lock))) {
5278 *pde = srcptepaddr & ~PG_W;
5279 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5280 atomic_add_long(&pmap_pde_mappings, 1);
5282 dst_pdpg->wire_count--;
5286 srcptepaddr &= PG_FRAME;
5287 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5288 KASSERT(srcmpte->wire_count > 0,
5289 ("pmap_copy: source page table page is unused"));
5291 if (va_next > end_addr)
5294 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5295 src_pte = &src_pte[pmap_pte_index(addr)];
5297 while (addr < va_next) {
5301 * we only virtual copy managed pages
5303 if ((ptetemp & PG_MANAGED) != 0) {
5304 if (dstmpte != NULL &&
5305 dstmpte->pindex == pmap_pde_pindex(addr))
5306 dstmpte->wire_count++;
5307 else if ((dstmpte = pmap_allocpte(dst_pmap,
5308 addr, NULL)) == NULL)
5310 dst_pte = (pt_entry_t *)
5311 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5312 dst_pte = &dst_pte[pmap_pte_index(addr)];
5313 if (*dst_pte == 0 &&
5314 pmap_try_insert_pv_entry(dst_pmap, addr,
5315 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5318 * Clear the wired, modified, and
5319 * accessed (referenced) bits
5322 *dst_pte = ptetemp & ~(PG_W | PG_M |
5324 pmap_resident_count_inc(dst_pmap, 1);
5327 if (pmap_unwire_ptp(dst_pmap, addr,
5330 * Although "addr" is not
5331 * mapped, paging-structure
5332 * caches could nonetheless
5333 * have entries that refer to
5334 * the freed page table pages.
5335 * Invalidate those entries.
5337 pmap_invalidate_page(dst_pmap,
5339 pmap_free_zero_pages(&free);
5343 if (dstmpte->wire_count >= srcmpte->wire_count)
5353 PMAP_UNLOCK(src_pmap);
5354 PMAP_UNLOCK(dst_pmap);
5358 * Zero the specified hardware page.
5361 pmap_zero_page(vm_page_t m)
5363 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5365 pagezero((void *)va);
5369 * Zero an an area within a single hardware page. off and size must not
5370 * cover an area beyond a single hardware page.
5373 pmap_zero_page_area(vm_page_t m, int off, int size)
5375 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5377 if (off == 0 && size == PAGE_SIZE)
5378 pagezero((void *)va);
5380 bzero((char *)va + off, size);
5384 * Copy 1 specified hardware page to another.
5387 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5389 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5390 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5392 pagecopy((void *)src, (void *)dst);
5395 int unmapped_buf_allowed = 1;
5398 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5399 vm_offset_t b_offset, int xfersize)
5403 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5407 while (xfersize > 0) {
5408 a_pg_offset = a_offset & PAGE_MASK;
5409 pages[0] = ma[a_offset >> PAGE_SHIFT];
5410 b_pg_offset = b_offset & PAGE_MASK;
5411 pages[1] = mb[b_offset >> PAGE_SHIFT];
5412 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5413 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5414 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5415 a_cp = (char *)vaddr[0] + a_pg_offset;
5416 b_cp = (char *)vaddr[1] + b_pg_offset;
5417 bcopy(a_cp, b_cp, cnt);
5418 if (__predict_false(mapped))
5419 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5427 * Returns true if the pmap's pv is one of the first
5428 * 16 pvs linked to from this page. This count may
5429 * be changed upwards or downwards in the future; it
5430 * is only necessary that true be returned for a small
5431 * subset of pmaps for proper page aging.
5434 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5436 struct md_page *pvh;
5437 struct rwlock *lock;
5442 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5443 ("pmap_page_exists_quick: page %p is not managed", m));
5445 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5447 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5448 if (PV_PMAP(pv) == pmap) {
5456 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5457 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5458 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5459 if (PV_PMAP(pv) == pmap) {
5473 * pmap_page_wired_mappings:
5475 * Return the number of managed mappings to the given physical page
5479 pmap_page_wired_mappings(vm_page_t m)
5481 struct rwlock *lock;
5482 struct md_page *pvh;
5486 int count, md_gen, pvh_gen;
5488 if ((m->oflags & VPO_UNMANAGED) != 0)
5490 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5494 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5496 if (!PMAP_TRYLOCK(pmap)) {
5497 md_gen = m->md.pv_gen;
5501 if (md_gen != m->md.pv_gen) {
5506 pte = pmap_pte(pmap, pv->pv_va);
5507 if ((*pte & PG_W) != 0)
5511 if ((m->flags & PG_FICTITIOUS) == 0) {
5512 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5513 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5515 if (!PMAP_TRYLOCK(pmap)) {
5516 md_gen = m->md.pv_gen;
5517 pvh_gen = pvh->pv_gen;
5521 if (md_gen != m->md.pv_gen ||
5522 pvh_gen != pvh->pv_gen) {
5527 pte = pmap_pde(pmap, pv->pv_va);
5528 if ((*pte & PG_W) != 0)
5538 * Returns TRUE if the given page is mapped individually or as part of
5539 * a 2mpage. Otherwise, returns FALSE.
5542 pmap_page_is_mapped(vm_page_t m)
5544 struct rwlock *lock;
5547 if ((m->oflags & VPO_UNMANAGED) != 0)
5549 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5551 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5552 ((m->flags & PG_FICTITIOUS) == 0 &&
5553 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5559 * Destroy all managed, non-wired mappings in the given user-space
5560 * pmap. This pmap cannot be active on any processor besides the
5563 * This function cannot be applied to the kernel pmap. Moreover, it
5564 * is not intended for general use. It is only to be used during
5565 * process termination. Consequently, it can be implemented in ways
5566 * that make it faster than pmap_remove(). First, it can more quickly
5567 * destroy mappings by iterating over the pmap's collection of PV
5568 * entries, rather than searching the page table. Second, it doesn't
5569 * have to test and clear the page table entries atomically, because
5570 * no processor is currently accessing the user address space. In
5571 * particular, a page table entry's dirty bit won't change state once
5572 * this function starts.
5574 * Although this function destroys all of the pmap's managed,
5575 * non-wired mappings, it can delay and batch the invalidation of TLB
5576 * entries without calling pmap_delayed_invl_started() and
5577 * pmap_delayed_invl_finished(). Because the pmap is not active on
5578 * any other processor, none of these TLB entries will ever be used
5579 * before their eventual invalidation. Consequently, there is no need
5580 * for either pmap_remove_all() or pmap_remove_write() to wait for
5581 * that eventual TLB invalidation.
5584 pmap_remove_pages(pmap_t pmap)
5587 pt_entry_t *pte, tpte;
5588 pt_entry_t PG_M, PG_RW, PG_V;
5589 struct spglist free;
5590 vm_page_t m, mpte, mt;
5592 struct md_page *pvh;
5593 struct pv_chunk *pc, *npc;
5594 struct rwlock *lock;
5596 uint64_t inuse, bitmask;
5597 int allfree, field, freed, idx;
5598 boolean_t superpage;
5602 * Assert that the given pmap is only active on the current
5603 * CPU. Unfortunately, we cannot block another CPU from
5604 * activating the pmap while this function is executing.
5606 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5609 cpuset_t other_cpus;
5611 other_cpus = all_cpus;
5613 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5614 CPU_AND(&other_cpus, &pmap->pm_active);
5616 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5621 PG_M = pmap_modified_bit(pmap);
5622 PG_V = pmap_valid_bit(pmap);
5623 PG_RW = pmap_rw_bit(pmap);
5627 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5630 for (field = 0; field < _NPCM; field++) {
5631 inuse = ~pc->pc_map[field] & pc_freemask[field];
5632 while (inuse != 0) {
5634 bitmask = 1UL << bit;
5635 idx = field * 64 + bit;
5636 pv = &pc->pc_pventry[idx];
5639 pte = pmap_pdpe(pmap, pv->pv_va);
5641 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5643 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5646 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5648 pte = &pte[pmap_pte_index(pv->pv_va)];
5652 * Keep track whether 'tpte' is a
5653 * superpage explicitly instead of
5654 * relying on PG_PS being set.
5656 * This is because PG_PS is numerically
5657 * identical to PG_PTE_PAT and thus a
5658 * regular page could be mistaken for
5664 if ((tpte & PG_V) == 0) {
5665 panic("bad pte va %lx pte %lx",
5670 * We cannot remove wired pages from a process' mapping at this time
5678 pa = tpte & PG_PS_FRAME;
5680 pa = tpte & PG_FRAME;
5682 m = PHYS_TO_VM_PAGE(pa);
5683 KASSERT(m->phys_addr == pa,
5684 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5685 m, (uintmax_t)m->phys_addr,
5688 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5689 m < &vm_page_array[vm_page_array_size],
5690 ("pmap_remove_pages: bad tpte %#jx",
5696 * Update the vm_page_t clean/reference bits.
5698 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5700 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5706 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5709 pc->pc_map[field] |= bitmask;
5711 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
5712 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
5713 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5715 if (TAILQ_EMPTY(&pvh->pv_list)) {
5716 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5717 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
5718 TAILQ_EMPTY(&mt->md.pv_list))
5719 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5721 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
5723 pmap_resident_count_dec(pmap, 1);
5724 KASSERT(mpte->wire_count == NPTEPG,
5725 ("pmap_remove_pages: pte page wire count error"));
5726 mpte->wire_count = 0;
5727 pmap_add_delayed_free_list(mpte, &free, FALSE);
5730 pmap_resident_count_dec(pmap, 1);
5731 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5733 if ((m->aflags & PGA_WRITEABLE) != 0 &&
5734 TAILQ_EMPTY(&m->md.pv_list) &&
5735 (m->flags & PG_FICTITIOUS) == 0) {
5736 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5737 if (TAILQ_EMPTY(&pvh->pv_list))
5738 vm_page_aflag_clear(m, PGA_WRITEABLE);
5741 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
5745 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5746 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5747 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5749 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5755 pmap_invalidate_all(pmap);
5757 pmap_free_zero_pages(&free);
5761 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
5763 struct rwlock *lock;
5765 struct md_page *pvh;
5766 pt_entry_t *pte, mask;
5767 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5769 int md_gen, pvh_gen;
5773 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5776 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5778 if (!PMAP_TRYLOCK(pmap)) {
5779 md_gen = m->md.pv_gen;
5783 if (md_gen != m->md.pv_gen) {
5788 pte = pmap_pte(pmap, pv->pv_va);
5791 PG_M = pmap_modified_bit(pmap);
5792 PG_RW = pmap_rw_bit(pmap);
5793 mask |= PG_RW | PG_M;
5796 PG_A = pmap_accessed_bit(pmap);
5797 PG_V = pmap_valid_bit(pmap);
5798 mask |= PG_V | PG_A;
5800 rv = (*pte & mask) == mask;
5805 if ((m->flags & PG_FICTITIOUS) == 0) {
5806 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5807 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5809 if (!PMAP_TRYLOCK(pmap)) {
5810 md_gen = m->md.pv_gen;
5811 pvh_gen = pvh->pv_gen;
5815 if (md_gen != m->md.pv_gen ||
5816 pvh_gen != pvh->pv_gen) {
5821 pte = pmap_pde(pmap, pv->pv_va);
5824 PG_M = pmap_modified_bit(pmap);
5825 PG_RW = pmap_rw_bit(pmap);
5826 mask |= PG_RW | PG_M;
5829 PG_A = pmap_accessed_bit(pmap);
5830 PG_V = pmap_valid_bit(pmap);
5831 mask |= PG_V | PG_A;
5833 rv = (*pte & mask) == mask;
5847 * Return whether or not the specified physical page was modified
5848 * in any physical maps.
5851 pmap_is_modified(vm_page_t m)
5854 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5855 ("pmap_is_modified: page %p is not managed", m));
5858 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5859 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
5860 * is clear, no PTEs can have PG_M set.
5862 VM_OBJECT_ASSERT_WLOCKED(m->object);
5863 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
5865 return (pmap_page_test_mappings(m, FALSE, TRUE));
5869 * pmap_is_prefaultable:
5871 * Return whether or not the specified virtual address is eligible
5875 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
5878 pt_entry_t *pte, PG_V;
5881 PG_V = pmap_valid_bit(pmap);
5884 pde = pmap_pde(pmap, addr);
5885 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
5886 pte = pmap_pde_to_pte(pde, addr);
5887 rv = (*pte & PG_V) == 0;
5894 * pmap_is_referenced:
5896 * Return whether or not the specified physical page was referenced
5897 * in any physical maps.
5900 pmap_is_referenced(vm_page_t m)
5903 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5904 ("pmap_is_referenced: page %p is not managed", m));
5905 return (pmap_page_test_mappings(m, TRUE, FALSE));
5909 * Clear the write and modified bits in each of the given page's mappings.
5912 pmap_remove_write(vm_page_t m)
5914 struct md_page *pvh;
5916 struct rwlock *lock;
5917 pv_entry_t next_pv, pv;
5919 pt_entry_t oldpte, *pte, PG_M, PG_RW;
5921 int pvh_gen, md_gen;
5923 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5924 ("pmap_remove_write: page %p is not managed", m));
5927 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5928 * set by another thread while the object is locked. Thus,
5929 * if PGA_WRITEABLE is clear, no page table entries need updating.
5931 VM_OBJECT_ASSERT_WLOCKED(m->object);
5932 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
5934 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5935 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
5936 pa_to_pvh(VM_PAGE_TO_PHYS(m));
5939 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
5941 if (!PMAP_TRYLOCK(pmap)) {
5942 pvh_gen = pvh->pv_gen;
5946 if (pvh_gen != pvh->pv_gen) {
5952 PG_RW = pmap_rw_bit(pmap);
5954 pde = pmap_pde(pmap, va);
5955 if ((*pde & PG_RW) != 0)
5956 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
5957 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
5958 ("inconsistent pv lock %p %p for page %p",
5959 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
5962 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5964 if (!PMAP_TRYLOCK(pmap)) {
5965 pvh_gen = pvh->pv_gen;
5966 md_gen = m->md.pv_gen;
5970 if (pvh_gen != pvh->pv_gen ||
5971 md_gen != m->md.pv_gen) {
5977 PG_M = pmap_modified_bit(pmap);
5978 PG_RW = pmap_rw_bit(pmap);
5979 pde = pmap_pde(pmap, pv->pv_va);
5980 KASSERT((*pde & PG_PS) == 0,
5981 ("pmap_remove_write: found a 2mpage in page %p's pv list",
5983 pte = pmap_pde_to_pte(pde, pv->pv_va);
5986 if (oldpte & PG_RW) {
5987 if (!atomic_cmpset_long(pte, oldpte, oldpte &
5990 if ((oldpte & PG_M) != 0)
5992 pmap_invalidate_page(pmap, pv->pv_va);
5997 vm_page_aflag_clear(m, PGA_WRITEABLE);
5998 pmap_delayed_invl_wait(m);
6001 static __inline boolean_t
6002 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
6005 if (!pmap_emulate_ad_bits(pmap))
6008 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
6011 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
6012 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
6013 * if the EPT_PG_WRITE bit is set.
6015 if ((pte & EPT_PG_WRITE) != 0)
6019 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
6021 if ((pte & EPT_PG_EXECUTE) == 0 ||
6022 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
6029 * pmap_ts_referenced:
6031 * Return a count of reference bits for a page, clearing those bits.
6032 * It is not necessary for every reference bit to be cleared, but it
6033 * is necessary that 0 only be returned when there are truly no
6034 * reference bits set.
6036 * As an optimization, update the page's dirty field if a modified bit is
6037 * found while counting reference bits. This opportunistic update can be
6038 * performed at low cost and can eliminate the need for some future calls
6039 * to pmap_is_modified(). However, since this function stops after
6040 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
6041 * dirty pages. Those dirty pages will only be detected by a future call
6042 * to pmap_is_modified().
6044 * A DI block is not needed within this function, because
6045 * invalidations are performed before the PV list lock is
6049 pmap_ts_referenced(vm_page_t m)
6051 struct md_page *pvh;
6054 struct rwlock *lock;
6055 pd_entry_t oldpde, *pde;
6056 pt_entry_t *pte, PG_A, PG_M, PG_RW;
6059 int cleared, md_gen, not_cleared, pvh_gen;
6060 struct spglist free;
6063 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6064 ("pmap_ts_referenced: page %p is not managed", m));
6067 pa = VM_PAGE_TO_PHYS(m);
6068 lock = PHYS_TO_PV_LIST_LOCK(pa);
6069 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
6073 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6074 goto small_mappings;
6080 if (!PMAP_TRYLOCK(pmap)) {
6081 pvh_gen = pvh->pv_gen;
6085 if (pvh_gen != pvh->pv_gen) {
6090 PG_A = pmap_accessed_bit(pmap);
6091 PG_M = pmap_modified_bit(pmap);
6092 PG_RW = pmap_rw_bit(pmap);
6094 pde = pmap_pde(pmap, pv->pv_va);
6096 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6098 * Although "oldpde" is mapping a 2MB page, because
6099 * this function is called at a 4KB page granularity,
6100 * we only update the 4KB page under test.
6104 if ((oldpde & PG_A) != 0) {
6106 * Since this reference bit is shared by 512 4KB
6107 * pages, it should not be cleared every time it is
6108 * tested. Apply a simple "hash" function on the
6109 * physical page number, the virtual superpage number,
6110 * and the pmap address to select one 4KB page out of
6111 * the 512 on which testing the reference bit will
6112 * result in clearing that reference bit. This
6113 * function is designed to avoid the selection of the
6114 * same 4KB page for every 2MB page mapping.
6116 * On demotion, a mapping that hasn't been referenced
6117 * is simply destroyed. To avoid the possibility of a
6118 * subsequent page fault on a demoted wired mapping,
6119 * always leave its reference bit set. Moreover,
6120 * since the superpage is wired, the current state of
6121 * its reference bit won't affect page replacement.
6123 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
6124 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
6125 (oldpde & PG_W) == 0) {
6126 if (safe_to_clear_referenced(pmap, oldpde)) {
6127 atomic_clear_long(pde, PG_A);
6128 pmap_invalidate_page(pmap, pv->pv_va);
6130 } else if (pmap_demote_pde_locked(pmap, pde,
6131 pv->pv_va, &lock)) {
6133 * Remove the mapping to a single page
6134 * so that a subsequent access may
6135 * repromote. Since the underlying
6136 * page table page is fully populated,
6137 * this removal never frees a page
6141 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6143 pte = pmap_pde_to_pte(pde, va);
6144 pmap_remove_pte(pmap, pte, va, *pde,
6146 pmap_invalidate_page(pmap, va);
6152 * The superpage mapping was removed
6153 * entirely and therefore 'pv' is no
6161 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6162 ("inconsistent pv lock %p %p for page %p",
6163 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6168 /* Rotate the PV list if it has more than one entry. */
6169 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6170 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6171 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6174 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6176 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6178 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6185 if (!PMAP_TRYLOCK(pmap)) {
6186 pvh_gen = pvh->pv_gen;
6187 md_gen = m->md.pv_gen;
6191 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6196 PG_A = pmap_accessed_bit(pmap);
6197 PG_M = pmap_modified_bit(pmap);
6198 PG_RW = pmap_rw_bit(pmap);
6199 pde = pmap_pde(pmap, pv->pv_va);
6200 KASSERT((*pde & PG_PS) == 0,
6201 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6203 pte = pmap_pde_to_pte(pde, pv->pv_va);
6204 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6206 if ((*pte & PG_A) != 0) {
6207 if (safe_to_clear_referenced(pmap, *pte)) {
6208 atomic_clear_long(pte, PG_A);
6209 pmap_invalidate_page(pmap, pv->pv_va);
6211 } else if ((*pte & PG_W) == 0) {
6213 * Wired pages cannot be paged out so
6214 * doing accessed bit emulation for
6215 * them is wasted effort. We do the
6216 * hard work for unwired pages only.
6218 pmap_remove_pte(pmap, pte, pv->pv_va,
6219 *pde, &free, &lock);
6220 pmap_invalidate_page(pmap, pv->pv_va);
6225 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6226 ("inconsistent pv lock %p %p for page %p",
6227 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6232 /* Rotate the PV list if it has more than one entry. */
6233 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6234 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6235 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6238 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6239 not_cleared < PMAP_TS_REFERENCED_MAX);
6242 pmap_free_zero_pages(&free);
6243 return (cleared + not_cleared);
6247 * Apply the given advice to the specified range of addresses within the
6248 * given pmap. Depending on the advice, clear the referenced and/or
6249 * modified flags in each mapping and set the mapped page's dirty field.
6252 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6254 struct rwlock *lock;
6255 pml4_entry_t *pml4e;
6257 pd_entry_t oldpde, *pde;
6258 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6259 vm_offset_t va, va_next;
6261 boolean_t anychanged;
6263 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6267 * A/D bit emulation requires an alternate code path when clearing
6268 * the modified and accessed bits below. Since this function is
6269 * advisory in nature we skip it entirely for pmaps that require
6270 * A/D bit emulation.
6272 if (pmap_emulate_ad_bits(pmap))
6275 PG_A = pmap_accessed_bit(pmap);
6276 PG_G = pmap_global_bit(pmap);
6277 PG_M = pmap_modified_bit(pmap);
6278 PG_V = pmap_valid_bit(pmap);
6279 PG_RW = pmap_rw_bit(pmap);
6281 pmap_delayed_invl_started();
6283 for (; sva < eva; sva = va_next) {
6284 pml4e = pmap_pml4e(pmap, sva);
6285 if ((*pml4e & PG_V) == 0) {
6286 va_next = (sva + NBPML4) & ~PML4MASK;
6291 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6292 if ((*pdpe & PG_V) == 0) {
6293 va_next = (sva + NBPDP) & ~PDPMASK;
6298 va_next = (sva + NBPDR) & ~PDRMASK;
6301 pde = pmap_pdpe_to_pde(pdpe, sva);
6303 if ((oldpde & PG_V) == 0)
6305 else if ((oldpde & PG_PS) != 0) {
6306 if ((oldpde & PG_MANAGED) == 0)
6309 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6314 * The large page mapping was destroyed.
6320 * Unless the page mappings are wired, remove the
6321 * mapping to a single page so that a subsequent
6322 * access may repromote. Since the underlying page
6323 * table page is fully populated, this removal never
6324 * frees a page table page.
6326 if ((oldpde & PG_W) == 0) {
6327 pte = pmap_pde_to_pte(pde, sva);
6328 KASSERT((*pte & PG_V) != 0,
6329 ("pmap_advise: invalid PTE"));
6330 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6340 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6342 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6344 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6345 if (advice == MADV_DONTNEED) {
6347 * Future calls to pmap_is_modified()
6348 * can be avoided by making the page
6351 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6354 atomic_clear_long(pte, PG_M | PG_A);
6355 } else if ((*pte & PG_A) != 0)
6356 atomic_clear_long(pte, PG_A);
6360 if ((*pte & PG_G) != 0) {
6367 if (va != va_next) {
6368 pmap_invalidate_range(pmap, va, sva);
6373 pmap_invalidate_range(pmap, va, sva);
6376 pmap_invalidate_all(pmap);
6378 pmap_delayed_invl_finished();
6382 * Clear the modify bits on the specified physical page.
6385 pmap_clear_modify(vm_page_t m)
6387 struct md_page *pvh;
6389 pv_entry_t next_pv, pv;
6390 pd_entry_t oldpde, *pde;
6391 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6392 struct rwlock *lock;
6394 int md_gen, pvh_gen;
6396 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6397 ("pmap_clear_modify: page %p is not managed", m));
6398 VM_OBJECT_ASSERT_WLOCKED(m->object);
6399 KASSERT(!vm_page_xbusied(m),
6400 ("pmap_clear_modify: page %p is exclusive busied", m));
6403 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6404 * If the object containing the page is locked and the page is not
6405 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6407 if ((m->aflags & PGA_WRITEABLE) == 0)
6409 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6410 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6411 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6414 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6416 if (!PMAP_TRYLOCK(pmap)) {
6417 pvh_gen = pvh->pv_gen;
6421 if (pvh_gen != pvh->pv_gen) {
6426 PG_M = pmap_modified_bit(pmap);
6427 PG_V = pmap_valid_bit(pmap);
6428 PG_RW = pmap_rw_bit(pmap);
6430 pde = pmap_pde(pmap, va);
6432 if ((oldpde & PG_RW) != 0) {
6433 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6434 if ((oldpde & PG_W) == 0) {
6436 * Write protect the mapping to a
6437 * single page so that a subsequent
6438 * write access may repromote.
6440 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6442 pte = pmap_pde_to_pte(pde, va);
6444 if ((oldpte & PG_V) != 0) {
6445 while (!atomic_cmpset_long(pte,
6447 oldpte & ~(PG_M | PG_RW)))
6450 pmap_invalidate_page(pmap, va);
6457 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6459 if (!PMAP_TRYLOCK(pmap)) {
6460 md_gen = m->md.pv_gen;
6461 pvh_gen = pvh->pv_gen;
6465 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6470 PG_M = pmap_modified_bit(pmap);
6471 PG_RW = pmap_rw_bit(pmap);
6472 pde = pmap_pde(pmap, pv->pv_va);
6473 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6474 " a 2mpage in page %p's pv list", m));
6475 pte = pmap_pde_to_pte(pde, pv->pv_va);
6476 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6477 atomic_clear_long(pte, PG_M);
6478 pmap_invalidate_page(pmap, pv->pv_va);
6486 * Miscellaneous support routines follow
6489 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6490 static __inline void
6491 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6496 * The cache mode bits are all in the low 32-bits of the
6497 * PTE, so we can just spin on updating the low 32-bits.
6500 opte = *(u_int *)pte;
6501 npte = opte & ~mask;
6503 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6506 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6507 static __inline void
6508 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6513 * The cache mode bits are all in the low 32-bits of the
6514 * PDE, so we can just spin on updating the low 32-bits.
6517 opde = *(u_int *)pde;
6518 npde = opde & ~mask;
6520 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6524 * Map a set of physical memory pages into the kernel virtual
6525 * address space. Return a pointer to where it is mapped. This
6526 * routine is intended to be used for mapping device memory,
6530 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6532 struct pmap_preinit_mapping *ppim;
6533 vm_offset_t va, offset;
6537 offset = pa & PAGE_MASK;
6538 size = round_page(offset + size);
6539 pa = trunc_page(pa);
6541 if (!pmap_initialized) {
6543 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6544 ppim = pmap_preinit_mapping + i;
6545 if (ppim->va == 0) {
6549 ppim->va = virtual_avail;
6550 virtual_avail += size;
6556 panic("%s: too many preinit mappings", __func__);
6559 * If we have a preinit mapping, re-use it.
6561 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6562 ppim = pmap_preinit_mapping + i;
6563 if (ppim->pa == pa && ppim->sz == size &&
6565 return ((void *)(ppim->va + offset));
6568 * If the specified range of physical addresses fits within
6569 * the direct map window, use the direct map.
6571 if (pa < dmaplimit && pa + size < dmaplimit) {
6572 va = PHYS_TO_DMAP(pa);
6573 if (!pmap_change_attr(va, size, mode))
6574 return ((void *)(va + offset));
6576 va = kva_alloc(size);
6578 panic("%s: Couldn't allocate KVA", __func__);
6580 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6581 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6582 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6583 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6584 return ((void *)(va + offset));
6588 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6591 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6595 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6598 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6602 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6604 struct pmap_preinit_mapping *ppim;
6608 /* If we gave a direct map region in pmap_mapdev, do nothing */
6609 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6611 offset = va & PAGE_MASK;
6612 size = round_page(offset + size);
6613 va = trunc_page(va);
6614 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6615 ppim = pmap_preinit_mapping + i;
6616 if (ppim->va == va && ppim->sz == size) {
6617 if (pmap_initialized)
6623 if (va + size == virtual_avail)
6628 if (pmap_initialized)
6633 * Tries to demote a 1GB page mapping.
6636 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6638 pdp_entry_t newpdpe, oldpdpe;
6639 pd_entry_t *firstpde, newpde, *pde;
6640 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6644 PG_A = pmap_accessed_bit(pmap);
6645 PG_M = pmap_modified_bit(pmap);
6646 PG_V = pmap_valid_bit(pmap);
6647 PG_RW = pmap_rw_bit(pmap);
6649 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6651 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6652 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6653 if ((pdpg = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6654 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6655 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6656 " in pmap %p", va, pmap);
6659 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
6660 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
6661 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6662 KASSERT((oldpdpe & PG_A) != 0,
6663 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6664 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6665 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
6669 * Initialize the page directory page.
6671 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
6677 * Demote the mapping.
6682 * Invalidate a stale recursive mapping of the page directory page.
6684 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
6686 pmap_pdpe_demotions++;
6687 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
6688 " in pmap %p", va, pmap);
6693 * Sets the memory attribute for the specified page.
6696 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6699 m->md.pat_mode = ma;
6702 * If "m" is a normal page, update its direct mapping. This update
6703 * can be relied upon to perform any cache operations that are
6704 * required for data coherence.
6706 if ((m->flags & PG_FICTITIOUS) == 0 &&
6707 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6709 panic("memory attribute change on the direct map failed");
6713 * Changes the specified virtual address range's memory type to that given by
6714 * the parameter "mode". The specified virtual address range must be
6715 * completely contained within either the direct map or the kernel map. If
6716 * the virtual address range is contained within the kernel map, then the
6717 * memory type for each of the corresponding ranges of the direct map is also
6718 * changed. (The corresponding ranges of the direct map are those ranges that
6719 * map the same physical pages as the specified virtual address range.) These
6720 * changes to the direct map are necessary because Intel describes the
6721 * behavior of their processors as "undefined" if two or more mappings to the
6722 * same physical page have different memory types.
6724 * Returns zero if the change completed successfully, and either EINVAL or
6725 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6726 * of the virtual address range was not mapped, and ENOMEM is returned if
6727 * there was insufficient memory available to complete the change. In the
6728 * latter case, the memory type may have been changed on some part of the
6729 * virtual address range or the direct map.
6732 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6736 PMAP_LOCK(kernel_pmap);
6737 error = pmap_change_attr_locked(va, size, mode);
6738 PMAP_UNLOCK(kernel_pmap);
6743 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
6745 vm_offset_t base, offset, tmpva;
6746 vm_paddr_t pa_start, pa_end, pa_end1;
6750 int cache_bits_pte, cache_bits_pde, error;
6753 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6754 base = trunc_page(va);
6755 offset = va & PAGE_MASK;
6756 size = round_page(offset + size);
6759 * Only supported on kernel virtual addresses, including the direct
6760 * map but excluding the recursive map.
6762 if (base < DMAP_MIN_ADDRESS)
6765 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
6766 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
6770 * Pages that aren't mapped aren't supported. Also break down 2MB pages
6771 * into 4KB pages if required.
6773 for (tmpva = base; tmpva < base + size; ) {
6774 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6775 if (pdpe == NULL || *pdpe == 0)
6777 if (*pdpe & PG_PS) {
6779 * If the current 1GB page already has the required
6780 * memory type, then we need not demote this page. Just
6781 * increment tmpva to the next 1GB page frame.
6783 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
6784 tmpva = trunc_1gpage(tmpva) + NBPDP;
6789 * If the current offset aligns with a 1GB page frame
6790 * and there is at least 1GB left within the range, then
6791 * we need not break down this page into 2MB pages.
6793 if ((tmpva & PDPMASK) == 0 &&
6794 tmpva + PDPMASK < base + size) {
6798 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
6801 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6806 * If the current 2MB page already has the required
6807 * memory type, then we need not demote this page. Just
6808 * increment tmpva to the next 2MB page frame.
6810 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
6811 tmpva = trunc_2mpage(tmpva) + NBPDR;
6816 * If the current offset aligns with a 2MB page frame
6817 * and there is at least 2MB left within the range, then
6818 * we need not break down this page into 4KB pages.
6820 if ((tmpva & PDRMASK) == 0 &&
6821 tmpva + PDRMASK < base + size) {
6825 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
6828 pte = pmap_pde_to_pte(pde, tmpva);
6836 * Ok, all the pages exist, so run through them updating their
6837 * cache mode if required.
6839 pa_start = pa_end = 0;
6840 for (tmpva = base; tmpva < base + size; ) {
6841 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6842 if (*pdpe & PG_PS) {
6843 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
6844 pmap_pde_attr(pdpe, cache_bits_pde,
6848 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6849 (*pdpe & PG_PS_FRAME) < dmaplimit) {
6850 if (pa_start == pa_end) {
6851 /* Start physical address run. */
6852 pa_start = *pdpe & PG_PS_FRAME;
6853 pa_end = pa_start + NBPDP;
6854 } else if (pa_end == (*pdpe & PG_PS_FRAME))
6857 /* Run ended, update direct map. */
6858 error = pmap_change_attr_locked(
6859 PHYS_TO_DMAP(pa_start),
6860 pa_end - pa_start, mode);
6863 /* Start physical address run. */
6864 pa_start = *pdpe & PG_PS_FRAME;
6865 pa_end = pa_start + NBPDP;
6868 tmpva = trunc_1gpage(tmpva) + NBPDP;
6871 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6873 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
6874 pmap_pde_attr(pde, cache_bits_pde,
6878 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6879 (*pde & PG_PS_FRAME) < dmaplimit) {
6880 if (pa_start == pa_end) {
6881 /* Start physical address run. */
6882 pa_start = *pde & PG_PS_FRAME;
6883 pa_end = pa_start + NBPDR;
6884 } else if (pa_end == (*pde & PG_PS_FRAME))
6887 /* Run ended, update direct map. */
6888 error = pmap_change_attr_locked(
6889 PHYS_TO_DMAP(pa_start),
6890 pa_end - pa_start, mode);
6893 /* Start physical address run. */
6894 pa_start = *pde & PG_PS_FRAME;
6895 pa_end = pa_start + NBPDR;
6898 tmpva = trunc_2mpage(tmpva) + NBPDR;
6900 pte = pmap_pde_to_pte(pde, tmpva);
6901 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
6902 pmap_pte_attr(pte, cache_bits_pte,
6906 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6907 (*pte & PG_FRAME) < dmaplimit) {
6908 if (pa_start == pa_end) {
6909 /* Start physical address run. */
6910 pa_start = *pte & PG_FRAME;
6911 pa_end = pa_start + PAGE_SIZE;
6912 } else if (pa_end == (*pte & PG_FRAME))
6913 pa_end += PAGE_SIZE;
6915 /* Run ended, update direct map. */
6916 error = pmap_change_attr_locked(
6917 PHYS_TO_DMAP(pa_start),
6918 pa_end - pa_start, mode);
6921 /* Start physical address run. */
6922 pa_start = *pte & PG_FRAME;
6923 pa_end = pa_start + PAGE_SIZE;
6929 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
6930 pa_end1 = MIN(pa_end, dmaplimit);
6931 if (pa_start != pa_end1)
6932 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
6933 pa_end1 - pa_start, mode);
6937 * Flush CPU caches if required to make sure any data isn't cached that
6938 * shouldn't be, etc.
6941 pmap_invalidate_range(kernel_pmap, base, tmpva);
6942 pmap_invalidate_cache_range(base, tmpva, FALSE);
6948 * Demotes any mapping within the direct map region that covers more than the
6949 * specified range of physical addresses. This range's size must be a power
6950 * of two and its starting address must be a multiple of its size. Since the
6951 * demotion does not change any attributes of the mapping, a TLB invalidation
6952 * is not mandatory. The caller may, however, request a TLB invalidation.
6955 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
6964 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
6965 KASSERT((base & (len - 1)) == 0,
6966 ("pmap_demote_DMAP: base is not a multiple of len"));
6967 if (len < NBPDP && base < dmaplimit) {
6968 va = PHYS_TO_DMAP(base);
6970 PMAP_LOCK(kernel_pmap);
6971 pdpe = pmap_pdpe(kernel_pmap, va);
6972 if ((*pdpe & X86_PG_V) == 0)
6973 panic("pmap_demote_DMAP: invalid PDPE");
6974 if ((*pdpe & PG_PS) != 0) {
6975 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
6976 panic("pmap_demote_DMAP: PDPE failed");
6980 pde = pmap_pdpe_to_pde(pdpe, va);
6981 if ((*pde & X86_PG_V) == 0)
6982 panic("pmap_demote_DMAP: invalid PDE");
6983 if ((*pde & PG_PS) != 0) {
6984 if (!pmap_demote_pde(kernel_pmap, pde, va))
6985 panic("pmap_demote_DMAP: PDE failed");
6989 if (changed && invalidate)
6990 pmap_invalidate_page(kernel_pmap, va);
6991 PMAP_UNLOCK(kernel_pmap);
6996 * perform the pmap work for mincore
6999 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
7002 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
7006 PG_A = pmap_accessed_bit(pmap);
7007 PG_M = pmap_modified_bit(pmap);
7008 PG_V = pmap_valid_bit(pmap);
7009 PG_RW = pmap_rw_bit(pmap);
7013 pdep = pmap_pde(pmap, addr);
7014 if (pdep != NULL && (*pdep & PG_V)) {
7015 if (*pdep & PG_PS) {
7017 /* Compute the physical address of the 4KB page. */
7018 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
7020 val = MINCORE_SUPER;
7022 pte = *pmap_pde_to_pte(pdep, addr);
7023 pa = pte & PG_FRAME;
7031 if ((pte & PG_V) != 0) {
7032 val |= MINCORE_INCORE;
7033 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7034 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
7035 if ((pte & PG_A) != 0)
7036 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
7038 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
7039 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
7040 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
7041 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
7042 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
7045 PA_UNLOCK_COND(*locked_pa);
7051 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
7053 uint32_t gen, new_gen, pcid_next;
7055 CRITICAL_ASSERT(curthread);
7056 gen = PCPU_GET(pcid_gen);
7057 if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN ||
7058 pmap->pm_pcids[cpuid].pm_gen == gen)
7059 return (CR3_PCID_SAVE);
7060 pcid_next = PCPU_GET(pcid_next);
7061 KASSERT(pcid_next <= PMAP_PCID_OVERMAX, ("cpu %d pcid_next %#x",
7063 if (pcid_next == PMAP_PCID_OVERMAX) {
7067 PCPU_SET(pcid_gen, new_gen);
7068 pcid_next = PMAP_PCID_KERN + 1;
7072 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
7073 pmap->pm_pcids[cpuid].pm_gen = new_gen;
7074 PCPU_SET(pcid_next, pcid_next + 1);
7079 pmap_activate_sw(struct thread *td)
7081 pmap_t oldpmap, pmap;
7082 uint64_t cached, cr3;
7086 oldpmap = PCPU_GET(curpmap);
7087 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7088 if (oldpmap == pmap)
7090 cpuid = PCPU_GET(cpuid);
7092 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7094 CPU_SET(cpuid, &pmap->pm_active);
7097 if (pmap_pcid_enabled) {
7098 cached = pmap_pcid_alloc(pmap, cpuid);
7099 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
7100 pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
7101 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
7102 pmap->pm_pcids[cpuid].pm_pcid));
7103 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
7104 pmap == kernel_pmap,
7105 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
7106 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
7109 * If the INVPCID instruction is not available,
7110 * invltlb_pcid_handler() is used for handle
7111 * invalidate_all IPI, which checks for curpmap ==
7112 * smp_tlb_pmap. Below operations sequence has a
7113 * window where %CR3 is loaded with the new pmap's
7114 * PML4 address, but curpmap value is not yet updated.
7115 * This causes invltlb IPI handler, called between the
7116 * updates, to execute as NOP, which leaves stale TLB
7119 * Note that the most typical use of
7120 * pmap_activate_sw(), from the context switch, is
7121 * immune to this race, because interrupts are
7122 * disabled (while the thread lock is owned), and IPI
7123 * happends after curpmap is updated. Protect other
7124 * callers in a similar way, by disabling interrupts
7125 * around the %cr3 register reload and curpmap
7129 rflags = intr_disable();
7131 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
7132 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
7135 PCPU_INC(pm_save_cnt);
7137 PCPU_SET(curpmap, pmap);
7139 intr_restore(rflags);
7140 } else if (cr3 != pmap->pm_cr3) {
7141 load_cr3(pmap->pm_cr3);
7142 PCPU_SET(curpmap, pmap);
7145 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
7147 CPU_CLR(cpuid, &oldpmap->pm_active);
7152 pmap_activate(struct thread *td)
7156 pmap_activate_sw(td);
7161 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
7166 * Increase the starting virtual address of the given mapping if a
7167 * different alignment might result in more superpage mappings.
7170 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7171 vm_offset_t *addr, vm_size_t size)
7173 vm_offset_t superpage_offset;
7177 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7178 offset += ptoa(object->pg_color);
7179 superpage_offset = offset & PDRMASK;
7180 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
7181 (*addr & PDRMASK) == superpage_offset)
7183 if ((*addr & PDRMASK) < superpage_offset)
7184 *addr = (*addr & ~PDRMASK) + superpage_offset;
7186 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
7190 static unsigned long num_dirty_emulations;
7191 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
7192 &num_dirty_emulations, 0, NULL);
7194 static unsigned long num_accessed_emulations;
7195 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
7196 &num_accessed_emulations, 0, NULL);
7198 static unsigned long num_superpage_accessed_emulations;
7199 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7200 &num_superpage_accessed_emulations, 0, NULL);
7202 static unsigned long ad_emulation_superpage_promotions;
7203 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7204 &ad_emulation_superpage_promotions, 0, NULL);
7205 #endif /* INVARIANTS */
7208 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7211 struct rwlock *lock;
7212 #if VM_NRESERVLEVEL > 0
7216 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7218 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7219 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7221 if (!pmap_emulate_ad_bits(pmap))
7224 PG_A = pmap_accessed_bit(pmap);
7225 PG_M = pmap_modified_bit(pmap);
7226 PG_V = pmap_valid_bit(pmap);
7227 PG_RW = pmap_rw_bit(pmap);
7233 pde = pmap_pde(pmap, va);
7234 if (pde == NULL || (*pde & PG_V) == 0)
7237 if ((*pde & PG_PS) != 0) {
7238 if (ftype == VM_PROT_READ) {
7240 atomic_add_long(&num_superpage_accessed_emulations, 1);
7248 pte = pmap_pde_to_pte(pde, va);
7249 if ((*pte & PG_V) == 0)
7252 if (ftype == VM_PROT_WRITE) {
7253 if ((*pte & PG_RW) == 0)
7256 * Set the modified and accessed bits simultaneously.
7258 * Intel EPT PTEs that do software emulation of A/D bits map
7259 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7260 * An EPT misconfiguration is triggered if the PTE is writable
7261 * but not readable (WR=10). This is avoided by setting PG_A
7262 * and PG_M simultaneously.
7264 *pte |= PG_M | PG_A;
7269 #if VM_NRESERVLEVEL > 0
7270 /* try to promote the mapping */
7271 if (va < VM_MAXUSER_ADDRESS)
7272 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7276 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7278 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7279 pmap_ps_enabled(pmap) &&
7280 (m->flags & PG_FICTITIOUS) == 0 &&
7281 vm_reserv_level_iffullpop(m) == 0) {
7282 pmap_promote_pde(pmap, pde, va, &lock);
7284 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7290 if (ftype == VM_PROT_WRITE)
7291 atomic_add_long(&num_dirty_emulations, 1);
7293 atomic_add_long(&num_accessed_emulations, 1);
7295 rv = 0; /* success */
7304 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7309 pt_entry_t *pte, PG_V;
7313 PG_V = pmap_valid_bit(pmap);
7316 pml4 = pmap_pml4e(pmap, va);
7318 if ((*pml4 & PG_V) == 0)
7321 pdp = pmap_pml4e_to_pdpe(pml4, va);
7323 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7326 pde = pmap_pdpe_to_pde(pdp, va);
7328 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7331 pte = pmap_pde_to_pte(pde, va);
7340 * Get the kernel virtual address of a set of physical pages. If there are
7341 * physical addresses not covered by the DMAP perform a transient mapping
7342 * that will be removed when calling pmap_unmap_io_transient.
7344 * \param page The pages the caller wishes to obtain the virtual
7345 * address on the kernel memory map.
7346 * \param vaddr On return contains the kernel virtual memory address
7347 * of the pages passed in the page parameter.
7348 * \param count Number of pages passed in.
7349 * \param can_fault TRUE if the thread using the mapped pages can take
7350 * page faults, FALSE otherwise.
7352 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7353 * finished or FALSE otherwise.
7357 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7358 boolean_t can_fault)
7361 boolean_t needs_mapping;
7363 int cache_bits, error, i;
7366 * Allocate any KVA space that we need, this is done in a separate
7367 * loop to prevent calling vmem_alloc while pinned.
7369 needs_mapping = FALSE;
7370 for (i = 0; i < count; i++) {
7371 paddr = VM_PAGE_TO_PHYS(page[i]);
7372 if (__predict_false(paddr >= dmaplimit)) {
7373 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7374 M_BESTFIT | M_WAITOK, &vaddr[i]);
7375 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7376 needs_mapping = TRUE;
7378 vaddr[i] = PHYS_TO_DMAP(paddr);
7382 /* Exit early if everything is covered by the DMAP */
7387 * NB: The sequence of updating a page table followed by accesses
7388 * to the corresponding pages used in the !DMAP case is subject to
7389 * the situation described in the "AMD64 Architecture Programmer's
7390 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7391 * Coherency Considerations". Therefore, issuing the INVLPG right
7392 * after modifying the PTE bits is crucial.
7396 for (i = 0; i < count; i++) {
7397 paddr = VM_PAGE_TO_PHYS(page[i]);
7398 if (paddr >= dmaplimit) {
7401 * Slow path, since we can get page faults
7402 * while mappings are active don't pin the
7403 * thread to the CPU and instead add a global
7404 * mapping visible to all CPUs.
7406 pmap_qenter(vaddr[i], &page[i], 1);
7408 pte = vtopte(vaddr[i]);
7409 cache_bits = pmap_cache_bits(kernel_pmap,
7410 page[i]->md.pat_mode, 0);
7411 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7418 return (needs_mapping);
7422 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7423 boolean_t can_fault)
7430 for (i = 0; i < count; i++) {
7431 paddr = VM_PAGE_TO_PHYS(page[i]);
7432 if (paddr >= dmaplimit) {
7434 pmap_qremove(vaddr[i], 1);
7435 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7441 pmap_quick_enter_page(vm_page_t m)
7445 paddr = VM_PAGE_TO_PHYS(m);
7446 if (paddr < dmaplimit)
7447 return (PHYS_TO_DMAP(paddr));
7448 mtx_lock_spin(&qframe_mtx);
7449 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7450 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7451 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7456 pmap_quick_remove_page(vm_offset_t addr)
7461 pte_store(vtopte(qframe), 0);
7463 mtx_unlock_spin(&qframe_mtx);
7466 #include "opt_ddb.h"
7468 #include <sys/kdb.h>
7469 #include <ddb/ddb.h>
7471 DB_SHOW_COMMAND(pte, pmap_print_pte)
7477 pt_entry_t *pte, PG_V;
7481 db_printf("show pte addr\n");
7484 va = (vm_offset_t)addr;
7486 if (kdb_thread != NULL)
7487 pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
7489 pmap = PCPU_GET(curpmap);
7491 PG_V = pmap_valid_bit(pmap);
7492 pml4 = pmap_pml4e(pmap, va);
7493 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
7494 if ((*pml4 & PG_V) == 0) {
7498 pdp = pmap_pml4e_to_pdpe(pml4, va);
7499 db_printf(" pdpe %#016lx", *pdp);
7500 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
7504 pde = pmap_pdpe_to_pde(pdp, va);
7505 db_printf(" pde %#016lx", *pde);
7506 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
7510 pte = pmap_pde_to_pte(pde, va);
7511 db_printf(" pte %#016lx\n", *pte);
7514 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
7519 a = (vm_paddr_t)addr;
7520 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
7522 db_printf("show phys2dmap addr\n");