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 pv_chunks_mutex;
384 static struct rwlock 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)
539 struct turnstile *ts;
542 bool accounted = false;
546 m_gen = pmap_delayed_invl_genp(m);
547 while (*m_gen > pmap_invl_gen) {
550 atomic_add_long(&invl_wait, 1);
554 ts = turnstile_trywait(&invl_gen_ts);
555 if (*m_gen > pmap_invl_gen)
556 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
558 turnstile_cancel(ts);
563 * Mark the page m's PV list as participating in the current thread's
564 * DI block. Any threads concurrently using m's PV list to remove or
565 * restrict all mappings to m will wait for the current thread's DI
566 * block to complete before proceeding.
568 * The function works by setting the DI generation number for m's PV
569 * list to at least the DI generation number of the current thread.
570 * This forces a caller of pmap_delayed_invl_wait() to block until
571 * current thread calls pmap_delayed_invl_finished().
574 pmap_delayed_invl_page(vm_page_t m)
578 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
579 gen = curthread->td_md.md_invl_gen.gen;
582 m_gen = pmap_delayed_invl_genp(m);
590 static caddr_t crashdumpmap;
593 * Internal flags for pmap_enter()'s helper functions.
595 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
596 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
598 static void free_pv_chunk(struct pv_chunk *pc);
599 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
600 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
601 static int popcnt_pc_map_pq(uint64_t *map);
602 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
603 static void reserve_pv_entries(pmap_t pmap, int needed,
604 struct rwlock **lockp);
605 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
606 struct rwlock **lockp);
607 static bool pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
608 u_int flags, struct rwlock **lockp);
609 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
610 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 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
634 struct rwlock **lockp);
635 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
637 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
638 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
639 struct spglist *free, struct rwlock **lockp);
640 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
641 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
642 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
643 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
644 struct spglist *free);
645 static bool pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
646 pd_entry_t *pde, struct spglist *free,
647 struct rwlock **lockp);
648 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
649 vm_page_t m, struct rwlock **lockp);
650 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
652 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
654 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
655 struct rwlock **lockp);
656 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
657 struct rwlock **lockp);
658 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
659 struct rwlock **lockp);
661 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
662 struct spglist *free);
663 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
664 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
667 * Move the kernel virtual free pointer to the next
668 * 2MB. This is used to help improve performance
669 * by using a large (2MB) page for much of the kernel
670 * (.text, .data, .bss)
673 pmap_kmem_choose(vm_offset_t addr)
675 vm_offset_t newaddr = addr;
677 newaddr = roundup2(addr, NBPDR);
681 /********************/
682 /* Inline functions */
683 /********************/
685 /* Return a non-clipped PD index for a given VA */
686 static __inline vm_pindex_t
687 pmap_pde_pindex(vm_offset_t va)
689 return (va >> PDRSHIFT);
693 /* Return a pointer to the PML4 slot that corresponds to a VA */
694 static __inline pml4_entry_t *
695 pmap_pml4e(pmap_t pmap, vm_offset_t va)
698 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
701 /* Return a pointer to the PDP slot that corresponds to a VA */
702 static __inline pdp_entry_t *
703 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
707 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
708 return (&pdpe[pmap_pdpe_index(va)]);
711 /* Return a pointer to the PDP slot that corresponds to a VA */
712 static __inline pdp_entry_t *
713 pmap_pdpe(pmap_t pmap, vm_offset_t va)
718 PG_V = pmap_valid_bit(pmap);
719 pml4e = pmap_pml4e(pmap, va);
720 if ((*pml4e & PG_V) == 0)
722 return (pmap_pml4e_to_pdpe(pml4e, va));
725 /* Return a pointer to the PD slot that corresponds to a VA */
726 static __inline pd_entry_t *
727 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
731 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
732 return (&pde[pmap_pde_index(va)]);
735 /* Return a pointer to the PD slot that corresponds to a VA */
736 static __inline pd_entry_t *
737 pmap_pde(pmap_t pmap, vm_offset_t va)
742 PG_V = pmap_valid_bit(pmap);
743 pdpe = pmap_pdpe(pmap, va);
744 if (pdpe == NULL || (*pdpe & PG_V) == 0)
746 return (pmap_pdpe_to_pde(pdpe, va));
749 /* Return a pointer to the PT slot that corresponds to a VA */
750 static __inline pt_entry_t *
751 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
755 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
756 return (&pte[pmap_pte_index(va)]);
759 /* Return a pointer to the PT slot that corresponds to a VA */
760 static __inline pt_entry_t *
761 pmap_pte(pmap_t pmap, vm_offset_t va)
766 PG_V = pmap_valid_bit(pmap);
767 pde = pmap_pde(pmap, va);
768 if (pde == NULL || (*pde & PG_V) == 0)
770 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
771 return ((pt_entry_t *)pde);
772 return (pmap_pde_to_pte(pde, va));
776 pmap_resident_count_inc(pmap_t pmap, int count)
779 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
780 pmap->pm_stats.resident_count += count;
784 pmap_resident_count_dec(pmap_t pmap, int count)
787 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
788 KASSERT(pmap->pm_stats.resident_count >= count,
789 ("pmap %p resident count underflow %ld %d", pmap,
790 pmap->pm_stats.resident_count, count));
791 pmap->pm_stats.resident_count -= count;
794 PMAP_INLINE pt_entry_t *
795 vtopte(vm_offset_t va)
797 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
799 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
801 return (PTmap + ((va >> PAGE_SHIFT) & mask));
804 static __inline pd_entry_t *
805 vtopde(vm_offset_t va)
807 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
809 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
811 return (PDmap + ((va >> PDRSHIFT) & mask));
815 allocpages(vm_paddr_t *firstaddr, int n)
820 bzero((void *)ret, n * PAGE_SIZE);
821 *firstaddr += n * PAGE_SIZE;
825 CTASSERT(powerof2(NDMPML4E));
827 /* number of kernel PDP slots */
828 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
831 nkpt_init(vm_paddr_t addr)
838 pt_pages = howmany(addr, 1 << PDRSHIFT);
839 pt_pages += NKPDPE(pt_pages);
842 * Add some slop beyond the bare minimum required for bootstrapping
845 * This is quite important when allocating KVA for kernel modules.
846 * The modules are required to be linked in the negative 2GB of
847 * the address space. If we run out of KVA in this region then
848 * pmap_growkernel() will need to allocate page table pages to map
849 * the entire 512GB of KVA space which is an unnecessary tax on
852 * Secondly, device memory mapped as part of setting up the low-
853 * level console(s) is taken from KVA, starting at virtual_avail.
854 * This is because cninit() is called after pmap_bootstrap() but
855 * before vm_init() and pmap_init(). 20MB for a frame buffer is
858 pt_pages += 32; /* 64MB additional slop. */
864 create_pagetables(vm_paddr_t *firstaddr)
866 int i, j, ndm1g, nkpdpe;
872 /* Allocate page table pages for the direct map */
873 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
874 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
876 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
877 if (ndmpdpphys > NDMPML4E) {
879 * Each NDMPML4E allows 512 GB, so limit to that,
880 * and then readjust ndmpdp and ndmpdpphys.
882 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
883 Maxmem = atop(NDMPML4E * NBPML4);
884 ndmpdpphys = NDMPML4E;
885 ndmpdp = NDMPML4E * NPDEPG;
887 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
889 if ((amd_feature & AMDID_PAGE1GB) != 0)
890 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
892 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
893 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
896 KPML4phys = allocpages(firstaddr, 1);
897 KPDPphys = allocpages(firstaddr, NKPML4E);
900 * Allocate the initial number of kernel page table pages required to
901 * bootstrap. We defer this until after all memory-size dependent
902 * allocations are done (e.g. direct map), so that we don't have to
903 * build in too much slop in our estimate.
905 * Note that when NKPML4E > 1, we have an empty page underneath
906 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
907 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
909 nkpt_init(*firstaddr);
910 nkpdpe = NKPDPE(nkpt);
912 KPTphys = allocpages(firstaddr, nkpt);
913 KPDphys = allocpages(firstaddr, nkpdpe);
915 /* Fill in the underlying page table pages */
916 /* Nominally read-only (but really R/W) from zero to physfree */
917 /* XXX not fully used, underneath 2M pages */
918 pt_p = (pt_entry_t *)KPTphys;
919 for (i = 0; ptoa(i) < *firstaddr; i++)
920 pt_p[i] = ptoa(i) | X86_PG_RW | X86_PG_V | X86_PG_G;
922 /* Now map the page tables at their location within PTmap */
923 pd_p = (pd_entry_t *)KPDphys;
924 for (i = 0; i < nkpt; i++)
925 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
927 /* Map from zero to end of allocations under 2M pages */
928 /* This replaces some of the KPTphys entries above */
929 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
930 pd_p[i] = (i << PDRSHIFT) | X86_PG_RW | X86_PG_V | PG_PS |
933 /* And connect up the PD to the PDP (leaving room for L4 pages) */
934 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
935 for (i = 0; i < nkpdpe; i++)
936 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
940 * Now, set up the direct map region using 2MB and/or 1GB pages. If
941 * the end of physical memory is not aligned to a 1GB page boundary,
942 * then the residual physical memory is mapped with 2MB pages. Later,
943 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
944 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
945 * that are partially used.
947 pd_p = (pd_entry_t *)DMPDphys;
948 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
949 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
950 /* Preset PG_M and PG_A because demotion expects it. */
951 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | X86_PG_G |
952 X86_PG_M | X86_PG_A | pg_nx;
954 pdp_p = (pdp_entry_t *)DMPDPphys;
955 for (i = 0; i < ndm1g; i++) {
956 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
957 /* Preset PG_M and PG_A because demotion expects it. */
958 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | X86_PG_G |
959 X86_PG_M | X86_PG_A | pg_nx;
961 for (j = 0; i < ndmpdp; i++, j++) {
962 pdp_p[i] = DMPDphys + ptoa(j);
963 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_U;
966 /* And recursively map PML4 to itself in order to get PTmap */
967 p4_p = (pml4_entry_t *)KPML4phys;
968 p4_p[PML4PML4I] = KPML4phys;
969 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | PG_U;
971 /* Connect the Direct Map slot(s) up to the PML4. */
972 for (i = 0; i < ndmpdpphys; i++) {
973 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
974 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | PG_U;
977 /* Connect the KVA slots up to the PML4 */
978 for (i = 0; i < NKPML4E; i++) {
979 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
980 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V | PG_U;
985 * Bootstrap the system enough to run with virtual memory.
987 * On amd64 this is called after mapping has already been enabled
988 * and just syncs the pmap module with what has already been done.
989 * [We can't call it easily with mapping off since the kernel is not
990 * mapped with PA == VA, hence we would have to relocate every address
991 * from the linked base (virtual) address "KERNBASE" to the actual
992 * (physical) address starting relative to 0]
995 pmap_bootstrap(vm_paddr_t *firstaddr)
1002 * Create an initial set of page tables to run the kernel in.
1004 create_pagetables(firstaddr);
1007 * Add a physical memory segment (vm_phys_seg) corresponding to the
1008 * preallocated kernel page table pages so that vm_page structures
1009 * representing these pages will be created. The vm_page structures
1010 * are required for promotion of the corresponding kernel virtual
1011 * addresses to superpage mappings.
1013 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1015 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
1016 virtual_avail = pmap_kmem_choose(virtual_avail);
1018 virtual_end = VM_MAX_KERNEL_ADDRESS;
1021 /* XXX do %cr0 as well */
1022 load_cr4(rcr4() | CR4_PGE);
1023 load_cr3(KPML4phys);
1024 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1025 load_cr4(rcr4() | CR4_SMEP);
1028 * Initialize the kernel pmap (which is statically allocated).
1030 PMAP_LOCK_INIT(kernel_pmap);
1031 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1032 kernel_pmap->pm_cr3 = KPML4phys;
1033 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1034 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1035 kernel_pmap->pm_flags = pmap_flags;
1038 * Initialize the TLB invalidations generation number lock.
1040 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1043 * Reserve some special page table entries/VA space for temporary
1046 #define SYSMAP(c, p, v, n) \
1047 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1053 * Crashdump maps. The first page is reused as CMAP1 for the
1056 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1057 CADDR1 = crashdumpmap;
1062 * Initialize the PAT MSR.
1063 * pmap_init_pat() clears and sets CR4_PGE, which, as a
1064 * side-effect, invalidates stale PG_G TLB entries that might
1065 * have been created in our pre-boot environment.
1069 /* Initialize TLB Context Id. */
1070 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1071 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1072 /* Check for INVPCID support */
1073 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1075 for (i = 0; i < MAXCPU; i++) {
1076 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1077 kernel_pmap->pm_pcids[i].pm_gen = 1;
1079 PCPU_SET(pcid_next, PMAP_PCID_KERN + 1);
1080 PCPU_SET(pcid_gen, 1);
1082 * pcpu area for APs is zeroed during AP startup.
1083 * pc_pcid_next and pc_pcid_gen are initialized by AP
1084 * during pcpu setup.
1086 load_cr4(rcr4() | CR4_PCIDE);
1088 pmap_pcid_enabled = 0;
1093 * Setup the PAT MSR.
1098 int pat_table[PAT_INDEX_SIZE];
1103 /* Bail if this CPU doesn't implement PAT. */
1104 if ((cpu_feature & CPUID_PAT) == 0)
1107 /* Set default PAT index table. */
1108 for (i = 0; i < PAT_INDEX_SIZE; i++)
1110 pat_table[PAT_WRITE_BACK] = 0;
1111 pat_table[PAT_WRITE_THROUGH] = 1;
1112 pat_table[PAT_UNCACHEABLE] = 3;
1113 pat_table[PAT_WRITE_COMBINING] = 3;
1114 pat_table[PAT_WRITE_PROTECTED] = 3;
1115 pat_table[PAT_UNCACHED] = 3;
1117 /* Initialize default PAT entries. */
1118 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1119 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1120 PAT_VALUE(2, PAT_UNCACHED) |
1121 PAT_VALUE(3, PAT_UNCACHEABLE) |
1122 PAT_VALUE(4, PAT_WRITE_BACK) |
1123 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1124 PAT_VALUE(6, PAT_UNCACHED) |
1125 PAT_VALUE(7, PAT_UNCACHEABLE);
1129 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1130 * Program 5 and 6 as WP and WC.
1131 * Leave 4 and 7 as WB and UC.
1133 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1134 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1135 PAT_VALUE(6, PAT_WRITE_COMBINING);
1136 pat_table[PAT_UNCACHED] = 2;
1137 pat_table[PAT_WRITE_PROTECTED] = 5;
1138 pat_table[PAT_WRITE_COMBINING] = 6;
1141 * Just replace PAT Index 2 with WC instead of UC-.
1143 pat_msr &= ~PAT_MASK(2);
1144 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1145 pat_table[PAT_WRITE_COMBINING] = 2;
1150 load_cr4(cr4 & ~CR4_PGE);
1152 /* Disable caches (CD = 1, NW = 0). */
1154 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1156 /* Flushes caches and TLBs. */
1160 /* Update PAT and index table. */
1161 wrmsr(MSR_PAT, pat_msr);
1162 for (i = 0; i < PAT_INDEX_SIZE; i++)
1163 pat_index[i] = pat_table[i];
1165 /* Flush caches and TLBs again. */
1169 /* Restore caches and PGE. */
1175 * Initialize a vm_page's machine-dependent fields.
1178 pmap_page_init(vm_page_t m)
1181 TAILQ_INIT(&m->md.pv_list);
1182 m->md.pat_mode = PAT_WRITE_BACK;
1186 * Initialize the pmap module.
1187 * Called by vm_init, to initialize any structures that the pmap
1188 * system needs to map virtual memory.
1193 struct pmap_preinit_mapping *ppim;
1196 int error, i, pv_npg;
1199 * Initialize the vm page array entries for the kernel pmap's
1202 for (i = 0; i < nkpt; i++) {
1203 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1204 KASSERT(mpte >= vm_page_array &&
1205 mpte < &vm_page_array[vm_page_array_size],
1206 ("pmap_init: page table page is out of range"));
1207 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1208 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1212 * If the kernel is running on a virtual machine, then it must assume
1213 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1214 * be prepared for the hypervisor changing the vendor and family that
1215 * are reported by CPUID. Consequently, the workaround for AMD Family
1216 * 10h Erratum 383 is enabled if the processor's feature set does not
1217 * include at least one feature that is only supported by older Intel
1218 * or newer AMD processors.
1220 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1221 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1222 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1224 workaround_erratum383 = 1;
1227 * Are large page mappings enabled?
1229 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1230 if (pg_ps_enabled) {
1231 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1232 ("pmap_init: can't assign to pagesizes[1]"));
1233 pagesizes[1] = NBPDR;
1237 * Initialize the pv chunk list mutex.
1239 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1242 * Initialize the pool of pv list locks.
1244 for (i = 0; i < NPV_LIST_LOCKS; i++)
1245 rw_init(&pv_list_locks[i], "pmap pv list");
1248 * Calculate the size of the pv head table for superpages.
1250 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1253 * Allocate memory for the pv head table for superpages.
1255 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1257 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1259 for (i = 0; i < pv_npg; i++)
1260 TAILQ_INIT(&pv_table[i].pv_list);
1261 TAILQ_INIT(&pv_dummy.pv_list);
1263 pmap_initialized = 1;
1264 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1265 ppim = pmap_preinit_mapping + i;
1268 /* Make the direct map consistent */
1269 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1270 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1271 ppim->sz, ppim->mode);
1275 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1276 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1279 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1280 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1281 (vmem_addr_t *)&qframe);
1283 panic("qframe allocation failed");
1286 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1287 "2MB page mapping counters");
1289 static u_long pmap_pde_demotions;
1290 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1291 &pmap_pde_demotions, 0, "2MB page demotions");
1293 static u_long pmap_pde_mappings;
1294 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1295 &pmap_pde_mappings, 0, "2MB page mappings");
1297 static u_long pmap_pde_p_failures;
1298 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1299 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1301 static u_long pmap_pde_promotions;
1302 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1303 &pmap_pde_promotions, 0, "2MB page promotions");
1305 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1306 "1GB page mapping counters");
1308 static u_long pmap_pdpe_demotions;
1309 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1310 &pmap_pdpe_demotions, 0, "1GB page demotions");
1312 /***************************************************
1313 * Low level helper routines.....
1314 ***************************************************/
1317 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1319 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1321 switch (pmap->pm_type) {
1324 /* Verify that both PAT bits are not set at the same time */
1325 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1326 ("Invalid PAT bits in entry %#lx", entry));
1328 /* Swap the PAT bits if one of them is set */
1329 if ((entry & x86_pat_bits) != 0)
1330 entry ^= x86_pat_bits;
1334 * Nothing to do - the memory attributes are represented
1335 * the same way for regular pages and superpages.
1339 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1346 * Determine the appropriate bits to set in a PTE or PDE for a specified
1350 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1352 int cache_bits, pat_flag, pat_idx;
1354 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1355 panic("Unknown caching mode %d\n", mode);
1357 switch (pmap->pm_type) {
1360 /* The PAT bit is different for PTE's and PDE's. */
1361 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1363 /* Map the caching mode to a PAT index. */
1364 pat_idx = pat_index[mode];
1366 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1369 cache_bits |= pat_flag;
1371 cache_bits |= PG_NC_PCD;
1373 cache_bits |= PG_NC_PWT;
1377 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1381 panic("unsupported pmap type %d", pmap->pm_type);
1384 return (cache_bits);
1388 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1392 switch (pmap->pm_type) {
1395 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1398 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1401 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1408 pmap_ps_enabled(pmap_t pmap)
1411 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1415 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1418 switch (pmap->pm_type) {
1425 * This is a little bogus since the generation number is
1426 * supposed to be bumped up when a region of the address
1427 * space is invalidated in the page tables.
1429 * In this case the old PDE entry is valid but yet we want
1430 * to make sure that any mappings using the old entry are
1431 * invalidated in the TLB.
1433 * The reason this works as expected is because we rendezvous
1434 * "all" host cpus and force any vcpu context to exit as a
1437 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1440 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1442 pde_store(pde, newpde);
1446 * After changing the page size for the specified virtual address in the page
1447 * table, flush the corresponding entries from the processor's TLB. Only the
1448 * calling processor's TLB is affected.
1450 * The calling thread must be pinned to a processor.
1453 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1457 if (pmap_type_guest(pmap))
1460 KASSERT(pmap->pm_type == PT_X86,
1461 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1463 PG_G = pmap_global_bit(pmap);
1465 if ((newpde & PG_PS) == 0)
1466 /* Demotion: flush a specific 2MB page mapping. */
1468 else if ((newpde & PG_G) == 0)
1470 * Promotion: flush every 4KB page mapping from the TLB
1471 * because there are too many to flush individually.
1476 * Promotion: flush every 4KB page mapping from the TLB,
1477 * including any global (PG_G) mappings.
1485 * For SMP, these functions have to use the IPI mechanism for coherence.
1487 * N.B.: Before calling any of the following TLB invalidation functions,
1488 * the calling processor must ensure that all stores updating a non-
1489 * kernel page table are globally performed. Otherwise, another
1490 * processor could cache an old, pre-update entry without being
1491 * invalidated. This can happen one of two ways: (1) The pmap becomes
1492 * active on another processor after its pm_active field is checked by
1493 * one of the following functions but before a store updating the page
1494 * table is globally performed. (2) The pmap becomes active on another
1495 * processor before its pm_active field is checked but due to
1496 * speculative loads one of the following functions stills reads the
1497 * pmap as inactive on the other processor.
1499 * The kernel page table is exempt because its pm_active field is
1500 * immutable. The kernel page table is always active on every
1505 * Interrupt the cpus that are executing in the guest context.
1506 * This will force the vcpu to exit and the cached EPT mappings
1507 * will be invalidated by the host before the next vmresume.
1509 static __inline void
1510 pmap_invalidate_ept(pmap_t pmap)
1515 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1516 ("pmap_invalidate_ept: absurd pm_active"));
1519 * The TLB mappings associated with a vcpu context are not
1520 * flushed each time a different vcpu is chosen to execute.
1522 * This is in contrast with a process's vtop mappings that
1523 * are flushed from the TLB on each context switch.
1525 * Therefore we need to do more than just a TLB shootdown on
1526 * the active cpus in 'pmap->pm_active'. To do this we keep
1527 * track of the number of invalidations performed on this pmap.
1529 * Each vcpu keeps a cache of this counter and compares it
1530 * just before a vmresume. If the counter is out-of-date an
1531 * invept will be done to flush stale mappings from the TLB.
1533 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1536 * Force the vcpu to exit and trap back into the hypervisor.
1538 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1539 ipi_selected(pmap->pm_active, ipinum);
1544 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1549 if (pmap_type_guest(pmap)) {
1550 pmap_invalidate_ept(pmap);
1554 KASSERT(pmap->pm_type == PT_X86,
1555 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1558 if (pmap == kernel_pmap) {
1562 cpuid = PCPU_GET(cpuid);
1563 if (pmap == PCPU_GET(curpmap))
1565 else if (pmap_pcid_enabled)
1566 pmap->pm_pcids[cpuid].pm_gen = 0;
1567 if (pmap_pcid_enabled) {
1570 pmap->pm_pcids[i].pm_gen = 0;
1573 mask = &pmap->pm_active;
1575 smp_masked_invlpg(*mask, va);
1579 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1580 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1583 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1589 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1590 pmap_invalidate_all(pmap);
1594 if (pmap_type_guest(pmap)) {
1595 pmap_invalidate_ept(pmap);
1599 KASSERT(pmap->pm_type == PT_X86,
1600 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1603 cpuid = PCPU_GET(cpuid);
1604 if (pmap == kernel_pmap) {
1605 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1609 if (pmap == PCPU_GET(curpmap)) {
1610 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1612 } else if (pmap_pcid_enabled) {
1613 pmap->pm_pcids[cpuid].pm_gen = 0;
1615 if (pmap_pcid_enabled) {
1618 pmap->pm_pcids[i].pm_gen = 0;
1621 mask = &pmap->pm_active;
1623 smp_masked_invlpg_range(*mask, sva, eva);
1628 pmap_invalidate_all(pmap_t pmap)
1631 struct invpcid_descr d;
1634 if (pmap_type_guest(pmap)) {
1635 pmap_invalidate_ept(pmap);
1639 KASSERT(pmap->pm_type == PT_X86,
1640 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1643 if (pmap == kernel_pmap) {
1644 if (pmap_pcid_enabled && invpcid_works) {
1645 bzero(&d, sizeof(d));
1646 invpcid(&d, INVPCID_CTXGLOB);
1652 cpuid = PCPU_GET(cpuid);
1653 if (pmap == PCPU_GET(curpmap)) {
1654 if (pmap_pcid_enabled) {
1655 if (invpcid_works) {
1656 d.pcid = pmap->pm_pcids[cpuid].pm_pcid;
1659 invpcid(&d, INVPCID_CTX);
1661 load_cr3(pmap->pm_cr3 | pmap->pm_pcids
1662 [PCPU_GET(cpuid)].pm_pcid);
1667 } else if (pmap_pcid_enabled) {
1668 pmap->pm_pcids[cpuid].pm_gen = 0;
1670 if (pmap_pcid_enabled) {
1673 pmap->pm_pcids[i].pm_gen = 0;
1676 mask = &pmap->pm_active;
1678 smp_masked_invltlb(*mask, pmap);
1683 pmap_invalidate_cache(void)
1693 cpuset_t invalidate; /* processors that invalidate their TLB */
1698 u_int store; /* processor that updates the PDE */
1702 pmap_update_pde_action(void *arg)
1704 struct pde_action *act = arg;
1706 if (act->store == PCPU_GET(cpuid))
1707 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1711 pmap_update_pde_teardown(void *arg)
1713 struct pde_action *act = arg;
1715 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1716 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1720 * Change the page size for the specified virtual address in a way that
1721 * prevents any possibility of the TLB ever having two entries that map the
1722 * same virtual address using different page sizes. This is the recommended
1723 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1724 * machine check exception for a TLB state that is improperly diagnosed as a
1728 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1730 struct pde_action act;
1731 cpuset_t active, other_cpus;
1735 cpuid = PCPU_GET(cpuid);
1736 other_cpus = all_cpus;
1737 CPU_CLR(cpuid, &other_cpus);
1738 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1741 active = pmap->pm_active;
1743 if (CPU_OVERLAP(&active, &other_cpus)) {
1745 act.invalidate = active;
1749 act.newpde = newpde;
1750 CPU_SET(cpuid, &active);
1751 smp_rendezvous_cpus(active,
1752 smp_no_rendezvous_barrier, pmap_update_pde_action,
1753 pmap_update_pde_teardown, &act);
1755 pmap_update_pde_store(pmap, pde, newpde);
1756 if (CPU_ISSET(cpuid, &active))
1757 pmap_update_pde_invalidate(pmap, va, newpde);
1763 * Normal, non-SMP, invalidation functions.
1766 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1769 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1773 KASSERT(pmap->pm_type == PT_X86,
1774 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1776 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1778 else if (pmap_pcid_enabled)
1779 pmap->pm_pcids[0].pm_gen = 0;
1783 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1787 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1791 KASSERT(pmap->pm_type == PT_X86,
1792 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1794 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1795 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1797 } else if (pmap_pcid_enabled) {
1798 pmap->pm_pcids[0].pm_gen = 0;
1803 pmap_invalidate_all(pmap_t pmap)
1805 struct invpcid_descr d;
1807 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1811 KASSERT(pmap->pm_type == PT_X86,
1812 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
1814 if (pmap == kernel_pmap) {
1815 if (pmap_pcid_enabled && invpcid_works) {
1816 bzero(&d, sizeof(d));
1817 invpcid(&d, INVPCID_CTXGLOB);
1821 } else if (pmap == PCPU_GET(curpmap)) {
1822 if (pmap_pcid_enabled) {
1823 if (invpcid_works) {
1824 d.pcid = pmap->pm_pcids[0].pm_pcid;
1827 invpcid(&d, INVPCID_CTX);
1829 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[0].
1835 } else if (pmap_pcid_enabled) {
1836 pmap->pm_pcids[0].pm_gen = 0;
1841 pmap_invalidate_cache(void)
1848 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1851 pmap_update_pde_store(pmap, pde, newpde);
1852 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1853 pmap_update_pde_invalidate(pmap, va, newpde);
1855 pmap->pm_pcids[0].pm_gen = 0;
1860 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
1864 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
1865 * by a promotion that did not invalidate the 512 4KB page mappings
1866 * that might exist in the TLB. Consequently, at this point, the TLB
1867 * may hold both 4KB and 2MB page mappings for the address range [va,
1868 * va + NBPDR). Therefore, the entire range must be invalidated here.
1869 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
1870 * 4KB page mappings for the address range [va, va + NBPDR), and so a
1871 * single INVLPG suffices to invalidate the 2MB page mapping from the
1874 if ((pde & PG_PROMOTED) != 0)
1875 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
1877 pmap_invalidate_page(pmap, va);
1880 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
1883 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
1887 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
1889 KASSERT((sva & PAGE_MASK) == 0,
1890 ("pmap_invalidate_cache_range: sva not page-aligned"));
1891 KASSERT((eva & PAGE_MASK) == 0,
1892 ("pmap_invalidate_cache_range: eva not page-aligned"));
1895 if ((cpu_feature & CPUID_SS) != 0 && !force)
1896 ; /* If "Self Snoop" is supported and allowed, do nothing. */
1897 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
1898 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1900 * XXX: Some CPUs fault, hang, or trash the local APIC
1901 * registers if we use CLFLUSH on the local APIC
1902 * range. The local APIC is always uncached, so we
1903 * don't need to flush for that range anyway.
1905 if (pmap_kextract(sva) == lapic_paddr)
1909 * Otherwise, do per-cache line flush. Use the sfence
1910 * instruction to insure that previous stores are
1911 * included in the write-back. The processor
1912 * propagates flush to other processors in the cache
1916 for (; sva < eva; sva += cpu_clflush_line_size)
1919 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
1920 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1921 if (pmap_kextract(sva) == lapic_paddr)
1924 * Writes are ordered by CLFLUSH on Intel CPUs.
1926 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1928 for (; sva < eva; sva += cpu_clflush_line_size)
1930 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1935 * No targeted cache flush methods are supported by CPU,
1936 * or the supplied range is bigger than 2MB.
1937 * Globally invalidate cache.
1939 pmap_invalidate_cache();
1944 * Remove the specified set of pages from the data and instruction caches.
1946 * In contrast to pmap_invalidate_cache_range(), this function does not
1947 * rely on the CPU's self-snoop feature, because it is intended for use
1948 * when moving pages into a different cache domain.
1951 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1953 vm_offset_t daddr, eva;
1957 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
1958 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1959 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
1960 pmap_invalidate_cache();
1964 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
1966 for (i = 0; i < count; i++) {
1967 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
1968 eva = daddr + PAGE_SIZE;
1969 for (; daddr < eva; daddr += cpu_clflush_line_size) {
1978 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
1984 * Routine: pmap_extract
1986 * Extract the physical page address associated
1987 * with the given map/virtual_address pair.
1990 pmap_extract(pmap_t pmap, vm_offset_t va)
1994 pt_entry_t *pte, PG_V;
1998 PG_V = pmap_valid_bit(pmap);
2000 pdpe = pmap_pdpe(pmap, va);
2001 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2002 if ((*pdpe & PG_PS) != 0)
2003 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
2005 pde = pmap_pdpe_to_pde(pdpe, va);
2006 if ((*pde & PG_V) != 0) {
2007 if ((*pde & PG_PS) != 0) {
2008 pa = (*pde & PG_PS_FRAME) |
2011 pte = pmap_pde_to_pte(pde, va);
2012 pa = (*pte & PG_FRAME) |
2023 * Routine: pmap_extract_and_hold
2025 * Atomically extract and hold the physical page
2026 * with the given pmap and virtual address pair
2027 * if that mapping permits the given protection.
2030 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
2032 pd_entry_t pde, *pdep;
2033 pt_entry_t pte, PG_RW, PG_V;
2039 PG_RW = pmap_rw_bit(pmap);
2040 PG_V = pmap_valid_bit(pmap);
2043 pdep = pmap_pde(pmap, va);
2044 if (pdep != NULL && (pde = *pdep)) {
2046 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2047 if (vm_page_pa_tryrelock(pmap, (pde &
2048 PG_PS_FRAME) | (va & PDRMASK), &pa))
2050 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
2055 pte = *pmap_pde_to_pte(pdep, va);
2057 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2058 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2061 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
2072 pmap_kextract(vm_offset_t va)
2077 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2078 pa = DMAP_TO_PHYS(va);
2082 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2085 * Beware of a concurrent promotion that changes the
2086 * PDE at this point! For example, vtopte() must not
2087 * be used to access the PTE because it would use the
2088 * new PDE. It is, however, safe to use the old PDE
2089 * because the page table page is preserved by the
2092 pa = *pmap_pde_to_pte(&pde, va);
2093 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2099 /***************************************************
2100 * Low level mapping routines.....
2101 ***************************************************/
2104 * Add a wired page to the kva.
2105 * Note: not SMP coherent.
2108 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2113 pte_store(pte, pa | X86_PG_RW | X86_PG_V | X86_PG_G);
2116 static __inline void
2117 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2123 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2124 pte_store(pte, pa | X86_PG_RW | X86_PG_V | X86_PG_G | cache_bits);
2128 * Remove a page from the kernel pagetables.
2129 * Note: not SMP coherent.
2132 pmap_kremove(vm_offset_t va)
2141 * Used to map a range of physical addresses into kernel
2142 * virtual address space.
2144 * The value passed in '*virt' is a suggested virtual address for
2145 * the mapping. Architectures which can support a direct-mapped
2146 * physical to virtual region can return the appropriate address
2147 * within that region, leaving '*virt' unchanged. Other
2148 * architectures should map the pages starting at '*virt' and
2149 * update '*virt' with the first usable address after the mapped
2153 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2155 return PHYS_TO_DMAP(start);
2160 * Add a list of wired pages to the kva
2161 * this routine is only used for temporary
2162 * kernel mappings that do not need to have
2163 * page modification or references recorded.
2164 * Note that old mappings are simply written
2165 * over. The page *must* be wired.
2166 * Note: SMP coherent. Uses a ranged shootdown IPI.
2169 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2171 pt_entry_t *endpte, oldpte, pa, *pte;
2177 endpte = pte + count;
2178 while (pte < endpte) {
2180 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2181 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2182 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2184 pte_store(pte, pa | X86_PG_G | X86_PG_RW | X86_PG_V);
2188 if (__predict_false((oldpte & X86_PG_V) != 0))
2189 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2194 * This routine tears out page mappings from the
2195 * kernel -- it is meant only for temporary mappings.
2196 * Note: SMP coherent. Uses a ranged shootdown IPI.
2199 pmap_qremove(vm_offset_t sva, int count)
2204 while (count-- > 0) {
2205 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2209 pmap_invalidate_range(kernel_pmap, sva, va);
2212 /***************************************************
2213 * Page table page management routines.....
2214 ***************************************************/
2215 static __inline void
2216 pmap_free_zero_pages(struct spglist *free)
2221 for (count = 0; (m = SLIST_FIRST(free)) != NULL; count++) {
2222 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2223 /* Preserve the page's PG_ZERO setting. */
2224 vm_page_free_toq(m);
2226 atomic_subtract_int(&vm_cnt.v_wire_count, count);
2230 * Schedule the specified unused page table page to be freed. Specifically,
2231 * add the page to the specified list of pages that will be released to the
2232 * physical memory manager after the TLB has been updated.
2234 static __inline void
2235 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2236 boolean_t set_PG_ZERO)
2240 m->flags |= PG_ZERO;
2242 m->flags &= ~PG_ZERO;
2243 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2247 * Inserts the specified page table page into the specified pmap's collection
2248 * of idle page table pages. Each of a pmap's page table pages is responsible
2249 * for mapping a distinct range of virtual addresses. The pmap's collection is
2250 * ordered by this virtual address range.
2253 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2256 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2257 return (vm_radix_insert(&pmap->pm_root, mpte));
2261 * Removes the page table page mapping the specified virtual address from the
2262 * specified pmap's collection of idle page table pages, and returns it.
2263 * Otherwise, returns NULL if there is no page table page corresponding to the
2264 * specified virtual address.
2266 static __inline vm_page_t
2267 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
2270 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2271 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
2275 * Decrements a page table page's wire count, which is used to record the
2276 * number of valid page table entries within the page. If the wire count
2277 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2278 * page table page was unmapped and FALSE otherwise.
2280 static inline boolean_t
2281 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2285 if (m->wire_count == 0) {
2286 _pmap_unwire_ptp(pmap, va, m, free);
2293 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2296 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2298 * unmap the page table page
2300 if (m->pindex >= (NUPDE + NUPDPE)) {
2303 pml4 = pmap_pml4e(pmap, va);
2305 } else if (m->pindex >= NUPDE) {
2308 pdp = pmap_pdpe(pmap, va);
2313 pd = pmap_pde(pmap, va);
2316 pmap_resident_count_dec(pmap, 1);
2317 if (m->pindex < NUPDE) {
2318 /* We just released a PT, unhold the matching PD */
2321 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2322 pmap_unwire_ptp(pmap, va, pdpg, free);
2324 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2325 /* We just released a PD, unhold the matching PDP */
2328 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2329 pmap_unwire_ptp(pmap, va, pdppg, free);
2333 * Put page on a list so that it is released after
2334 * *ALL* TLB shootdown is done
2336 pmap_add_delayed_free_list(m, free, TRUE);
2340 * After removing a page table entry, this routine is used to
2341 * conditionally free the page, and manage the hold/wire counts.
2344 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2345 struct spglist *free)
2349 if (va >= VM_MAXUSER_ADDRESS)
2351 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2352 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2353 return (pmap_unwire_ptp(pmap, va, mpte, free));
2357 pmap_pinit0(pmap_t pmap)
2361 PMAP_LOCK_INIT(pmap);
2362 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2363 pmap->pm_cr3 = KPML4phys;
2364 pmap->pm_root.rt_root = 0;
2365 CPU_ZERO(&pmap->pm_active);
2366 TAILQ_INIT(&pmap->pm_pvchunk);
2367 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2368 pmap->pm_flags = pmap_flags;
2370 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2371 pmap->pm_pcids[i].pm_gen = 0;
2373 PCPU_SET(curpmap, kernel_pmap);
2374 pmap_activate(curthread);
2375 CPU_FILL(&kernel_pmap->pm_active);
2379 pmap_pinit_pml4(vm_page_t pml4pg)
2381 pml4_entry_t *pm_pml4;
2384 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2386 /* Wire in kernel global address entries. */
2387 for (i = 0; i < NKPML4E; i++) {
2388 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2391 for (i = 0; i < ndmpdpphys; i++) {
2392 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2396 /* install self-referential address mapping entry(s) */
2397 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2398 X86_PG_A | X86_PG_M;
2402 * Initialize a preallocated and zeroed pmap structure,
2403 * such as one in a vmspace structure.
2406 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2409 vm_paddr_t pml4phys;
2413 * allocate the page directory page
2415 while ((pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2416 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL)
2419 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2420 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2422 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2423 pmap->pm_pcids[i].pm_gen = 0;
2425 pmap->pm_cr3 = ~0; /* initialize to an invalid value */
2427 if ((pml4pg->flags & PG_ZERO) == 0)
2428 pagezero(pmap->pm_pml4);
2431 * Do not install the host kernel mappings in the nested page
2432 * tables. These mappings are meaningless in the guest physical
2435 if ((pmap->pm_type = pm_type) == PT_X86) {
2436 pmap->pm_cr3 = pml4phys;
2437 pmap_pinit_pml4(pml4pg);
2440 pmap->pm_root.rt_root = 0;
2441 CPU_ZERO(&pmap->pm_active);
2442 TAILQ_INIT(&pmap->pm_pvchunk);
2443 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2444 pmap->pm_flags = flags;
2445 pmap->pm_eptgen = 0;
2451 pmap_pinit(pmap_t pmap)
2454 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2458 * This routine is called if the desired page table page does not exist.
2460 * If page table page allocation fails, this routine may sleep before
2461 * returning NULL. It sleeps only if a lock pointer was given.
2463 * Note: If a page allocation fails at page table level two or three,
2464 * one or two pages may be held during the wait, only to be released
2465 * afterwards. This conservative approach is easily argued to avoid
2469 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2471 vm_page_t m, pdppg, pdpg;
2472 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2474 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2476 PG_A = pmap_accessed_bit(pmap);
2477 PG_M = pmap_modified_bit(pmap);
2478 PG_V = pmap_valid_bit(pmap);
2479 PG_RW = pmap_rw_bit(pmap);
2482 * Allocate a page table page.
2484 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2485 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2486 if (lockp != NULL) {
2487 RELEASE_PV_LIST_LOCK(lockp);
2489 PMAP_ASSERT_NOT_IN_DI();
2495 * Indicate the need to retry. While waiting, the page table
2496 * page may have been allocated.
2500 if ((m->flags & PG_ZERO) == 0)
2504 * Map the pagetable page into the process address space, if
2505 * it isn't already there.
2508 if (ptepindex >= (NUPDE + NUPDPE)) {
2510 vm_pindex_t pml4index;
2512 /* Wire up a new PDPE page */
2513 pml4index = ptepindex - (NUPDE + NUPDPE);
2514 pml4 = &pmap->pm_pml4[pml4index];
2515 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2517 } else if (ptepindex >= NUPDE) {
2518 vm_pindex_t pml4index;
2519 vm_pindex_t pdpindex;
2523 /* Wire up a new PDE page */
2524 pdpindex = ptepindex - NUPDE;
2525 pml4index = pdpindex >> NPML4EPGSHIFT;
2527 pml4 = &pmap->pm_pml4[pml4index];
2528 if ((*pml4 & PG_V) == 0) {
2529 /* Have to allocate a new pdp, recurse */
2530 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2533 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2534 vm_page_free_zero(m);
2538 /* Add reference to pdp page */
2539 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2540 pdppg->wire_count++;
2542 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2544 /* Now find the pdp page */
2545 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2546 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2549 vm_pindex_t pml4index;
2550 vm_pindex_t pdpindex;
2555 /* Wire up a new PTE page */
2556 pdpindex = ptepindex >> NPDPEPGSHIFT;
2557 pml4index = pdpindex >> NPML4EPGSHIFT;
2559 /* First, find the pdp and check that its valid. */
2560 pml4 = &pmap->pm_pml4[pml4index];
2561 if ((*pml4 & PG_V) == 0) {
2562 /* Have to allocate a new pd, recurse */
2563 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2566 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2567 vm_page_free_zero(m);
2570 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2571 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2573 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2574 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2575 if ((*pdp & PG_V) == 0) {
2576 /* Have to allocate a new pd, recurse */
2577 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2580 atomic_subtract_int(&vm_cnt.v_wire_count,
2582 vm_page_free_zero(m);
2586 /* Add reference to the pd page */
2587 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2591 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2593 /* Now we know where the page directory page is */
2594 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2595 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2598 pmap_resident_count_inc(pmap, 1);
2604 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2606 vm_pindex_t pdpindex, ptepindex;
2607 pdp_entry_t *pdpe, PG_V;
2610 PG_V = pmap_valid_bit(pmap);
2613 pdpe = pmap_pdpe(pmap, va);
2614 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2615 /* Add a reference to the pd page. */
2616 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2619 /* Allocate a pd page. */
2620 ptepindex = pmap_pde_pindex(va);
2621 pdpindex = ptepindex >> NPDPEPGSHIFT;
2622 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2623 if (pdpg == NULL && lockp != NULL)
2630 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2632 vm_pindex_t ptepindex;
2633 pd_entry_t *pd, PG_V;
2636 PG_V = pmap_valid_bit(pmap);
2639 * Calculate pagetable page index
2641 ptepindex = pmap_pde_pindex(va);
2644 * Get the page directory entry
2646 pd = pmap_pde(pmap, va);
2649 * This supports switching from a 2MB page to a
2652 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2653 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2655 * Invalidation of the 2MB page mapping may have caused
2656 * the deallocation of the underlying PD page.
2663 * If the page table page is mapped, we just increment the
2664 * hold count, and activate it.
2666 if (pd != NULL && (*pd & PG_V) != 0) {
2667 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2671 * Here if the pte page isn't mapped, or if it has been
2674 m = _pmap_allocpte(pmap, ptepindex, lockp);
2675 if (m == NULL && lockp != NULL)
2682 /***************************************************
2683 * Pmap allocation/deallocation routines.
2684 ***************************************************/
2687 * Release any resources held by the given physical map.
2688 * Called when a pmap initialized by pmap_pinit is being released.
2689 * Should only be called if the map contains no valid mappings.
2692 pmap_release(pmap_t pmap)
2697 KASSERT(pmap->pm_stats.resident_count == 0,
2698 ("pmap_release: pmap resident count %ld != 0",
2699 pmap->pm_stats.resident_count));
2700 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2701 ("pmap_release: pmap has reserved page table page(s)"));
2702 KASSERT(CPU_EMPTY(&pmap->pm_active),
2703 ("releasing active pmap %p", pmap));
2705 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2707 for (i = 0; i < NKPML4E; i++) /* KVA */
2708 pmap->pm_pml4[KPML4BASE + i] = 0;
2709 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
2710 pmap->pm_pml4[DMPML4I + i] = 0;
2711 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
2714 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2715 vm_page_free_zero(m);
2719 kvm_size(SYSCTL_HANDLER_ARGS)
2721 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2723 return sysctl_handle_long(oidp, &ksize, 0, req);
2725 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2726 0, 0, kvm_size, "LU", "Size of KVM");
2729 kvm_free(SYSCTL_HANDLER_ARGS)
2731 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2733 return sysctl_handle_long(oidp, &kfree, 0, req);
2735 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2736 0, 0, kvm_free, "LU", "Amount of KVM free");
2739 * grow the number of kernel page table entries, if needed
2742 pmap_growkernel(vm_offset_t addr)
2746 pd_entry_t *pde, newpdir;
2749 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2752 * Return if "addr" is within the range of kernel page table pages
2753 * that were preallocated during pmap bootstrap. Moreover, leave
2754 * "kernel_vm_end" and the kernel page table as they were.
2756 * The correctness of this action is based on the following
2757 * argument: vm_map_insert() allocates contiguous ranges of the
2758 * kernel virtual address space. It calls this function if a range
2759 * ends after "kernel_vm_end". If the kernel is mapped between
2760 * "kernel_vm_end" and "addr", then the range cannot begin at
2761 * "kernel_vm_end". In fact, its beginning address cannot be less
2762 * than the kernel. Thus, there is no immediate need to allocate
2763 * any new kernel page table pages between "kernel_vm_end" and
2766 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
2769 addr = roundup2(addr, NBPDR);
2770 if (addr - 1 >= kernel_map->max_offset)
2771 addr = kernel_map->max_offset;
2772 while (kernel_vm_end < addr) {
2773 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
2774 if ((*pdpe & X86_PG_V) == 0) {
2775 /* We need a new PDP entry */
2776 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
2777 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
2778 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2780 panic("pmap_growkernel: no memory to grow kernel");
2781 if ((nkpg->flags & PG_ZERO) == 0)
2782 pmap_zero_page(nkpg);
2783 paddr = VM_PAGE_TO_PHYS(nkpg);
2784 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
2785 X86_PG_A | X86_PG_M);
2786 continue; /* try again */
2788 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
2789 if ((*pde & X86_PG_V) != 0) {
2790 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2791 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2792 kernel_vm_end = kernel_map->max_offset;
2798 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
2799 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
2802 panic("pmap_growkernel: no memory to grow kernel");
2803 if ((nkpg->flags & PG_ZERO) == 0)
2804 pmap_zero_page(nkpg);
2805 paddr = VM_PAGE_TO_PHYS(nkpg);
2806 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
2807 pde_store(pde, newpdir);
2809 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2810 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2811 kernel_vm_end = kernel_map->max_offset;
2818 /***************************************************
2819 * page management routines.
2820 ***************************************************/
2822 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
2823 CTASSERT(_NPCM == 3);
2824 CTASSERT(_NPCPV == 168);
2826 static __inline struct pv_chunk *
2827 pv_to_chunk(pv_entry_t pv)
2830 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
2833 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
2835 #define PC_FREE0 0xfffffffffffffffful
2836 #define PC_FREE1 0xfffffffffffffffful
2837 #define PC_FREE2 0x000000fffffffffful
2839 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
2842 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2844 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2845 "Current number of pv entry chunks");
2846 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2847 "Current number of pv entry chunks allocated");
2848 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2849 "Current number of pv entry chunks frees");
2850 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
2851 "Number of times tried to get a chunk page but failed.");
2853 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
2854 static int pv_entry_spare;
2856 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2857 "Current number of pv entry frees");
2858 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
2859 "Current number of pv entry allocs");
2860 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2861 "Current number of pv entries");
2862 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2863 "Current number of spare pv entries");
2867 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
2872 pmap_invalidate_all(pmap);
2873 if (pmap != locked_pmap)
2876 pmap_delayed_invl_finished();
2880 * We are in a serious low memory condition. Resort to
2881 * drastic measures to free some pages so we can allocate
2882 * another pv entry chunk.
2884 * Returns NULL if PV entries were reclaimed from the specified pmap.
2886 * We do not, however, unmap 2mpages because subsequent accesses will
2887 * allocate per-page pv entries until repromotion occurs, thereby
2888 * exacerbating the shortage of free pv entries.
2891 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
2893 struct pch new_tail;
2894 struct pv_chunk *pc;
2895 struct md_page *pvh;
2898 pt_entry_t *pte, tpte;
2899 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
2903 struct spglist free;
2905 int bit, field, freed;
2908 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2909 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
2912 PG_G = PG_A = PG_M = PG_RW = 0;
2914 TAILQ_INIT(&new_tail);
2917 * A delayed invalidation block should already be active if
2918 * pmap_advise() or pmap_remove() called this function by way
2919 * of pmap_demote_pde_locked().
2921 start_di = pmap_not_in_di();
2923 mtx_lock(&pv_chunks_mutex);
2924 while ((pc = TAILQ_FIRST(&pv_chunks)) != NULL && SLIST_EMPTY(&free)) {
2925 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2926 mtx_unlock(&pv_chunks_mutex);
2927 if (pmap != pc->pc_pmap) {
2928 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
2931 /* Avoid deadlock and lock recursion. */
2932 if (pmap > locked_pmap) {
2933 RELEASE_PV_LIST_LOCK(lockp);
2935 } else if (pmap != locked_pmap &&
2936 !PMAP_TRYLOCK(pmap)) {
2938 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2939 mtx_lock(&pv_chunks_mutex);
2942 PG_G = pmap_global_bit(pmap);
2943 PG_A = pmap_accessed_bit(pmap);
2944 PG_M = pmap_modified_bit(pmap);
2945 PG_RW = pmap_rw_bit(pmap);
2947 pmap_delayed_invl_started();
2951 * Destroy every non-wired, 4 KB page mapping in the chunk.
2954 for (field = 0; field < _NPCM; field++) {
2955 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2956 inuse != 0; inuse &= ~(1UL << bit)) {
2958 pv = &pc->pc_pventry[field * 64 + bit];
2960 pde = pmap_pde(pmap, va);
2961 if ((*pde & PG_PS) != 0)
2963 pte = pmap_pde_to_pte(pde, va);
2964 if ((*pte & PG_W) != 0)
2966 tpte = pte_load_clear(pte);
2967 if ((tpte & PG_G) != 0)
2968 pmap_invalidate_page(pmap, va);
2969 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
2970 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
2972 if ((tpte & PG_A) != 0)
2973 vm_page_aflag_set(m, PGA_REFERENCED);
2974 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
2975 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
2977 if (TAILQ_EMPTY(&m->md.pv_list) &&
2978 (m->flags & PG_FICTITIOUS) == 0) {
2979 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
2980 if (TAILQ_EMPTY(&pvh->pv_list)) {
2981 vm_page_aflag_clear(m,
2985 pmap_delayed_invl_page(m);
2986 pc->pc_map[field] |= 1UL << bit;
2987 pmap_unuse_pt(pmap, va, *pde, &free);
2992 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2993 mtx_lock(&pv_chunks_mutex);
2996 /* Every freed mapping is for a 4 KB page. */
2997 pmap_resident_count_dec(pmap, freed);
2998 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
2999 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
3000 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
3001 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3002 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
3003 pc->pc_map[2] == PC_FREE2) {
3004 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3005 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3006 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3007 /* Entire chunk is free; return it. */
3008 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3009 dump_drop_page(m_pc->phys_addr);
3010 mtx_lock(&pv_chunks_mutex);
3013 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3014 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3015 mtx_lock(&pv_chunks_mutex);
3016 /* One freed pv entry in locked_pmap is sufficient. */
3017 if (pmap == locked_pmap)
3020 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3021 mtx_unlock(&pv_chunks_mutex);
3022 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
3023 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
3024 m_pc = SLIST_FIRST(&free);
3025 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3026 /* Recycle a freed page table page. */
3027 m_pc->wire_count = 1;
3029 pmap_free_zero_pages(&free);
3034 * free the pv_entry back to the free list
3037 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3039 struct pv_chunk *pc;
3040 int idx, field, bit;
3042 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3043 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3044 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3045 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3046 pc = pv_to_chunk(pv);
3047 idx = pv - &pc->pc_pventry[0];
3050 pc->pc_map[field] |= 1ul << bit;
3051 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3052 pc->pc_map[2] != PC_FREE2) {
3053 /* 98% of the time, pc is already at the head of the list. */
3054 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3055 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3056 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3060 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3065 free_pv_chunk(struct pv_chunk *pc)
3069 mtx_lock(&pv_chunks_mutex);
3070 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3071 mtx_unlock(&pv_chunks_mutex);
3072 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3073 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3074 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3075 /* entire chunk is free, return it */
3076 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3077 dump_drop_page(m->phys_addr);
3078 vm_page_unwire(m, PQ_NONE);
3083 * Returns a new PV entry, allocating a new PV chunk from the system when
3084 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3085 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3088 * The given PV list lock may be released.
3091 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3095 struct pv_chunk *pc;
3098 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3099 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3101 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3103 for (field = 0; field < _NPCM; field++) {
3104 if (pc->pc_map[field]) {
3105 bit = bsfq(pc->pc_map[field]);
3109 if (field < _NPCM) {
3110 pv = &pc->pc_pventry[field * 64 + bit];
3111 pc->pc_map[field] &= ~(1ul << bit);
3112 /* If this was the last item, move it to tail */
3113 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3114 pc->pc_map[2] == 0) {
3115 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3116 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3119 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3120 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3124 /* No free items, allocate another chunk */
3125 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3128 if (lockp == NULL) {
3129 PV_STAT(pc_chunk_tryfail++);
3132 m = reclaim_pv_chunk(pmap, lockp);
3136 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3137 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3138 dump_add_page(m->phys_addr);
3139 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3141 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3142 pc->pc_map[1] = PC_FREE1;
3143 pc->pc_map[2] = PC_FREE2;
3144 mtx_lock(&pv_chunks_mutex);
3145 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3146 mtx_unlock(&pv_chunks_mutex);
3147 pv = &pc->pc_pventry[0];
3148 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3149 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3150 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3155 * Returns the number of one bits within the given PV chunk map.
3157 * The erratas for Intel processors state that "POPCNT Instruction May
3158 * Take Longer to Execute Than Expected". It is believed that the
3159 * issue is the spurious dependency on the destination register.
3160 * Provide a hint to the register rename logic that the destination
3161 * value is overwritten, by clearing it, as suggested in the
3162 * optimization manual. It should be cheap for unaffected processors
3165 * Reference numbers for erratas are
3166 * 4th Gen Core: HSD146
3167 * 5th Gen Core: BDM85
3168 * 6th Gen Core: SKL029
3171 popcnt_pc_map_pq(uint64_t *map)
3175 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3176 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3177 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3178 : "=&r" (result), "=&r" (tmp)
3179 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3184 * Ensure that the number of spare PV entries in the specified pmap meets or
3185 * exceeds the given count, "needed".
3187 * The given PV list lock may be released.
3190 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3192 struct pch new_tail;
3193 struct pv_chunk *pc;
3197 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3198 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3201 * Newly allocated PV chunks must be stored in a private list until
3202 * the required number of PV chunks have been allocated. Otherwise,
3203 * reclaim_pv_chunk() could recycle one of these chunks. In
3204 * contrast, these chunks must be added to the pmap upon allocation.
3206 TAILQ_INIT(&new_tail);
3209 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3211 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3212 bit_count((bitstr_t *)pc->pc_map, 0,
3213 sizeof(pc->pc_map) * NBBY, &free);
3216 free = popcnt_pc_map_pq(pc->pc_map);
3220 if (avail >= needed)
3223 for (; avail < needed; avail += _NPCPV) {
3224 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3227 m = reclaim_pv_chunk(pmap, lockp);
3231 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3232 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3233 dump_add_page(m->phys_addr);
3234 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3236 pc->pc_map[0] = PC_FREE0;
3237 pc->pc_map[1] = PC_FREE1;
3238 pc->pc_map[2] = PC_FREE2;
3239 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3240 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3241 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3243 if (!TAILQ_EMPTY(&new_tail)) {
3244 mtx_lock(&pv_chunks_mutex);
3245 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3246 mtx_unlock(&pv_chunks_mutex);
3251 * First find and then remove the pv entry for the specified pmap and virtual
3252 * address from the specified pv list. Returns the pv entry if found and NULL
3253 * otherwise. This operation can be performed on pv lists for either 4KB or
3254 * 2MB page mappings.
3256 static __inline pv_entry_t
3257 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3261 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3262 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3263 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3272 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3273 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3274 * entries for each of the 4KB page mappings.
3277 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3278 struct rwlock **lockp)
3280 struct md_page *pvh;
3281 struct pv_chunk *pc;
3283 vm_offset_t va_last;
3287 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3288 KASSERT((pa & PDRMASK) == 0,
3289 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3290 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3293 * Transfer the 2mpage's pv entry for this mapping to the first
3294 * page's pv list. Once this transfer begins, the pv list lock
3295 * must not be released until the last pv entry is reinstantiated.
3297 pvh = pa_to_pvh(pa);
3298 va = trunc_2mpage(va);
3299 pv = pmap_pvh_remove(pvh, pmap, va);
3300 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3301 m = PHYS_TO_VM_PAGE(pa);
3302 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3304 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3305 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3306 va_last = va + NBPDR - PAGE_SIZE;
3308 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3309 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3310 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3311 for (field = 0; field < _NPCM; field++) {
3312 while (pc->pc_map[field]) {
3313 bit = bsfq(pc->pc_map[field]);
3314 pc->pc_map[field] &= ~(1ul << bit);
3315 pv = &pc->pc_pventry[field * 64 + bit];
3319 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3320 ("pmap_pv_demote_pde: page %p is not managed", m));
3321 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3327 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3328 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3331 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3332 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3333 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3335 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3336 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3340 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3341 * replace the many pv entries for the 4KB page mappings by a single pv entry
3342 * for the 2MB page mapping.
3345 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3346 struct rwlock **lockp)
3348 struct md_page *pvh;
3350 vm_offset_t va_last;
3353 KASSERT((pa & PDRMASK) == 0,
3354 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3355 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3358 * Transfer the first page's pv entry for this mapping to the 2mpage's
3359 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3360 * a transfer avoids the possibility that get_pv_entry() calls
3361 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3362 * mappings that is being promoted.
3364 m = PHYS_TO_VM_PAGE(pa);
3365 va = trunc_2mpage(va);
3366 pv = pmap_pvh_remove(&m->md, pmap, va);
3367 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3368 pvh = pa_to_pvh(pa);
3369 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3371 /* Free the remaining NPTEPG - 1 pv entries. */
3372 va_last = va + NBPDR - PAGE_SIZE;
3376 pmap_pvh_free(&m->md, pmap, va);
3377 } while (va < va_last);
3381 * First find and then destroy the pv entry for the specified pmap and virtual
3382 * address. This operation can be performed on pv lists for either 4KB or 2MB
3386 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3390 pv = pmap_pvh_remove(pvh, pmap, va);
3391 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3392 free_pv_entry(pmap, pv);
3396 * Conditionally create the PV entry for a 4KB page mapping if the required
3397 * memory can be allocated without resorting to reclamation.
3400 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3401 struct rwlock **lockp)
3405 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3406 /* Pass NULL instead of the lock pointer to disable reclamation. */
3407 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3409 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3410 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3418 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3419 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3420 * false if the PV entry cannot be allocated without resorting to reclamation.
3423 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
3424 struct rwlock **lockp)
3426 struct md_page *pvh;
3430 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3431 /* Pass NULL instead of the lock pointer to disable reclamation. */
3432 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3433 NULL : lockp)) == NULL)
3436 pa = pde & PG_PS_FRAME;
3437 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3438 pvh = pa_to_pvh(pa);
3439 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3445 * Fills a page table page with mappings to consecutive physical pages.
3448 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3452 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3454 newpte += PAGE_SIZE;
3459 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3460 * mapping is invalidated.
3463 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3465 struct rwlock *lock;
3469 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3476 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3477 struct rwlock **lockp)
3479 pd_entry_t newpde, oldpde;
3480 pt_entry_t *firstpte, newpte;
3481 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3484 struct spglist free;
3488 PG_G = pmap_global_bit(pmap);
3489 PG_A = pmap_accessed_bit(pmap);
3490 PG_M = pmap_modified_bit(pmap);
3491 PG_RW = pmap_rw_bit(pmap);
3492 PG_V = pmap_valid_bit(pmap);
3493 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3495 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3497 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3498 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3499 if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
3501 KASSERT((oldpde & PG_W) == 0,
3502 ("pmap_demote_pde: page table page for a wired mapping"
3506 * Invalidate the 2MB page mapping and return "failure" if the
3507 * mapping was never accessed or the allocation of the new
3508 * page table page fails. If the 2MB page mapping belongs to
3509 * the direct map region of the kernel's address space, then
3510 * the page allocation request specifies the highest possible
3511 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3512 * normal. Page table pages are preallocated for every other
3513 * part of the kernel address space, so the direct map region
3514 * is the only part of the kernel address space that must be
3517 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3518 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3519 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3520 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3522 sva = trunc_2mpage(va);
3523 pmap_remove_pde(pmap, pde, sva, &free, lockp);
3524 if ((oldpde & PG_G) == 0)
3525 pmap_invalidate_pde_page(pmap, sva, oldpde);
3526 pmap_free_zero_pages(&free);
3527 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3528 " in pmap %p", va, pmap);
3531 if (va < VM_MAXUSER_ADDRESS)
3532 pmap_resident_count_inc(pmap, 1);
3534 mptepa = VM_PAGE_TO_PHYS(mpte);
3535 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3536 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3537 KASSERT((oldpde & PG_A) != 0,
3538 ("pmap_demote_pde: oldpde is missing PG_A"));
3539 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3540 ("pmap_demote_pde: oldpde is missing PG_M"));
3541 newpte = oldpde & ~PG_PS;
3542 newpte = pmap_swap_pat(pmap, newpte);
3545 * If the page table page is new, initialize it.
3547 if (mpte->wire_count == 1) {
3548 mpte->wire_count = NPTEPG;
3549 pmap_fill_ptp(firstpte, newpte);
3551 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3552 ("pmap_demote_pde: firstpte and newpte map different physical"
3556 * If the mapping has changed attributes, update the page table
3559 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3560 pmap_fill_ptp(firstpte, newpte);
3563 * The spare PV entries must be reserved prior to demoting the
3564 * mapping, that is, prior to changing the PDE. Otherwise, the state
3565 * of the PDE and the PV lists will be inconsistent, which can result
3566 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3567 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3568 * PV entry for the 2MB page mapping that is being demoted.
3570 if ((oldpde & PG_MANAGED) != 0)
3571 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3574 * Demote the mapping. This pmap is locked. The old PDE has
3575 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3576 * set. Thus, there is no danger of a race with another
3577 * processor changing the setting of PG_A and/or PG_M between
3578 * the read above and the store below.
3580 if (workaround_erratum383)
3581 pmap_update_pde(pmap, va, pde, newpde);
3583 pde_store(pde, newpde);
3586 * Invalidate a stale recursive mapping of the page table page.
3588 if (va >= VM_MAXUSER_ADDRESS)
3589 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3592 * Demote the PV entry.
3594 if ((oldpde & PG_MANAGED) != 0)
3595 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3597 atomic_add_long(&pmap_pde_demotions, 1);
3598 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3599 " in pmap %p", va, pmap);
3604 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3607 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3613 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3614 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3615 mpte = pmap_remove_pt_page(pmap, va);
3617 panic("pmap_remove_kernel_pde: Missing pt page.");
3619 mptepa = VM_PAGE_TO_PHYS(mpte);
3620 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3623 * Initialize the page table page.
3625 pagezero((void *)PHYS_TO_DMAP(mptepa));
3628 * Demote the mapping.
3630 if (workaround_erratum383)
3631 pmap_update_pde(pmap, va, pde, newpde);
3633 pde_store(pde, newpde);
3636 * Invalidate a stale recursive mapping of the page table page.
3638 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3642 * pmap_remove_pde: do the things to unmap a superpage in a process
3645 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
3646 struct spglist *free, struct rwlock **lockp)
3648 struct md_page *pvh;
3650 vm_offset_t eva, va;
3652 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3654 PG_G = pmap_global_bit(pmap);
3655 PG_A = pmap_accessed_bit(pmap);
3656 PG_M = pmap_modified_bit(pmap);
3657 PG_RW = pmap_rw_bit(pmap);
3659 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3660 KASSERT((sva & PDRMASK) == 0,
3661 ("pmap_remove_pde: sva is not 2mpage aligned"));
3662 oldpde = pte_load_clear(pdq);
3664 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
3665 if ((oldpde & PG_G) != 0)
3666 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
3667 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
3668 if (oldpde & PG_MANAGED) {
3669 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
3670 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
3671 pmap_pvh_free(pvh, pmap, sva);
3673 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3674 va < eva; va += PAGE_SIZE, m++) {
3675 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3678 vm_page_aflag_set(m, PGA_REFERENCED);
3679 if (TAILQ_EMPTY(&m->md.pv_list) &&
3680 TAILQ_EMPTY(&pvh->pv_list))
3681 vm_page_aflag_clear(m, PGA_WRITEABLE);
3682 pmap_delayed_invl_page(m);
3685 if (pmap == kernel_pmap) {
3686 pmap_remove_kernel_pde(pmap, pdq, sva);
3688 mpte = pmap_remove_pt_page(pmap, sva);
3690 pmap_resident_count_dec(pmap, 1);
3691 KASSERT(mpte->wire_count == NPTEPG,
3692 ("pmap_remove_pde: pte page wire count error"));
3693 mpte->wire_count = 0;
3694 pmap_add_delayed_free_list(mpte, free, FALSE);
3697 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
3701 * pmap_remove_pte: do the things to unmap a page in a process
3704 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
3705 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
3707 struct md_page *pvh;
3708 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
3711 PG_A = pmap_accessed_bit(pmap);
3712 PG_M = pmap_modified_bit(pmap);
3713 PG_RW = pmap_rw_bit(pmap);
3715 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3716 oldpte = pte_load_clear(ptq);
3718 pmap->pm_stats.wired_count -= 1;
3719 pmap_resident_count_dec(pmap, 1);
3720 if (oldpte & PG_MANAGED) {
3721 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
3722 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3725 vm_page_aflag_set(m, PGA_REFERENCED);
3726 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3727 pmap_pvh_free(&m->md, pmap, va);
3728 if (TAILQ_EMPTY(&m->md.pv_list) &&
3729 (m->flags & PG_FICTITIOUS) == 0) {
3730 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3731 if (TAILQ_EMPTY(&pvh->pv_list))
3732 vm_page_aflag_clear(m, PGA_WRITEABLE);
3734 pmap_delayed_invl_page(m);
3736 return (pmap_unuse_pt(pmap, va, ptepde, free));
3740 * Remove a single page from a process address space
3743 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
3744 struct spglist *free)
3746 struct rwlock *lock;
3747 pt_entry_t *pte, PG_V;
3749 PG_V = pmap_valid_bit(pmap);
3750 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3751 if ((*pde & PG_V) == 0)
3753 pte = pmap_pde_to_pte(pde, va);
3754 if ((*pte & PG_V) == 0)
3757 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
3760 pmap_invalidate_page(pmap, va);
3764 * Removes the specified range of addresses from the page table page.
3767 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
3768 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
3770 pt_entry_t PG_G, *pte;
3774 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3775 PG_G = pmap_global_bit(pmap);
3778 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
3782 pmap_invalidate_range(pmap, va, sva);
3787 if ((*pte & PG_G) == 0)
3791 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
3797 pmap_invalidate_range(pmap, va, sva);
3802 * Remove the given range of addresses from the specified map.
3804 * It is assumed that the start and end are properly
3805 * rounded to the page size.
3808 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3810 struct rwlock *lock;
3811 vm_offset_t va_next;
3812 pml4_entry_t *pml4e;
3814 pd_entry_t ptpaddr, *pde;
3815 pt_entry_t PG_G, PG_V;
3816 struct spglist free;
3819 PG_G = pmap_global_bit(pmap);
3820 PG_V = pmap_valid_bit(pmap);
3823 * Perform an unsynchronized read. This is, however, safe.
3825 if (pmap->pm_stats.resident_count == 0)
3831 pmap_delayed_invl_started();
3835 * special handling of removing one page. a very
3836 * common operation and easy to short circuit some
3839 if (sva + PAGE_SIZE == eva) {
3840 pde = pmap_pde(pmap, sva);
3841 if (pde && (*pde & PG_PS) == 0) {
3842 pmap_remove_page(pmap, sva, pde, &free);
3848 for (; sva < eva; sva = va_next) {
3850 if (pmap->pm_stats.resident_count == 0)
3853 pml4e = pmap_pml4e(pmap, sva);
3854 if ((*pml4e & PG_V) == 0) {
3855 va_next = (sva + NBPML4) & ~PML4MASK;
3861 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
3862 if ((*pdpe & PG_V) == 0) {
3863 va_next = (sva + NBPDP) & ~PDPMASK;
3870 * Calculate index for next page table.
3872 va_next = (sva + NBPDR) & ~PDRMASK;
3876 pde = pmap_pdpe_to_pde(pdpe, sva);
3880 * Weed out invalid mappings.
3886 * Check for large page.
3888 if ((ptpaddr & PG_PS) != 0) {
3890 * Are we removing the entire large page? If not,
3891 * demote the mapping and fall through.
3893 if (sva + NBPDR == va_next && eva >= va_next) {
3895 * The TLB entry for a PG_G mapping is
3896 * invalidated by pmap_remove_pde().
3898 if ((ptpaddr & PG_G) == 0)
3900 pmap_remove_pde(pmap, pde, sva, &free, &lock);
3902 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
3904 /* The large page mapping was destroyed. */
3911 * Limit our scan to either the end of the va represented
3912 * by the current page table page, or to the end of the
3913 * range being removed.
3918 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
3925 pmap_invalidate_all(pmap);
3927 pmap_delayed_invl_finished();
3928 pmap_free_zero_pages(&free);
3932 * Routine: pmap_remove_all
3934 * Removes this physical page from
3935 * all physical maps in which it resides.
3936 * Reflects back modify bits to the pager.
3939 * Original versions of this routine were very
3940 * inefficient because they iteratively called
3941 * pmap_remove (slow...)
3945 pmap_remove_all(vm_page_t m)
3947 struct md_page *pvh;
3950 struct rwlock *lock;
3951 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
3954 struct spglist free;
3955 int pvh_gen, md_gen;
3957 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3958 ("pmap_remove_all: page %p is not managed", m));
3960 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3961 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
3962 pa_to_pvh(VM_PAGE_TO_PHYS(m));
3965 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
3967 if (!PMAP_TRYLOCK(pmap)) {
3968 pvh_gen = pvh->pv_gen;
3972 if (pvh_gen != pvh->pv_gen) {
3979 pde = pmap_pde(pmap, va);
3980 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
3983 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3985 if (!PMAP_TRYLOCK(pmap)) {
3986 pvh_gen = pvh->pv_gen;
3987 md_gen = m->md.pv_gen;
3991 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
3997 PG_A = pmap_accessed_bit(pmap);
3998 PG_M = pmap_modified_bit(pmap);
3999 PG_RW = pmap_rw_bit(pmap);
4000 pmap_resident_count_dec(pmap, 1);
4001 pde = pmap_pde(pmap, pv->pv_va);
4002 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
4003 " a 2mpage in page %p's pv list", m));
4004 pte = pmap_pde_to_pte(pde, pv->pv_va);
4005 tpte = pte_load_clear(pte);
4007 pmap->pm_stats.wired_count--;
4009 vm_page_aflag_set(m, PGA_REFERENCED);
4012 * Update the vm_page_t clean and reference bits.
4014 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4016 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
4017 pmap_invalidate_page(pmap, pv->pv_va);
4018 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4020 free_pv_entry(pmap, pv);
4023 vm_page_aflag_clear(m, PGA_WRITEABLE);
4025 pmap_delayed_invl_wait(m);
4026 pmap_free_zero_pages(&free);
4030 * pmap_protect_pde: do the things to protect a 2mpage in a process
4033 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
4035 pd_entry_t newpde, oldpde;
4036 vm_offset_t eva, va;
4038 boolean_t anychanged;
4039 pt_entry_t PG_G, PG_M, PG_RW;
4041 PG_G = pmap_global_bit(pmap);
4042 PG_M = pmap_modified_bit(pmap);
4043 PG_RW = pmap_rw_bit(pmap);
4045 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4046 KASSERT((sva & PDRMASK) == 0,
4047 ("pmap_protect_pde: sva is not 2mpage aligned"));
4050 oldpde = newpde = *pde;
4051 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4052 (PG_MANAGED | PG_M | PG_RW)) {
4054 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4055 va < eva; va += PAGE_SIZE, m++)
4058 if ((prot & VM_PROT_WRITE) == 0)
4059 newpde &= ~(PG_RW | PG_M);
4060 if ((prot & VM_PROT_EXECUTE) == 0)
4062 if (newpde != oldpde) {
4064 * As an optimization to future operations on this PDE, clear
4065 * PG_PROMOTED. The impending invalidation will remove any
4066 * lingering 4KB page mappings from the TLB.
4068 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
4070 if ((oldpde & PG_G) != 0)
4071 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4075 return (anychanged);
4079 * Set the physical protection on the
4080 * specified range of this map as requested.
4083 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4085 vm_offset_t va_next;
4086 pml4_entry_t *pml4e;
4088 pd_entry_t ptpaddr, *pde;
4089 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4090 boolean_t anychanged;
4092 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4093 if (prot == VM_PROT_NONE) {
4094 pmap_remove(pmap, sva, eva);
4098 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4099 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4102 PG_G = pmap_global_bit(pmap);
4103 PG_M = pmap_modified_bit(pmap);
4104 PG_V = pmap_valid_bit(pmap);
4105 PG_RW = pmap_rw_bit(pmap);
4109 * Although this function delays and batches the invalidation
4110 * of stale TLB entries, it does not need to call
4111 * pmap_delayed_invl_started() and
4112 * pmap_delayed_invl_finished(), because it does not
4113 * ordinarily destroy mappings. Stale TLB entries from
4114 * protection-only changes need only be invalidated before the
4115 * pmap lock is released, because protection-only changes do
4116 * not destroy PV entries. Even operations that iterate over
4117 * a physical page's PV list of mappings, like
4118 * pmap_remove_write(), acquire the pmap lock for each
4119 * mapping. Consequently, for protection-only changes, the
4120 * pmap lock suffices to synchronize both page table and TLB
4123 * This function only destroys a mapping if pmap_demote_pde()
4124 * fails. In that case, stale TLB entries are immediately
4129 for (; sva < eva; sva = va_next) {
4131 pml4e = pmap_pml4e(pmap, sva);
4132 if ((*pml4e & PG_V) == 0) {
4133 va_next = (sva + NBPML4) & ~PML4MASK;
4139 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4140 if ((*pdpe & PG_V) == 0) {
4141 va_next = (sva + NBPDP) & ~PDPMASK;
4147 va_next = (sva + NBPDR) & ~PDRMASK;
4151 pde = pmap_pdpe_to_pde(pdpe, sva);
4155 * Weed out invalid mappings.
4161 * Check for large page.
4163 if ((ptpaddr & PG_PS) != 0) {
4165 * Are we protecting the entire large page? If not,
4166 * demote the mapping and fall through.
4168 if (sva + NBPDR == va_next && eva >= va_next) {
4170 * The TLB entry for a PG_G mapping is
4171 * invalidated by pmap_protect_pde().
4173 if (pmap_protect_pde(pmap, pde, sva, prot))
4176 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4178 * The large page mapping was destroyed.
4187 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4189 pt_entry_t obits, pbits;
4193 obits = pbits = *pte;
4194 if ((pbits & PG_V) == 0)
4197 if ((prot & VM_PROT_WRITE) == 0) {
4198 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4199 (PG_MANAGED | PG_M | PG_RW)) {
4200 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4203 pbits &= ~(PG_RW | PG_M);
4205 if ((prot & VM_PROT_EXECUTE) == 0)
4208 if (pbits != obits) {
4209 if (!atomic_cmpset_long(pte, obits, pbits))
4212 pmap_invalidate_page(pmap, sva);
4219 pmap_invalidate_all(pmap);
4224 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4225 * single page table page (PTP) to a single 2MB page mapping. For promotion
4226 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4227 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4228 * identical characteristics.
4231 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4232 struct rwlock **lockp)
4235 pt_entry_t *firstpte, oldpte, pa, *pte;
4236 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4240 PG_A = pmap_accessed_bit(pmap);
4241 PG_G = pmap_global_bit(pmap);
4242 PG_M = pmap_modified_bit(pmap);
4243 PG_V = pmap_valid_bit(pmap);
4244 PG_RW = pmap_rw_bit(pmap);
4245 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4247 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4250 * Examine the first PTE in the specified PTP. Abort if this PTE is
4251 * either invalid, unused, or does not map the first 4KB physical page
4252 * within a 2MB page.
4254 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4257 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4258 atomic_add_long(&pmap_pde_p_failures, 1);
4259 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4260 " in pmap %p", va, pmap);
4263 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4265 * When PG_M is already clear, PG_RW can be cleared without
4266 * a TLB invalidation.
4268 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4274 * Examine each of the other PTEs in the specified PTP. Abort if this
4275 * PTE maps an unexpected 4KB physical page or does not have identical
4276 * characteristics to the first PTE.
4278 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4279 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4282 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4283 atomic_add_long(&pmap_pde_p_failures, 1);
4284 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4285 " in pmap %p", va, pmap);
4288 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4290 * When PG_M is already clear, PG_RW can be cleared
4291 * without a TLB invalidation.
4293 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4296 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4297 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4298 (va & ~PDRMASK), pmap);
4300 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4301 atomic_add_long(&pmap_pde_p_failures, 1);
4302 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4303 " in pmap %p", va, pmap);
4310 * Save the page table page in its current state until the PDE
4311 * mapping the superpage is demoted by pmap_demote_pde() or
4312 * destroyed by pmap_remove_pde().
4314 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4315 KASSERT(mpte >= vm_page_array &&
4316 mpte < &vm_page_array[vm_page_array_size],
4317 ("pmap_promote_pde: page table page is out of range"));
4318 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4319 ("pmap_promote_pde: page table page's pindex is wrong"));
4320 if (pmap_insert_pt_page(pmap, mpte)) {
4321 atomic_add_long(&pmap_pde_p_failures, 1);
4323 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4329 * Promote the pv entries.
4331 if ((newpde & PG_MANAGED) != 0)
4332 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4335 * Propagate the PAT index to its proper position.
4337 newpde = pmap_swap_pat(pmap, newpde);
4340 * Map the superpage.
4342 if (workaround_erratum383)
4343 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4345 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
4347 atomic_add_long(&pmap_pde_promotions, 1);
4348 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4349 " in pmap %p", va, pmap);
4353 * Insert the given physical page (p) at
4354 * the specified virtual address (v) in the
4355 * target physical map with the protection requested.
4357 * If specified, the page will be wired down, meaning
4358 * that the related pte can not be reclaimed.
4360 * NB: This is the only routine which MAY NOT lazy-evaluate
4361 * or lose information. That is, this routine must actually
4362 * insert this page into the given map NOW.
4364 * When destroying both a page table and PV entry, this function
4365 * performs the TLB invalidation before releasing the PV list
4366 * lock, so we do not need pmap_delayed_invl_page() calls here.
4369 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4370 u_int flags, int8_t psind)
4372 struct rwlock *lock;
4374 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4375 pt_entry_t newpte, origpte;
4382 PG_A = pmap_accessed_bit(pmap);
4383 PG_G = pmap_global_bit(pmap);
4384 PG_M = pmap_modified_bit(pmap);
4385 PG_V = pmap_valid_bit(pmap);
4386 PG_RW = pmap_rw_bit(pmap);
4388 va = trunc_page(va);
4389 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4390 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4391 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4393 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4394 va >= kmi.clean_eva,
4395 ("pmap_enter: managed mapping within the clean submap"));
4396 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4397 VM_OBJECT_ASSERT_LOCKED(m->object);
4398 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
4399 ("pmap_enter: flags %u has reserved bits set", flags));
4400 pa = VM_PAGE_TO_PHYS(m);
4401 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4402 if ((flags & VM_PROT_WRITE) != 0)
4404 if ((prot & VM_PROT_WRITE) != 0)
4406 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4407 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4408 if ((prot & VM_PROT_EXECUTE) == 0)
4410 if ((flags & PMAP_ENTER_WIRED) != 0)
4412 if (va < VM_MAXUSER_ADDRESS)
4414 if (pmap == kernel_pmap)
4416 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
4419 * Set modified bit gratuitously for writeable mappings if
4420 * the page is unmanaged. We do not want to take a fault
4421 * to do the dirty bit accounting for these mappings.
4423 if ((m->oflags & VPO_UNMANAGED) != 0) {
4424 if ((newpte & PG_RW) != 0)
4427 newpte |= PG_MANAGED;
4432 /* Assert the required virtual and physical alignment. */
4433 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
4434 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4435 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
4441 * In the case that a page table page is not
4442 * resident, we are creating it here.
4445 pde = pmap_pde(pmap, va);
4446 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4447 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4448 pte = pmap_pde_to_pte(pde, va);
4449 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4450 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4453 } else if (va < VM_MAXUSER_ADDRESS) {
4455 * Here if the pte page isn't mapped, or if it has been
4458 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4459 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4460 nosleep ? NULL : &lock);
4461 if (mpte == NULL && nosleep) {
4462 rv = KERN_RESOURCE_SHORTAGE;
4467 panic("pmap_enter: invalid page directory va=%#lx", va);
4472 * Is the specified virtual address already mapped?
4474 if ((origpte & PG_V) != 0) {
4476 * Wiring change, just update stats. We don't worry about
4477 * wiring PT pages as they remain resident as long as there
4478 * are valid mappings in them. Hence, if a user page is wired,
4479 * the PT page will be also.
4481 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4482 pmap->pm_stats.wired_count++;
4483 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4484 pmap->pm_stats.wired_count--;
4487 * Remove the extra PT page reference.
4491 KASSERT(mpte->wire_count > 0,
4492 ("pmap_enter: missing reference to page table page,"
4497 * Has the physical page changed?
4499 opa = origpte & PG_FRAME;
4502 * No, might be a protection or wiring change.
4504 if ((origpte & PG_MANAGED) != 0 &&
4505 (newpte & PG_RW) != 0)
4506 vm_page_aflag_set(m, PGA_WRITEABLE);
4507 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4513 * Increment the counters.
4515 if ((newpte & PG_W) != 0)
4516 pmap->pm_stats.wired_count++;
4517 pmap_resident_count_inc(pmap, 1);
4521 * Enter on the PV list if part of our managed memory.
4523 if ((newpte & PG_MANAGED) != 0) {
4524 pv = get_pv_entry(pmap, &lock);
4526 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4527 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4529 if ((newpte & PG_RW) != 0)
4530 vm_page_aflag_set(m, PGA_WRITEABLE);
4536 if ((origpte & PG_V) != 0) {
4538 origpte = pte_load_store(pte, newpte);
4539 opa = origpte & PG_FRAME;
4541 if ((origpte & PG_MANAGED) != 0) {
4542 om = PHYS_TO_VM_PAGE(opa);
4543 if ((origpte & (PG_M | PG_RW)) == (PG_M |
4546 if ((origpte & PG_A) != 0)
4547 vm_page_aflag_set(om, PGA_REFERENCED);
4548 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4549 pmap_pvh_free(&om->md, pmap, va);
4550 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4551 TAILQ_EMPTY(&om->md.pv_list) &&
4552 ((om->flags & PG_FICTITIOUS) != 0 ||
4553 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4554 vm_page_aflag_clear(om, PGA_WRITEABLE);
4556 } else if ((newpte & PG_M) == 0 && (origpte & (PG_M |
4557 PG_RW)) == (PG_M | PG_RW)) {
4558 if ((origpte & PG_MANAGED) != 0)
4562 * Although the PTE may still have PG_RW set, TLB
4563 * invalidation may nonetheless be required because
4564 * the PTE no longer has PG_M set.
4566 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4568 * This PTE change does not require TLB invalidation.
4572 if ((origpte & PG_A) != 0)
4573 pmap_invalidate_page(pmap, va);
4575 pte_store(pte, newpte);
4580 * If both the page table page and the reservation are fully
4581 * populated, then attempt promotion.
4583 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4584 pmap_ps_enabled(pmap) &&
4585 (m->flags & PG_FICTITIOUS) == 0 &&
4586 vm_reserv_level_iffullpop(m) == 0)
4587 pmap_promote_pde(pmap, pde, va, &lock);
4598 * Tries to create a read- and/or execute-only 2MB page mapping. Returns true
4599 * if successful. Returns false if (1) a page table page cannot be allocated
4600 * without sleeping, (2) a mapping already exists at the specified virtual
4601 * address, or (3) a PV entry cannot be allocated without reclaiming another
4605 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4606 struct rwlock **lockp)
4611 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4612 PG_V = pmap_valid_bit(pmap);
4613 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
4615 if ((m->oflags & VPO_UNMANAGED) == 0)
4616 newpde |= PG_MANAGED;
4617 if ((prot & VM_PROT_EXECUTE) == 0)
4619 if (va < VM_MAXUSER_ADDRESS)
4621 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
4622 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
4627 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
4628 * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
4629 * otherwise. Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
4630 * a mapping already exists at the specified virtual address. Returns
4631 * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
4632 * page allocation failed. Returns KERN_RESOURCE_SHORTAGE if
4633 * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
4635 * The parameter "m" is only used when creating a managed, writeable mapping.
4638 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
4639 vm_page_t m, struct rwlock **lockp)
4641 struct spglist free;
4642 pd_entry_t oldpde, *pde;
4643 pt_entry_t PG_G, PG_RW, PG_V;
4646 PG_G = pmap_global_bit(pmap);
4647 PG_RW = pmap_rw_bit(pmap);
4648 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
4649 ("pmap_enter_pde: newpde is missing PG_M"));
4650 PG_V = pmap_valid_bit(pmap);
4651 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4653 if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
4654 NULL : lockp)) == NULL) {
4655 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4656 " in pmap %p", va, pmap);
4657 return (KERN_RESOURCE_SHORTAGE);
4659 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4660 pde = &pde[pmap_pde_index(va)];
4662 if ((oldpde & PG_V) != 0) {
4663 KASSERT(pdpg->wire_count > 1,
4664 ("pmap_enter_pde: pdpg's wire count is too low"));
4665 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
4667 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4668 " in pmap %p", va, pmap);
4669 return (KERN_FAILURE);
4671 /* Break the existing mapping(s). */
4673 if ((oldpde & PG_PS) != 0) {
4675 * The reference to the PD page that was acquired by
4676 * pmap_allocpde() ensures that it won't be freed.
4677 * However, if the PDE resulted from a promotion, then
4678 * a reserved PT page could be freed.
4680 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
4681 if ((oldpde & PG_G) == 0)
4682 pmap_invalidate_pde_page(pmap, va, oldpde);
4684 pmap_delayed_invl_started();
4685 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
4687 pmap_invalidate_all(pmap);
4688 pmap_delayed_invl_finished();
4690 pmap_free_zero_pages(&free);
4691 if (va >= VM_MAXUSER_ADDRESS) {
4692 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4693 if (pmap_insert_pt_page(pmap, mt)) {
4695 * XXX Currently, this can't happen because
4696 * we do not perform pmap_enter(psind == 1)
4697 * on the kernel pmap.
4699 panic("pmap_enter_pde: trie insert failed");
4702 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
4705 if ((newpde & PG_MANAGED) != 0) {
4707 * Abort this mapping if its PV entry could not be created.
4709 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
4711 if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
4713 * Although "va" is not mapped, paging-
4714 * structure caches could nonetheless have
4715 * entries that refer to the freed page table
4716 * pages. Invalidate those entries.
4718 pmap_invalidate_page(pmap, va);
4719 pmap_free_zero_pages(&free);
4721 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4722 " in pmap %p", va, pmap);
4723 return (KERN_RESOURCE_SHORTAGE);
4725 if ((newpde & PG_RW) != 0) {
4726 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
4727 vm_page_aflag_set(mt, PGA_WRITEABLE);
4732 * Increment counters.
4734 if ((newpde & PG_W) != 0)
4735 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
4736 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
4739 * Map the superpage. (This is not a promoted mapping; there will not
4740 * be any lingering 4KB page mappings in the TLB.)
4742 pde_store(pde, newpde);
4744 atomic_add_long(&pmap_pde_mappings, 1);
4745 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
4746 " in pmap %p", va, pmap);
4747 return (KERN_SUCCESS);
4751 * Maps a sequence of resident pages belonging to the same object.
4752 * The sequence begins with the given page m_start. This page is
4753 * mapped at the given virtual address start. Each subsequent page is
4754 * mapped at a virtual address that is offset from start by the same
4755 * amount as the page is offset from m_start within the object. The
4756 * last page in the sequence is the page with the largest offset from
4757 * m_start that can be mapped at a virtual address less than the given
4758 * virtual address end. Not every virtual page between start and end
4759 * is mapped; only those for which a resident page exists with the
4760 * corresponding offset from m_start are mapped.
4763 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
4764 vm_page_t m_start, vm_prot_t prot)
4766 struct rwlock *lock;
4769 vm_pindex_t diff, psize;
4771 VM_OBJECT_ASSERT_LOCKED(m_start->object);
4773 psize = atop(end - start);
4778 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
4779 va = start + ptoa(diff);
4780 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
4781 m->psind == 1 && pmap_ps_enabled(pmap) &&
4782 pmap_enter_2mpage(pmap, va, m, prot, &lock))
4783 m = &m[NBPDR / PAGE_SIZE - 1];
4785 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
4787 m = TAILQ_NEXT(m, listq);
4795 * this code makes some *MAJOR* assumptions:
4796 * 1. Current pmap & pmap exists.
4799 * 4. No page table pages.
4800 * but is *MUCH* faster than pmap_enter...
4804 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
4806 struct rwlock *lock;
4810 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
4817 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
4818 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
4820 struct spglist free;
4821 pt_entry_t *pte, PG_V;
4824 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
4825 (m->oflags & VPO_UNMANAGED) != 0,
4826 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
4827 PG_V = pmap_valid_bit(pmap);
4828 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4831 * In the case that a page table page is not
4832 * resident, we are creating it here.
4834 if (va < VM_MAXUSER_ADDRESS) {
4835 vm_pindex_t ptepindex;
4839 * Calculate pagetable page index
4841 ptepindex = pmap_pde_pindex(va);
4842 if (mpte && (mpte->pindex == ptepindex)) {
4846 * Get the page directory entry
4848 ptepa = pmap_pde(pmap, va);
4851 * If the page table page is mapped, we just increment
4852 * the hold count, and activate it. Otherwise, we
4853 * attempt to allocate a page table page. If this
4854 * attempt fails, we don't retry. Instead, we give up.
4856 if (ptepa && (*ptepa & PG_V) != 0) {
4859 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
4863 * Pass NULL instead of the PV list lock
4864 * pointer, because we don't intend to sleep.
4866 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
4871 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
4872 pte = &pte[pmap_pte_index(va)];
4886 * Enter on the PV list if part of our managed memory.
4888 if ((m->oflags & VPO_UNMANAGED) == 0 &&
4889 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
4892 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
4894 * Although "va" is not mapped, paging-
4895 * structure caches could nonetheless have
4896 * entries that refer to the freed page table
4897 * pages. Invalidate those entries.
4899 pmap_invalidate_page(pmap, va);
4900 pmap_free_zero_pages(&free);
4908 * Increment counters
4910 pmap_resident_count_inc(pmap, 1);
4912 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
4913 if ((prot & VM_PROT_EXECUTE) == 0)
4917 * Now validate mapping with RO protection
4919 if ((m->oflags & VPO_UNMANAGED) != 0)
4920 pte_store(pte, pa | PG_V | PG_U);
4922 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
4927 * Make a temporary mapping for a physical address. This is only intended
4928 * to be used for panic dumps.
4931 pmap_kenter_temporary(vm_paddr_t pa, int i)
4935 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
4936 pmap_kenter(va, pa);
4938 return ((void *)crashdumpmap);
4942 * This code maps large physical mmap regions into the
4943 * processor address space. Note that some shortcuts
4944 * are taken, but the code works.
4947 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
4948 vm_pindex_t pindex, vm_size_t size)
4951 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
4952 vm_paddr_t pa, ptepa;
4956 PG_A = pmap_accessed_bit(pmap);
4957 PG_M = pmap_modified_bit(pmap);
4958 PG_V = pmap_valid_bit(pmap);
4959 PG_RW = pmap_rw_bit(pmap);
4961 VM_OBJECT_ASSERT_WLOCKED(object);
4962 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
4963 ("pmap_object_init_pt: non-device object"));
4964 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
4965 if (!pmap_ps_enabled(pmap))
4967 if (!vm_object_populate(object, pindex, pindex + atop(size)))
4969 p = vm_page_lookup(object, pindex);
4970 KASSERT(p->valid == VM_PAGE_BITS_ALL,
4971 ("pmap_object_init_pt: invalid page %p", p));
4972 pat_mode = p->md.pat_mode;
4975 * Abort the mapping if the first page is not physically
4976 * aligned to a 2MB page boundary.
4978 ptepa = VM_PAGE_TO_PHYS(p);
4979 if (ptepa & (NBPDR - 1))
4983 * Skip the first page. Abort the mapping if the rest of
4984 * the pages are not physically contiguous or have differing
4985 * memory attributes.
4987 p = TAILQ_NEXT(p, listq);
4988 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
4990 KASSERT(p->valid == VM_PAGE_BITS_ALL,
4991 ("pmap_object_init_pt: invalid page %p", p));
4992 if (pa != VM_PAGE_TO_PHYS(p) ||
4993 pat_mode != p->md.pat_mode)
4995 p = TAILQ_NEXT(p, listq);
4999 * Map using 2MB pages. Since "ptepa" is 2M aligned and
5000 * "size" is a multiple of 2M, adding the PAT setting to "pa"
5001 * will not affect the termination of this loop.
5004 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
5005 pa < ptepa + size; pa += NBPDR) {
5006 pdpg = pmap_allocpde(pmap, addr, NULL);
5009 * The creation of mappings below is only an
5010 * optimization. If a page directory page
5011 * cannot be allocated without blocking,
5012 * continue on to the next mapping rather than
5018 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5019 pde = &pde[pmap_pde_index(addr)];
5020 if ((*pde & PG_V) == 0) {
5021 pde_store(pde, pa | PG_PS | PG_M | PG_A |
5022 PG_U | PG_RW | PG_V);
5023 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5024 atomic_add_long(&pmap_pde_mappings, 1);
5026 /* Continue on if the PDE is already valid. */
5028 KASSERT(pdpg->wire_count > 0,
5029 ("pmap_object_init_pt: missing reference "
5030 "to page directory page, va: 0x%lx", addr));
5039 * Clear the wired attribute from the mappings for the specified range of
5040 * addresses in the given pmap. Every valid mapping within that range
5041 * must have the wired attribute set. In contrast, invalid mappings
5042 * cannot have the wired attribute set, so they are ignored.
5044 * The wired attribute of the page table entry is not a hardware
5045 * feature, so there is no need to invalidate any TLB entries.
5046 * Since pmap_demote_pde() for the wired entry must never fail,
5047 * pmap_delayed_invl_started()/finished() calls around the
5048 * function are not needed.
5051 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5053 vm_offset_t va_next;
5054 pml4_entry_t *pml4e;
5057 pt_entry_t *pte, PG_V;
5059 PG_V = pmap_valid_bit(pmap);
5061 for (; sva < eva; sva = va_next) {
5062 pml4e = pmap_pml4e(pmap, sva);
5063 if ((*pml4e & PG_V) == 0) {
5064 va_next = (sva + NBPML4) & ~PML4MASK;
5069 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5070 if ((*pdpe & PG_V) == 0) {
5071 va_next = (sva + NBPDP) & ~PDPMASK;
5076 va_next = (sva + NBPDR) & ~PDRMASK;
5079 pde = pmap_pdpe_to_pde(pdpe, sva);
5080 if ((*pde & PG_V) == 0)
5082 if ((*pde & PG_PS) != 0) {
5083 if ((*pde & PG_W) == 0)
5084 panic("pmap_unwire: pde %#jx is missing PG_W",
5088 * Are we unwiring the entire large page? If not,
5089 * demote the mapping and fall through.
5091 if (sva + NBPDR == va_next && eva >= va_next) {
5092 atomic_clear_long(pde, PG_W);
5093 pmap->pm_stats.wired_count -= NBPDR /
5096 } else if (!pmap_demote_pde(pmap, pde, sva))
5097 panic("pmap_unwire: demotion failed");
5101 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
5103 if ((*pte & PG_V) == 0)
5105 if ((*pte & PG_W) == 0)
5106 panic("pmap_unwire: pte %#jx is missing PG_W",
5110 * PG_W must be cleared atomically. Although the pmap
5111 * lock synchronizes access to PG_W, another processor
5112 * could be setting PG_M and/or PG_A concurrently.
5114 atomic_clear_long(pte, PG_W);
5115 pmap->pm_stats.wired_count--;
5122 * Copy the range specified by src_addr/len
5123 * from the source map to the range dst_addr/len
5124 * in the destination map.
5126 * This routine is only advisory and need not do anything.
5130 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5131 vm_offset_t src_addr)
5133 struct rwlock *lock;
5134 struct spglist free;
5136 vm_offset_t end_addr = src_addr + len;
5137 vm_offset_t va_next;
5138 vm_page_t dst_pdpg, dstmpte, srcmpte;
5139 pt_entry_t PG_A, PG_M, PG_V;
5141 if (dst_addr != src_addr)
5144 if (dst_pmap->pm_type != src_pmap->pm_type)
5148 * EPT page table entries that require emulation of A/D bits are
5149 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5150 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5151 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5152 * implementations flag an EPT misconfiguration for exec-only
5153 * mappings we skip this function entirely for emulated pmaps.
5155 if (pmap_emulate_ad_bits(dst_pmap))
5159 if (dst_pmap < src_pmap) {
5160 PMAP_LOCK(dst_pmap);
5161 PMAP_LOCK(src_pmap);
5163 PMAP_LOCK(src_pmap);
5164 PMAP_LOCK(dst_pmap);
5167 PG_A = pmap_accessed_bit(dst_pmap);
5168 PG_M = pmap_modified_bit(dst_pmap);
5169 PG_V = pmap_valid_bit(dst_pmap);
5171 for (addr = src_addr; addr < end_addr; addr = va_next) {
5172 pt_entry_t *src_pte, *dst_pte;
5173 pml4_entry_t *pml4e;
5175 pd_entry_t srcptepaddr, *pde;
5177 KASSERT(addr < UPT_MIN_ADDRESS,
5178 ("pmap_copy: invalid to pmap_copy page tables"));
5180 pml4e = pmap_pml4e(src_pmap, addr);
5181 if ((*pml4e & PG_V) == 0) {
5182 va_next = (addr + NBPML4) & ~PML4MASK;
5188 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5189 if ((*pdpe & PG_V) == 0) {
5190 va_next = (addr + NBPDP) & ~PDPMASK;
5196 va_next = (addr + NBPDR) & ~PDRMASK;
5200 pde = pmap_pdpe_to_pde(pdpe, addr);
5202 if (srcptepaddr == 0)
5205 if (srcptepaddr & PG_PS) {
5206 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5208 dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
5209 if (dst_pdpg == NULL)
5211 pde = (pd_entry_t *)
5212 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
5213 pde = &pde[pmap_pde_index(addr)];
5214 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5215 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
5216 PMAP_ENTER_NORECLAIM, &lock))) {
5217 *pde = srcptepaddr & ~PG_W;
5218 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5219 atomic_add_long(&pmap_pde_mappings, 1);
5221 dst_pdpg->wire_count--;
5225 srcptepaddr &= PG_FRAME;
5226 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5227 KASSERT(srcmpte->wire_count > 0,
5228 ("pmap_copy: source page table page is unused"));
5230 if (va_next > end_addr)
5233 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5234 src_pte = &src_pte[pmap_pte_index(addr)];
5236 while (addr < va_next) {
5240 * we only virtual copy managed pages
5242 if ((ptetemp & PG_MANAGED) != 0) {
5243 if (dstmpte != NULL &&
5244 dstmpte->pindex == pmap_pde_pindex(addr))
5245 dstmpte->wire_count++;
5246 else if ((dstmpte = pmap_allocpte(dst_pmap,
5247 addr, NULL)) == NULL)
5249 dst_pte = (pt_entry_t *)
5250 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5251 dst_pte = &dst_pte[pmap_pte_index(addr)];
5252 if (*dst_pte == 0 &&
5253 pmap_try_insert_pv_entry(dst_pmap, addr,
5254 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5257 * Clear the wired, modified, and
5258 * accessed (referenced) bits
5261 *dst_pte = ptetemp & ~(PG_W | PG_M |
5263 pmap_resident_count_inc(dst_pmap, 1);
5266 if (pmap_unwire_ptp(dst_pmap, addr,
5269 * Although "addr" is not
5270 * mapped, paging-structure
5271 * caches could nonetheless
5272 * have entries that refer to
5273 * the freed page table pages.
5274 * Invalidate those entries.
5276 pmap_invalidate_page(dst_pmap,
5278 pmap_free_zero_pages(&free);
5282 if (dstmpte->wire_count >= srcmpte->wire_count)
5292 PMAP_UNLOCK(src_pmap);
5293 PMAP_UNLOCK(dst_pmap);
5297 * Zero the specified hardware page.
5300 pmap_zero_page(vm_page_t m)
5302 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5304 pagezero((void *)va);
5308 * Zero an an area within a single hardware page. off and size must not
5309 * cover an area beyond a single hardware page.
5312 pmap_zero_page_area(vm_page_t m, int off, int size)
5314 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5316 if (off == 0 && size == PAGE_SIZE)
5317 pagezero((void *)va);
5319 bzero((char *)va + off, size);
5323 * Copy 1 specified hardware page to another.
5326 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5328 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5329 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5331 pagecopy((void *)src, (void *)dst);
5334 int unmapped_buf_allowed = 1;
5337 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5338 vm_offset_t b_offset, int xfersize)
5342 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5346 while (xfersize > 0) {
5347 a_pg_offset = a_offset & PAGE_MASK;
5348 pages[0] = ma[a_offset >> PAGE_SHIFT];
5349 b_pg_offset = b_offset & PAGE_MASK;
5350 pages[1] = mb[b_offset >> PAGE_SHIFT];
5351 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5352 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5353 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5354 a_cp = (char *)vaddr[0] + a_pg_offset;
5355 b_cp = (char *)vaddr[1] + b_pg_offset;
5356 bcopy(a_cp, b_cp, cnt);
5357 if (__predict_false(mapped))
5358 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5366 * Returns true if the pmap's pv is one of the first
5367 * 16 pvs linked to from this page. This count may
5368 * be changed upwards or downwards in the future; it
5369 * is only necessary that true be returned for a small
5370 * subset of pmaps for proper page aging.
5373 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5375 struct md_page *pvh;
5376 struct rwlock *lock;
5381 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5382 ("pmap_page_exists_quick: page %p is not managed", m));
5384 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5386 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5387 if (PV_PMAP(pv) == pmap) {
5395 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5396 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5397 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5398 if (PV_PMAP(pv) == pmap) {
5412 * pmap_page_wired_mappings:
5414 * Return the number of managed mappings to the given physical page
5418 pmap_page_wired_mappings(vm_page_t m)
5420 struct rwlock *lock;
5421 struct md_page *pvh;
5425 int count, md_gen, pvh_gen;
5427 if ((m->oflags & VPO_UNMANAGED) != 0)
5429 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5433 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5435 if (!PMAP_TRYLOCK(pmap)) {
5436 md_gen = m->md.pv_gen;
5440 if (md_gen != m->md.pv_gen) {
5445 pte = pmap_pte(pmap, pv->pv_va);
5446 if ((*pte & PG_W) != 0)
5450 if ((m->flags & PG_FICTITIOUS) == 0) {
5451 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5452 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5454 if (!PMAP_TRYLOCK(pmap)) {
5455 md_gen = m->md.pv_gen;
5456 pvh_gen = pvh->pv_gen;
5460 if (md_gen != m->md.pv_gen ||
5461 pvh_gen != pvh->pv_gen) {
5466 pte = pmap_pde(pmap, pv->pv_va);
5467 if ((*pte & PG_W) != 0)
5477 * Returns TRUE if the given page is mapped individually or as part of
5478 * a 2mpage. Otherwise, returns FALSE.
5481 pmap_page_is_mapped(vm_page_t m)
5483 struct rwlock *lock;
5486 if ((m->oflags & VPO_UNMANAGED) != 0)
5488 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5490 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5491 ((m->flags & PG_FICTITIOUS) == 0 &&
5492 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5498 * Destroy all managed, non-wired mappings in the given user-space
5499 * pmap. This pmap cannot be active on any processor besides the
5502 * This function cannot be applied to the kernel pmap. Moreover, it
5503 * is not intended for general use. It is only to be used during
5504 * process termination. Consequently, it can be implemented in ways
5505 * that make it faster than pmap_remove(). First, it can more quickly
5506 * destroy mappings by iterating over the pmap's collection of PV
5507 * entries, rather than searching the page table. Second, it doesn't
5508 * have to test and clear the page table entries atomically, because
5509 * no processor is currently accessing the user address space. In
5510 * particular, a page table entry's dirty bit won't change state once
5511 * this function starts.
5513 * Although this function destroys all of the pmap's managed,
5514 * non-wired mappings, it can delay and batch the invalidation of TLB
5515 * entries without calling pmap_delayed_invl_started() and
5516 * pmap_delayed_invl_finished(). Because the pmap is not active on
5517 * any other processor, none of these TLB entries will ever be used
5518 * before their eventual invalidation. Consequently, there is no need
5519 * for either pmap_remove_all() or pmap_remove_write() to wait for
5520 * that eventual TLB invalidation.
5523 pmap_remove_pages(pmap_t pmap)
5526 pt_entry_t *pte, tpte;
5527 pt_entry_t PG_M, PG_RW, PG_V;
5528 struct spglist free;
5529 vm_page_t m, mpte, mt;
5531 struct md_page *pvh;
5532 struct pv_chunk *pc, *npc;
5533 struct rwlock *lock;
5535 uint64_t inuse, bitmask;
5536 int allfree, field, freed, idx;
5537 boolean_t superpage;
5541 * Assert that the given pmap is only active on the current
5542 * CPU. Unfortunately, we cannot block another CPU from
5543 * activating the pmap while this function is executing.
5545 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5548 cpuset_t other_cpus;
5550 other_cpus = all_cpus;
5552 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5553 CPU_AND(&other_cpus, &pmap->pm_active);
5555 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5560 PG_M = pmap_modified_bit(pmap);
5561 PG_V = pmap_valid_bit(pmap);
5562 PG_RW = pmap_rw_bit(pmap);
5566 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5569 for (field = 0; field < _NPCM; field++) {
5570 inuse = ~pc->pc_map[field] & pc_freemask[field];
5571 while (inuse != 0) {
5573 bitmask = 1UL << bit;
5574 idx = field * 64 + bit;
5575 pv = &pc->pc_pventry[idx];
5578 pte = pmap_pdpe(pmap, pv->pv_va);
5580 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5582 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5585 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5587 pte = &pte[pmap_pte_index(pv->pv_va)];
5591 * Keep track whether 'tpte' is a
5592 * superpage explicitly instead of
5593 * relying on PG_PS being set.
5595 * This is because PG_PS is numerically
5596 * identical to PG_PTE_PAT and thus a
5597 * regular page could be mistaken for
5603 if ((tpte & PG_V) == 0) {
5604 panic("bad pte va %lx pte %lx",
5609 * We cannot remove wired pages from a process' mapping at this time
5617 pa = tpte & PG_PS_FRAME;
5619 pa = tpte & PG_FRAME;
5621 m = PHYS_TO_VM_PAGE(pa);
5622 KASSERT(m->phys_addr == pa,
5623 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5624 m, (uintmax_t)m->phys_addr,
5627 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5628 m < &vm_page_array[vm_page_array_size],
5629 ("pmap_remove_pages: bad tpte %#jx",
5635 * Update the vm_page_t clean/reference bits.
5637 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5639 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5645 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5648 pc->pc_map[field] |= bitmask;
5650 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
5651 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
5652 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5654 if (TAILQ_EMPTY(&pvh->pv_list)) {
5655 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5656 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
5657 TAILQ_EMPTY(&mt->md.pv_list))
5658 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5660 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
5662 pmap_resident_count_dec(pmap, 1);
5663 KASSERT(mpte->wire_count == NPTEPG,
5664 ("pmap_remove_pages: pte page wire count error"));
5665 mpte->wire_count = 0;
5666 pmap_add_delayed_free_list(mpte, &free, FALSE);
5669 pmap_resident_count_dec(pmap, 1);
5670 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5672 if ((m->aflags & PGA_WRITEABLE) != 0 &&
5673 TAILQ_EMPTY(&m->md.pv_list) &&
5674 (m->flags & PG_FICTITIOUS) == 0) {
5675 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5676 if (TAILQ_EMPTY(&pvh->pv_list))
5677 vm_page_aflag_clear(m, PGA_WRITEABLE);
5680 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
5684 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5685 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5686 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5688 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5694 pmap_invalidate_all(pmap);
5696 pmap_free_zero_pages(&free);
5700 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
5702 struct rwlock *lock;
5704 struct md_page *pvh;
5705 pt_entry_t *pte, mask;
5706 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5708 int md_gen, pvh_gen;
5712 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5715 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5717 if (!PMAP_TRYLOCK(pmap)) {
5718 md_gen = m->md.pv_gen;
5722 if (md_gen != m->md.pv_gen) {
5727 pte = pmap_pte(pmap, pv->pv_va);
5730 PG_M = pmap_modified_bit(pmap);
5731 PG_RW = pmap_rw_bit(pmap);
5732 mask |= PG_RW | PG_M;
5735 PG_A = pmap_accessed_bit(pmap);
5736 PG_V = pmap_valid_bit(pmap);
5737 mask |= PG_V | PG_A;
5739 rv = (*pte & mask) == mask;
5744 if ((m->flags & PG_FICTITIOUS) == 0) {
5745 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5746 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5748 if (!PMAP_TRYLOCK(pmap)) {
5749 md_gen = m->md.pv_gen;
5750 pvh_gen = pvh->pv_gen;
5754 if (md_gen != m->md.pv_gen ||
5755 pvh_gen != pvh->pv_gen) {
5760 pte = pmap_pde(pmap, pv->pv_va);
5763 PG_M = pmap_modified_bit(pmap);
5764 PG_RW = pmap_rw_bit(pmap);
5765 mask |= PG_RW | PG_M;
5768 PG_A = pmap_accessed_bit(pmap);
5769 PG_V = pmap_valid_bit(pmap);
5770 mask |= PG_V | PG_A;
5772 rv = (*pte & mask) == mask;
5786 * Return whether or not the specified physical page was modified
5787 * in any physical maps.
5790 pmap_is_modified(vm_page_t m)
5793 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5794 ("pmap_is_modified: page %p is not managed", m));
5797 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5798 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
5799 * is clear, no PTEs can have PG_M set.
5801 VM_OBJECT_ASSERT_WLOCKED(m->object);
5802 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
5804 return (pmap_page_test_mappings(m, FALSE, TRUE));
5808 * pmap_is_prefaultable:
5810 * Return whether or not the specified virtual address is eligible
5814 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
5817 pt_entry_t *pte, PG_V;
5820 PG_V = pmap_valid_bit(pmap);
5823 pde = pmap_pde(pmap, addr);
5824 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
5825 pte = pmap_pde_to_pte(pde, addr);
5826 rv = (*pte & PG_V) == 0;
5833 * pmap_is_referenced:
5835 * Return whether or not the specified physical page was referenced
5836 * in any physical maps.
5839 pmap_is_referenced(vm_page_t m)
5842 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5843 ("pmap_is_referenced: page %p is not managed", m));
5844 return (pmap_page_test_mappings(m, TRUE, FALSE));
5848 * Clear the write and modified bits in each of the given page's mappings.
5851 pmap_remove_write(vm_page_t m)
5853 struct md_page *pvh;
5855 struct rwlock *lock;
5856 pv_entry_t next_pv, pv;
5858 pt_entry_t oldpte, *pte, PG_M, PG_RW;
5860 int pvh_gen, md_gen;
5862 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5863 ("pmap_remove_write: page %p is not managed", m));
5866 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5867 * set by another thread while the object is locked. Thus,
5868 * if PGA_WRITEABLE is clear, no page table entries need updating.
5870 VM_OBJECT_ASSERT_WLOCKED(m->object);
5871 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
5873 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5874 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
5875 pa_to_pvh(VM_PAGE_TO_PHYS(m));
5878 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
5880 if (!PMAP_TRYLOCK(pmap)) {
5881 pvh_gen = pvh->pv_gen;
5885 if (pvh_gen != pvh->pv_gen) {
5891 PG_RW = pmap_rw_bit(pmap);
5893 pde = pmap_pde(pmap, va);
5894 if ((*pde & PG_RW) != 0)
5895 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
5896 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
5897 ("inconsistent pv lock %p %p for page %p",
5898 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
5901 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5903 if (!PMAP_TRYLOCK(pmap)) {
5904 pvh_gen = pvh->pv_gen;
5905 md_gen = m->md.pv_gen;
5909 if (pvh_gen != pvh->pv_gen ||
5910 md_gen != m->md.pv_gen) {
5916 PG_M = pmap_modified_bit(pmap);
5917 PG_RW = pmap_rw_bit(pmap);
5918 pde = pmap_pde(pmap, pv->pv_va);
5919 KASSERT((*pde & PG_PS) == 0,
5920 ("pmap_remove_write: found a 2mpage in page %p's pv list",
5922 pte = pmap_pde_to_pte(pde, pv->pv_va);
5925 if (oldpte & PG_RW) {
5926 if (!atomic_cmpset_long(pte, oldpte, oldpte &
5929 if ((oldpte & PG_M) != 0)
5931 pmap_invalidate_page(pmap, pv->pv_va);
5936 vm_page_aflag_clear(m, PGA_WRITEABLE);
5937 pmap_delayed_invl_wait(m);
5940 static __inline boolean_t
5941 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
5944 if (!pmap_emulate_ad_bits(pmap))
5947 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
5950 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
5951 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
5952 * if the EPT_PG_WRITE bit is set.
5954 if ((pte & EPT_PG_WRITE) != 0)
5958 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
5960 if ((pte & EPT_PG_EXECUTE) == 0 ||
5961 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
5968 * pmap_ts_referenced:
5970 * Return a count of reference bits for a page, clearing those bits.
5971 * It is not necessary for every reference bit to be cleared, but it
5972 * is necessary that 0 only be returned when there are truly no
5973 * reference bits set.
5975 * As an optimization, update the page's dirty field if a modified bit is
5976 * found while counting reference bits. This opportunistic update can be
5977 * performed at low cost and can eliminate the need for some future calls
5978 * to pmap_is_modified(). However, since this function stops after
5979 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
5980 * dirty pages. Those dirty pages will only be detected by a future call
5981 * to pmap_is_modified().
5983 * A DI block is not needed within this function, because
5984 * invalidations are performed before the PV list lock is
5988 pmap_ts_referenced(vm_page_t m)
5990 struct md_page *pvh;
5993 struct rwlock *lock;
5994 pd_entry_t oldpde, *pde;
5995 pt_entry_t *pte, PG_A, PG_M, PG_RW;
5998 int cleared, md_gen, not_cleared, pvh_gen;
5999 struct spglist free;
6002 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6003 ("pmap_ts_referenced: page %p is not managed", m));
6006 pa = VM_PAGE_TO_PHYS(m);
6007 lock = PHYS_TO_PV_LIST_LOCK(pa);
6008 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
6012 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6013 goto small_mappings;
6019 if (!PMAP_TRYLOCK(pmap)) {
6020 pvh_gen = pvh->pv_gen;
6024 if (pvh_gen != pvh->pv_gen) {
6029 PG_A = pmap_accessed_bit(pmap);
6030 PG_M = pmap_modified_bit(pmap);
6031 PG_RW = pmap_rw_bit(pmap);
6033 pde = pmap_pde(pmap, pv->pv_va);
6035 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6037 * Although "oldpde" is mapping a 2MB page, because
6038 * this function is called at a 4KB page granularity,
6039 * we only update the 4KB page under test.
6043 if ((oldpde & PG_A) != 0) {
6045 * Since this reference bit is shared by 512 4KB
6046 * pages, it should not be cleared every time it is
6047 * tested. Apply a simple "hash" function on the
6048 * physical page number, the virtual superpage number,
6049 * and the pmap address to select one 4KB page out of
6050 * the 512 on which testing the reference bit will
6051 * result in clearing that reference bit. This
6052 * function is designed to avoid the selection of the
6053 * same 4KB page for every 2MB page mapping.
6055 * On demotion, a mapping that hasn't been referenced
6056 * is simply destroyed. To avoid the possibility of a
6057 * subsequent page fault on a demoted wired mapping,
6058 * always leave its reference bit set. Moreover,
6059 * since the superpage is wired, the current state of
6060 * its reference bit won't affect page replacement.
6062 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
6063 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
6064 (oldpde & PG_W) == 0) {
6065 if (safe_to_clear_referenced(pmap, oldpde)) {
6066 atomic_clear_long(pde, PG_A);
6067 pmap_invalidate_page(pmap, pv->pv_va);
6069 } else if (pmap_demote_pde_locked(pmap, pde,
6070 pv->pv_va, &lock)) {
6072 * Remove the mapping to a single page
6073 * so that a subsequent access may
6074 * repromote. Since the underlying
6075 * page table page is fully populated,
6076 * this removal never frees a page
6080 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6082 pte = pmap_pde_to_pte(pde, va);
6083 pmap_remove_pte(pmap, pte, va, *pde,
6085 pmap_invalidate_page(pmap, va);
6091 * The superpage mapping was removed
6092 * entirely and therefore 'pv' is no
6100 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6101 ("inconsistent pv lock %p %p for page %p",
6102 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6107 /* Rotate the PV list if it has more than one entry. */
6108 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6109 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6110 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6113 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6115 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6117 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6124 if (!PMAP_TRYLOCK(pmap)) {
6125 pvh_gen = pvh->pv_gen;
6126 md_gen = m->md.pv_gen;
6130 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6135 PG_A = pmap_accessed_bit(pmap);
6136 PG_M = pmap_modified_bit(pmap);
6137 PG_RW = pmap_rw_bit(pmap);
6138 pde = pmap_pde(pmap, pv->pv_va);
6139 KASSERT((*pde & PG_PS) == 0,
6140 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6142 pte = pmap_pde_to_pte(pde, pv->pv_va);
6143 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6145 if ((*pte & PG_A) != 0) {
6146 if (safe_to_clear_referenced(pmap, *pte)) {
6147 atomic_clear_long(pte, PG_A);
6148 pmap_invalidate_page(pmap, pv->pv_va);
6150 } else if ((*pte & PG_W) == 0) {
6152 * Wired pages cannot be paged out so
6153 * doing accessed bit emulation for
6154 * them is wasted effort. We do the
6155 * hard work for unwired pages only.
6157 pmap_remove_pte(pmap, pte, pv->pv_va,
6158 *pde, &free, &lock);
6159 pmap_invalidate_page(pmap, pv->pv_va);
6164 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6165 ("inconsistent pv lock %p %p for page %p",
6166 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6171 /* Rotate the PV list if it has more than one entry. */
6172 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6173 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6174 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6177 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6178 not_cleared < PMAP_TS_REFERENCED_MAX);
6181 pmap_free_zero_pages(&free);
6182 return (cleared + not_cleared);
6186 * Apply the given advice to the specified range of addresses within the
6187 * given pmap. Depending on the advice, clear the referenced and/or
6188 * modified flags in each mapping and set the mapped page's dirty field.
6191 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6193 struct rwlock *lock;
6194 pml4_entry_t *pml4e;
6196 pd_entry_t oldpde, *pde;
6197 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6198 vm_offset_t va, va_next;
6200 boolean_t anychanged;
6202 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6206 * A/D bit emulation requires an alternate code path when clearing
6207 * the modified and accessed bits below. Since this function is
6208 * advisory in nature we skip it entirely for pmaps that require
6209 * A/D bit emulation.
6211 if (pmap_emulate_ad_bits(pmap))
6214 PG_A = pmap_accessed_bit(pmap);
6215 PG_G = pmap_global_bit(pmap);
6216 PG_M = pmap_modified_bit(pmap);
6217 PG_V = pmap_valid_bit(pmap);
6218 PG_RW = pmap_rw_bit(pmap);
6220 pmap_delayed_invl_started();
6222 for (; sva < eva; sva = va_next) {
6223 pml4e = pmap_pml4e(pmap, sva);
6224 if ((*pml4e & PG_V) == 0) {
6225 va_next = (sva + NBPML4) & ~PML4MASK;
6230 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6231 if ((*pdpe & PG_V) == 0) {
6232 va_next = (sva + NBPDP) & ~PDPMASK;
6237 va_next = (sva + NBPDR) & ~PDRMASK;
6240 pde = pmap_pdpe_to_pde(pdpe, sva);
6242 if ((oldpde & PG_V) == 0)
6244 else if ((oldpde & PG_PS) != 0) {
6245 if ((oldpde & PG_MANAGED) == 0)
6248 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6253 * The large page mapping was destroyed.
6259 * Unless the page mappings are wired, remove the
6260 * mapping to a single page so that a subsequent
6261 * access may repromote. Since the underlying page
6262 * table page is fully populated, this removal never
6263 * frees a page table page.
6265 if ((oldpde & PG_W) == 0) {
6266 pte = pmap_pde_to_pte(pde, sva);
6267 KASSERT((*pte & PG_V) != 0,
6268 ("pmap_advise: invalid PTE"));
6269 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6279 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6281 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6283 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6284 if (advice == MADV_DONTNEED) {
6286 * Future calls to pmap_is_modified()
6287 * can be avoided by making the page
6290 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6293 atomic_clear_long(pte, PG_M | PG_A);
6294 } else if ((*pte & PG_A) != 0)
6295 atomic_clear_long(pte, PG_A);
6299 if ((*pte & PG_G) != 0) {
6306 if (va != va_next) {
6307 pmap_invalidate_range(pmap, va, sva);
6312 pmap_invalidate_range(pmap, va, sva);
6315 pmap_invalidate_all(pmap);
6317 pmap_delayed_invl_finished();
6321 * Clear the modify bits on the specified physical page.
6324 pmap_clear_modify(vm_page_t m)
6326 struct md_page *pvh;
6328 pv_entry_t next_pv, pv;
6329 pd_entry_t oldpde, *pde;
6330 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6331 struct rwlock *lock;
6333 int md_gen, pvh_gen;
6335 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6336 ("pmap_clear_modify: page %p is not managed", m));
6337 VM_OBJECT_ASSERT_WLOCKED(m->object);
6338 KASSERT(!vm_page_xbusied(m),
6339 ("pmap_clear_modify: page %p is exclusive busied", m));
6342 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6343 * If the object containing the page is locked and the page is not
6344 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6346 if ((m->aflags & PGA_WRITEABLE) == 0)
6348 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6349 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6350 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6353 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6355 if (!PMAP_TRYLOCK(pmap)) {
6356 pvh_gen = pvh->pv_gen;
6360 if (pvh_gen != pvh->pv_gen) {
6365 PG_M = pmap_modified_bit(pmap);
6366 PG_V = pmap_valid_bit(pmap);
6367 PG_RW = pmap_rw_bit(pmap);
6369 pde = pmap_pde(pmap, va);
6371 if ((oldpde & PG_RW) != 0) {
6372 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6373 if ((oldpde & PG_W) == 0) {
6375 * Write protect the mapping to a
6376 * single page so that a subsequent
6377 * write access may repromote.
6379 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6381 pte = pmap_pde_to_pte(pde, va);
6383 if ((oldpte & PG_V) != 0) {
6384 while (!atomic_cmpset_long(pte,
6386 oldpte & ~(PG_M | PG_RW)))
6389 pmap_invalidate_page(pmap, va);
6396 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6398 if (!PMAP_TRYLOCK(pmap)) {
6399 md_gen = m->md.pv_gen;
6400 pvh_gen = pvh->pv_gen;
6404 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6409 PG_M = pmap_modified_bit(pmap);
6410 PG_RW = pmap_rw_bit(pmap);
6411 pde = pmap_pde(pmap, pv->pv_va);
6412 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6413 " a 2mpage in page %p's pv list", m));
6414 pte = pmap_pde_to_pte(pde, pv->pv_va);
6415 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6416 atomic_clear_long(pte, PG_M);
6417 pmap_invalidate_page(pmap, pv->pv_va);
6425 * Miscellaneous support routines follow
6428 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6429 static __inline void
6430 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6435 * The cache mode bits are all in the low 32-bits of the
6436 * PTE, so we can just spin on updating the low 32-bits.
6439 opte = *(u_int *)pte;
6440 npte = opte & ~mask;
6442 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6445 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6446 static __inline void
6447 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6452 * The cache mode bits are all in the low 32-bits of the
6453 * PDE, so we can just spin on updating the low 32-bits.
6456 opde = *(u_int *)pde;
6457 npde = opde & ~mask;
6459 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6463 * Map a set of physical memory pages into the kernel virtual
6464 * address space. Return a pointer to where it is mapped. This
6465 * routine is intended to be used for mapping device memory,
6469 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6471 struct pmap_preinit_mapping *ppim;
6472 vm_offset_t va, offset;
6476 offset = pa & PAGE_MASK;
6477 size = round_page(offset + size);
6478 pa = trunc_page(pa);
6480 if (!pmap_initialized) {
6482 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6483 ppim = pmap_preinit_mapping + i;
6484 if (ppim->va == 0) {
6488 ppim->va = virtual_avail;
6489 virtual_avail += size;
6495 panic("%s: too many preinit mappings", __func__);
6498 * If we have a preinit mapping, re-use it.
6500 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6501 ppim = pmap_preinit_mapping + i;
6502 if (ppim->pa == pa && ppim->sz == size &&
6504 return ((void *)(ppim->va + offset));
6507 * If the specified range of physical addresses fits within
6508 * the direct map window, use the direct map.
6510 if (pa < dmaplimit && pa + size < dmaplimit) {
6511 va = PHYS_TO_DMAP(pa);
6512 if (!pmap_change_attr(va, size, mode))
6513 return ((void *)(va + offset));
6515 va = kva_alloc(size);
6517 panic("%s: Couldn't allocate KVA", __func__);
6519 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6520 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6521 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6522 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6523 return ((void *)(va + offset));
6527 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6530 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6534 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6537 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6541 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6543 struct pmap_preinit_mapping *ppim;
6547 /* If we gave a direct map region in pmap_mapdev, do nothing */
6548 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6550 offset = va & PAGE_MASK;
6551 size = round_page(offset + size);
6552 va = trunc_page(va);
6553 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6554 ppim = pmap_preinit_mapping + i;
6555 if (ppim->va == va && ppim->sz == size) {
6556 if (pmap_initialized)
6562 if (va + size == virtual_avail)
6567 if (pmap_initialized)
6572 * Tries to demote a 1GB page mapping.
6575 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6577 pdp_entry_t newpdpe, oldpdpe;
6578 pd_entry_t *firstpde, newpde, *pde;
6579 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6583 PG_A = pmap_accessed_bit(pmap);
6584 PG_M = pmap_modified_bit(pmap);
6585 PG_V = pmap_valid_bit(pmap);
6586 PG_RW = pmap_rw_bit(pmap);
6588 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6590 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6591 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6592 if ((pdpg = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6593 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6594 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6595 " in pmap %p", va, pmap);
6598 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
6599 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
6600 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6601 KASSERT((oldpdpe & PG_A) != 0,
6602 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6603 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6604 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
6608 * Initialize the page directory page.
6610 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
6616 * Demote the mapping.
6621 * Invalidate a stale recursive mapping of the page directory page.
6623 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
6625 pmap_pdpe_demotions++;
6626 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
6627 " in pmap %p", va, pmap);
6632 * Sets the memory attribute for the specified page.
6635 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6638 m->md.pat_mode = ma;
6641 * If "m" is a normal page, update its direct mapping. This update
6642 * can be relied upon to perform any cache operations that are
6643 * required for data coherence.
6645 if ((m->flags & PG_FICTITIOUS) == 0 &&
6646 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6648 panic("memory attribute change on the direct map failed");
6652 * Changes the specified virtual address range's memory type to that given by
6653 * the parameter "mode". The specified virtual address range must be
6654 * completely contained within either the direct map or the kernel map. If
6655 * the virtual address range is contained within the kernel map, then the
6656 * memory type for each of the corresponding ranges of the direct map is also
6657 * changed. (The corresponding ranges of the direct map are those ranges that
6658 * map the same physical pages as the specified virtual address range.) These
6659 * changes to the direct map are necessary because Intel describes the
6660 * behavior of their processors as "undefined" if two or more mappings to the
6661 * same physical page have different memory types.
6663 * Returns zero if the change completed successfully, and either EINVAL or
6664 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6665 * of the virtual address range was not mapped, and ENOMEM is returned if
6666 * there was insufficient memory available to complete the change. In the
6667 * latter case, the memory type may have been changed on some part of the
6668 * virtual address range or the direct map.
6671 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6675 PMAP_LOCK(kernel_pmap);
6676 error = pmap_change_attr_locked(va, size, mode);
6677 PMAP_UNLOCK(kernel_pmap);
6682 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
6684 vm_offset_t base, offset, tmpva;
6685 vm_paddr_t pa_start, pa_end, pa_end1;
6689 int cache_bits_pte, cache_bits_pde, error;
6692 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6693 base = trunc_page(va);
6694 offset = va & PAGE_MASK;
6695 size = round_page(offset + size);
6698 * Only supported on kernel virtual addresses, including the direct
6699 * map but excluding the recursive map.
6701 if (base < DMAP_MIN_ADDRESS)
6704 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
6705 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
6709 * Pages that aren't mapped aren't supported. Also break down 2MB pages
6710 * into 4KB pages if required.
6712 for (tmpva = base; tmpva < base + size; ) {
6713 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6714 if (pdpe == NULL || *pdpe == 0)
6716 if (*pdpe & PG_PS) {
6718 * If the current 1GB page already has the required
6719 * memory type, then we need not demote this page. Just
6720 * increment tmpva to the next 1GB page frame.
6722 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
6723 tmpva = trunc_1gpage(tmpva) + NBPDP;
6728 * If the current offset aligns with a 1GB page frame
6729 * and there is at least 1GB left within the range, then
6730 * we need not break down this page into 2MB pages.
6732 if ((tmpva & PDPMASK) == 0 &&
6733 tmpva + PDPMASK < base + size) {
6737 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
6740 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6745 * If the current 2MB page already has the required
6746 * memory type, then we need not demote this page. Just
6747 * increment tmpva to the next 2MB page frame.
6749 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
6750 tmpva = trunc_2mpage(tmpva) + NBPDR;
6755 * If the current offset aligns with a 2MB page frame
6756 * and there is at least 2MB left within the range, then
6757 * we need not break down this page into 4KB pages.
6759 if ((tmpva & PDRMASK) == 0 &&
6760 tmpva + PDRMASK < base + size) {
6764 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
6767 pte = pmap_pde_to_pte(pde, tmpva);
6775 * Ok, all the pages exist, so run through them updating their
6776 * cache mode if required.
6778 pa_start = pa_end = 0;
6779 for (tmpva = base; tmpva < base + size; ) {
6780 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6781 if (*pdpe & PG_PS) {
6782 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
6783 pmap_pde_attr(pdpe, cache_bits_pde,
6787 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6788 (*pdpe & PG_PS_FRAME) < dmaplimit) {
6789 if (pa_start == pa_end) {
6790 /* Start physical address run. */
6791 pa_start = *pdpe & PG_PS_FRAME;
6792 pa_end = pa_start + NBPDP;
6793 } else if (pa_end == (*pdpe & PG_PS_FRAME))
6796 /* Run ended, update direct map. */
6797 error = pmap_change_attr_locked(
6798 PHYS_TO_DMAP(pa_start),
6799 pa_end - pa_start, mode);
6802 /* Start physical address run. */
6803 pa_start = *pdpe & PG_PS_FRAME;
6804 pa_end = pa_start + NBPDP;
6807 tmpva = trunc_1gpage(tmpva) + NBPDP;
6810 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6812 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
6813 pmap_pde_attr(pde, cache_bits_pde,
6817 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6818 (*pde & PG_PS_FRAME) < dmaplimit) {
6819 if (pa_start == pa_end) {
6820 /* Start physical address run. */
6821 pa_start = *pde & PG_PS_FRAME;
6822 pa_end = pa_start + NBPDR;
6823 } else if (pa_end == (*pde & PG_PS_FRAME))
6826 /* Run ended, update direct map. */
6827 error = pmap_change_attr_locked(
6828 PHYS_TO_DMAP(pa_start),
6829 pa_end - pa_start, mode);
6832 /* Start physical address run. */
6833 pa_start = *pde & PG_PS_FRAME;
6834 pa_end = pa_start + NBPDR;
6837 tmpva = trunc_2mpage(tmpva) + NBPDR;
6839 pte = pmap_pde_to_pte(pde, tmpva);
6840 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
6841 pmap_pte_attr(pte, cache_bits_pte,
6845 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6846 (*pte & PG_FRAME) < dmaplimit) {
6847 if (pa_start == pa_end) {
6848 /* Start physical address run. */
6849 pa_start = *pte & PG_FRAME;
6850 pa_end = pa_start + PAGE_SIZE;
6851 } else if (pa_end == (*pte & PG_FRAME))
6852 pa_end += PAGE_SIZE;
6854 /* Run ended, update direct map. */
6855 error = pmap_change_attr_locked(
6856 PHYS_TO_DMAP(pa_start),
6857 pa_end - pa_start, mode);
6860 /* Start physical address run. */
6861 pa_start = *pte & PG_FRAME;
6862 pa_end = pa_start + PAGE_SIZE;
6868 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
6869 pa_end1 = MIN(pa_end, dmaplimit);
6870 if (pa_start != pa_end1)
6871 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
6872 pa_end1 - pa_start, mode);
6876 * Flush CPU caches if required to make sure any data isn't cached that
6877 * shouldn't be, etc.
6880 pmap_invalidate_range(kernel_pmap, base, tmpva);
6881 pmap_invalidate_cache_range(base, tmpva, FALSE);
6887 * Demotes any mapping within the direct map region that covers more than the
6888 * specified range of physical addresses. This range's size must be a power
6889 * of two and its starting address must be a multiple of its size. Since the
6890 * demotion does not change any attributes of the mapping, a TLB invalidation
6891 * is not mandatory. The caller may, however, request a TLB invalidation.
6894 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
6903 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
6904 KASSERT((base & (len - 1)) == 0,
6905 ("pmap_demote_DMAP: base is not a multiple of len"));
6906 if (len < NBPDP && base < dmaplimit) {
6907 va = PHYS_TO_DMAP(base);
6909 PMAP_LOCK(kernel_pmap);
6910 pdpe = pmap_pdpe(kernel_pmap, va);
6911 if ((*pdpe & X86_PG_V) == 0)
6912 panic("pmap_demote_DMAP: invalid PDPE");
6913 if ((*pdpe & PG_PS) != 0) {
6914 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
6915 panic("pmap_demote_DMAP: PDPE failed");
6919 pde = pmap_pdpe_to_pde(pdpe, va);
6920 if ((*pde & X86_PG_V) == 0)
6921 panic("pmap_demote_DMAP: invalid PDE");
6922 if ((*pde & PG_PS) != 0) {
6923 if (!pmap_demote_pde(kernel_pmap, pde, va))
6924 panic("pmap_demote_DMAP: PDE failed");
6928 if (changed && invalidate)
6929 pmap_invalidate_page(kernel_pmap, va);
6930 PMAP_UNLOCK(kernel_pmap);
6935 * perform the pmap work for mincore
6938 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
6941 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
6945 PG_A = pmap_accessed_bit(pmap);
6946 PG_M = pmap_modified_bit(pmap);
6947 PG_V = pmap_valid_bit(pmap);
6948 PG_RW = pmap_rw_bit(pmap);
6952 pdep = pmap_pde(pmap, addr);
6953 if (pdep != NULL && (*pdep & PG_V)) {
6954 if (*pdep & PG_PS) {
6956 /* Compute the physical address of the 4KB page. */
6957 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
6959 val = MINCORE_SUPER;
6961 pte = *pmap_pde_to_pte(pdep, addr);
6962 pa = pte & PG_FRAME;
6970 if ((pte & PG_V) != 0) {
6971 val |= MINCORE_INCORE;
6972 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6973 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
6974 if ((pte & PG_A) != 0)
6975 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
6977 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
6978 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
6979 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
6980 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
6981 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
6984 PA_UNLOCK_COND(*locked_pa);
6990 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
6992 uint32_t gen, new_gen, pcid_next;
6994 CRITICAL_ASSERT(curthread);
6995 gen = PCPU_GET(pcid_gen);
6996 if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN ||
6997 pmap->pm_pcids[cpuid].pm_gen == gen)
6998 return (CR3_PCID_SAVE);
6999 pcid_next = PCPU_GET(pcid_next);
7000 KASSERT(pcid_next <= PMAP_PCID_OVERMAX, ("cpu %d pcid_next %#x",
7002 if (pcid_next == PMAP_PCID_OVERMAX) {
7006 PCPU_SET(pcid_gen, new_gen);
7007 pcid_next = PMAP_PCID_KERN + 1;
7011 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
7012 pmap->pm_pcids[cpuid].pm_gen = new_gen;
7013 PCPU_SET(pcid_next, pcid_next + 1);
7018 pmap_activate_sw(struct thread *td)
7020 pmap_t oldpmap, pmap;
7021 uint64_t cached, cr3;
7025 oldpmap = PCPU_GET(curpmap);
7026 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7027 if (oldpmap == pmap)
7029 cpuid = PCPU_GET(cpuid);
7031 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7033 CPU_SET(cpuid, &pmap->pm_active);
7036 if (pmap_pcid_enabled) {
7037 cached = pmap_pcid_alloc(pmap, cpuid);
7038 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
7039 pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
7040 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
7041 pmap->pm_pcids[cpuid].pm_pcid));
7042 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
7043 pmap == kernel_pmap,
7044 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
7045 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
7048 * If the INVPCID instruction is not available,
7049 * invltlb_pcid_handler() is used for handle
7050 * invalidate_all IPI, which checks for curpmap ==
7051 * smp_tlb_pmap. Below operations sequence has a
7052 * window where %CR3 is loaded with the new pmap's
7053 * PML4 address, but curpmap value is not yet updated.
7054 * This causes invltlb IPI handler, called between the
7055 * updates, to execute as NOP, which leaves stale TLB
7058 * Note that the most typical use of
7059 * pmap_activate_sw(), from the context switch, is
7060 * immune to this race, because interrupts are
7061 * disabled (while the thread lock is owned), and IPI
7062 * happends after curpmap is updated. Protect other
7063 * callers in a similar way, by disabling interrupts
7064 * around the %cr3 register reload and curpmap
7068 rflags = intr_disable();
7070 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
7071 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
7074 PCPU_INC(pm_save_cnt);
7076 PCPU_SET(curpmap, pmap);
7078 intr_restore(rflags);
7079 } else if (cr3 != pmap->pm_cr3) {
7080 load_cr3(pmap->pm_cr3);
7081 PCPU_SET(curpmap, pmap);
7084 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
7086 CPU_CLR(cpuid, &oldpmap->pm_active);
7091 pmap_activate(struct thread *td)
7095 pmap_activate_sw(td);
7100 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
7105 * Increase the starting virtual address of the given mapping if a
7106 * different alignment might result in more superpage mappings.
7109 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7110 vm_offset_t *addr, vm_size_t size)
7112 vm_offset_t superpage_offset;
7116 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7117 offset += ptoa(object->pg_color);
7118 superpage_offset = offset & PDRMASK;
7119 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
7120 (*addr & PDRMASK) == superpage_offset)
7122 if ((*addr & PDRMASK) < superpage_offset)
7123 *addr = (*addr & ~PDRMASK) + superpage_offset;
7125 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
7129 static unsigned long num_dirty_emulations;
7130 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
7131 &num_dirty_emulations, 0, NULL);
7133 static unsigned long num_accessed_emulations;
7134 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
7135 &num_accessed_emulations, 0, NULL);
7137 static unsigned long num_superpage_accessed_emulations;
7138 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7139 &num_superpage_accessed_emulations, 0, NULL);
7141 static unsigned long ad_emulation_superpage_promotions;
7142 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7143 &ad_emulation_superpage_promotions, 0, NULL);
7144 #endif /* INVARIANTS */
7147 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7150 struct rwlock *lock;
7153 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7155 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7156 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7158 if (!pmap_emulate_ad_bits(pmap))
7161 PG_A = pmap_accessed_bit(pmap);
7162 PG_M = pmap_modified_bit(pmap);
7163 PG_V = pmap_valid_bit(pmap);
7164 PG_RW = pmap_rw_bit(pmap);
7170 pde = pmap_pde(pmap, va);
7171 if (pde == NULL || (*pde & PG_V) == 0)
7174 if ((*pde & PG_PS) != 0) {
7175 if (ftype == VM_PROT_READ) {
7177 atomic_add_long(&num_superpage_accessed_emulations, 1);
7185 pte = pmap_pde_to_pte(pde, va);
7186 if ((*pte & PG_V) == 0)
7189 if (ftype == VM_PROT_WRITE) {
7190 if ((*pte & PG_RW) == 0)
7193 * Set the modified and accessed bits simultaneously.
7195 * Intel EPT PTEs that do software emulation of A/D bits map
7196 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7197 * An EPT misconfiguration is triggered if the PTE is writable
7198 * but not readable (WR=10). This is avoided by setting PG_A
7199 * and PG_M simultaneously.
7201 *pte |= PG_M | PG_A;
7206 /* try to promote the mapping */
7207 if (va < VM_MAXUSER_ADDRESS)
7208 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7212 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7214 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7215 pmap_ps_enabled(pmap) &&
7216 (m->flags & PG_FICTITIOUS) == 0 &&
7217 vm_reserv_level_iffullpop(m) == 0) {
7218 pmap_promote_pde(pmap, pde, va, &lock);
7220 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7224 if (ftype == VM_PROT_WRITE)
7225 atomic_add_long(&num_dirty_emulations, 1);
7227 atomic_add_long(&num_accessed_emulations, 1);
7229 rv = 0; /* success */
7238 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7243 pt_entry_t *pte, PG_V;
7247 PG_V = pmap_valid_bit(pmap);
7250 pml4 = pmap_pml4e(pmap, va);
7252 if ((*pml4 & PG_V) == 0)
7255 pdp = pmap_pml4e_to_pdpe(pml4, va);
7257 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7260 pde = pmap_pdpe_to_pde(pdp, va);
7262 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7265 pte = pmap_pde_to_pte(pde, va);
7274 * Get the kernel virtual address of a set of physical pages. If there are
7275 * physical addresses not covered by the DMAP perform a transient mapping
7276 * that will be removed when calling pmap_unmap_io_transient.
7278 * \param page The pages the caller wishes to obtain the virtual
7279 * address on the kernel memory map.
7280 * \param vaddr On return contains the kernel virtual memory address
7281 * of the pages passed in the page parameter.
7282 * \param count Number of pages passed in.
7283 * \param can_fault TRUE if the thread using the mapped pages can take
7284 * page faults, FALSE otherwise.
7286 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7287 * finished or FALSE otherwise.
7291 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7292 boolean_t can_fault)
7295 boolean_t needs_mapping;
7297 int cache_bits, error, i;
7300 * Allocate any KVA space that we need, this is done in a separate
7301 * loop to prevent calling vmem_alloc while pinned.
7303 needs_mapping = FALSE;
7304 for (i = 0; i < count; i++) {
7305 paddr = VM_PAGE_TO_PHYS(page[i]);
7306 if (__predict_false(paddr >= dmaplimit)) {
7307 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7308 M_BESTFIT | M_WAITOK, &vaddr[i]);
7309 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7310 needs_mapping = TRUE;
7312 vaddr[i] = PHYS_TO_DMAP(paddr);
7316 /* Exit early if everything is covered by the DMAP */
7321 * NB: The sequence of updating a page table followed by accesses
7322 * to the corresponding pages used in the !DMAP case is subject to
7323 * the situation described in the "AMD64 Architecture Programmer's
7324 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7325 * Coherency Considerations". Therefore, issuing the INVLPG right
7326 * after modifying the PTE bits is crucial.
7330 for (i = 0; i < count; i++) {
7331 paddr = VM_PAGE_TO_PHYS(page[i]);
7332 if (paddr >= dmaplimit) {
7335 * Slow path, since we can get page faults
7336 * while mappings are active don't pin the
7337 * thread to the CPU and instead add a global
7338 * mapping visible to all CPUs.
7340 pmap_qenter(vaddr[i], &page[i], 1);
7342 pte = vtopte(vaddr[i]);
7343 cache_bits = pmap_cache_bits(kernel_pmap,
7344 page[i]->md.pat_mode, 0);
7345 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7352 return (needs_mapping);
7356 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7357 boolean_t can_fault)
7364 for (i = 0; i < count; i++) {
7365 paddr = VM_PAGE_TO_PHYS(page[i]);
7366 if (paddr >= dmaplimit) {
7368 pmap_qremove(vaddr[i], 1);
7369 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7375 pmap_quick_enter_page(vm_page_t m)
7379 paddr = VM_PAGE_TO_PHYS(m);
7380 if (paddr < dmaplimit)
7381 return (PHYS_TO_DMAP(paddr));
7382 mtx_lock_spin(&qframe_mtx);
7383 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7384 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7385 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7390 pmap_quick_remove_page(vm_offset_t addr)
7395 pte_store(vtopte(qframe), 0);
7397 mtx_unlock_spin(&qframe_mtx);
7400 #include "opt_ddb.h"
7402 #include <sys/kdb.h>
7403 #include <ddb/ddb.h>
7405 DB_SHOW_COMMAND(pte, pmap_print_pte)
7411 pt_entry_t *pte, PG_V;
7415 db_printf("show pte addr\n");
7418 va = (vm_offset_t)addr;
7420 if (kdb_thread != NULL)
7421 pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
7423 pmap = PCPU_GET(curpmap);
7425 PG_V = pmap_valid_bit(pmap);
7426 pml4 = pmap_pml4e(pmap, va);
7427 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
7428 if ((*pml4 & PG_V) == 0) {
7432 pdp = pmap_pml4e_to_pdpe(pml4, va);
7433 db_printf(" pdpe %#016lx", *pdp);
7434 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
7438 pde = pmap_pdpe_to_pde(pdp, va);
7439 db_printf(" pde %#016lx", *pde);
7440 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
7444 pte = pmap_pde_to_pte(pde, va);
7445 db_printf(" pte %#016lx\n", *pte);
7448 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
7453 a = (vm_paddr_t)addr;
7454 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
7456 db_printf("show phys2dmap addr\n");