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>
108 #include <sys/systm.h>
109 #include <sys/kernel.h>
111 #include <sys/lock.h>
112 #include <sys/malloc.h>
113 #include <sys/mman.h>
114 #include <sys/mutex.h>
115 #include <sys/proc.h>
116 #include <sys/rwlock.h>
118 #include <sys/turnstile.h>
119 #include <sys/vmem.h>
120 #include <sys/vmmeter.h>
121 #include <sys/sched.h>
122 #include <sys/sysctl.h>
126 #include <vm/vm_param.h>
127 #include <vm/vm_kern.h>
128 #include <vm/vm_page.h>
129 #include <vm/vm_map.h>
130 #include <vm/vm_object.h>
131 #include <vm/vm_extern.h>
132 #include <vm/vm_pageout.h>
133 #include <vm/vm_pager.h>
134 #include <vm/vm_phys.h>
135 #include <vm/vm_radix.h>
136 #include <vm/vm_reserv.h>
139 #include <machine/intr_machdep.h>
140 #include <x86/apicvar.h>
141 #include <machine/cpu.h>
142 #include <machine/cputypes.h>
143 #include <machine/md_var.h>
144 #include <machine/pcb.h>
145 #include <machine/specialreg.h>
147 #include <machine/smp.h>
150 static __inline boolean_t
151 pmap_type_guest(pmap_t pmap)
154 return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
157 static __inline boolean_t
158 pmap_emulate_ad_bits(pmap_t pmap)
161 return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
164 static __inline pt_entry_t
165 pmap_valid_bit(pmap_t pmap)
169 switch (pmap->pm_type) {
175 if (pmap_emulate_ad_bits(pmap))
176 mask = EPT_PG_EMUL_V;
181 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
187 static __inline pt_entry_t
188 pmap_rw_bit(pmap_t pmap)
192 switch (pmap->pm_type) {
198 if (pmap_emulate_ad_bits(pmap))
199 mask = EPT_PG_EMUL_RW;
204 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
210 static __inline pt_entry_t
211 pmap_global_bit(pmap_t pmap)
215 switch (pmap->pm_type) {
224 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
230 static __inline pt_entry_t
231 pmap_accessed_bit(pmap_t pmap)
235 switch (pmap->pm_type) {
241 if (pmap_emulate_ad_bits(pmap))
247 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
253 static __inline pt_entry_t
254 pmap_modified_bit(pmap_t pmap)
258 switch (pmap->pm_type) {
264 if (pmap_emulate_ad_bits(pmap))
270 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
276 extern struct pcpu __pcpu[];
278 #if !defined(DIAGNOSTIC)
279 #ifdef __GNUC_GNU_INLINE__
280 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
282 #define PMAP_INLINE extern inline
289 #define PV_STAT(x) do { x ; } while (0)
291 #define PV_STAT(x) do { } while (0)
294 #define pa_index(pa) ((pa) >> PDRSHIFT)
295 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
297 #define NPV_LIST_LOCKS MAXCPU
299 #define PHYS_TO_PV_LIST_LOCK(pa) \
300 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
302 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
303 struct rwlock **_lockp = (lockp); \
304 struct rwlock *_new_lock; \
306 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
307 if (_new_lock != *_lockp) { \
308 if (*_lockp != NULL) \
309 rw_wunlock(*_lockp); \
310 *_lockp = _new_lock; \
315 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
316 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
318 #define RELEASE_PV_LIST_LOCK(lockp) do { \
319 struct rwlock **_lockp = (lockp); \
321 if (*_lockp != NULL) { \
322 rw_wunlock(*_lockp); \
327 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
328 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
330 struct pmap kernel_pmap_store;
332 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
333 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
336 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
337 "Number of kernel page table pages allocated on bootup");
340 vm_paddr_t dmaplimit;
341 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
344 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
346 static int pat_works = 1;
347 SYSCTL_INT(_vm_pmap, OID_AUTO, pat_works, CTLFLAG_RD, &pat_works, 1,
348 "Is page attribute table fully functional?");
350 static int pg_ps_enabled = 1;
351 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
352 &pg_ps_enabled, 0, "Are large page mappings enabled?");
354 #define PAT_INDEX_SIZE 8
355 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
357 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
358 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
359 u_int64_t KPDPphys; /* phys addr of kernel level 3 */
360 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
362 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
363 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
364 static int ndmpdpphys; /* number of DMPDPphys pages */
367 * pmap_mapdev support pre initialization (i.e. console)
369 #define PMAP_PREINIT_MAPPING_COUNT 8
370 static struct pmap_preinit_mapping {
375 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
376 static int pmap_initialized;
379 * Data for the pv entry allocation mechanism.
380 * Updates to pv_invl_gen are protected by the pv_list_locks[]
381 * elements, but reads are not.
383 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
384 static struct mtx pv_chunks_mutex;
385 static struct rwlock pv_list_locks[NPV_LIST_LOCKS];
386 static u_long pv_invl_gen[NPV_LIST_LOCKS];
387 static struct md_page *pv_table;
390 * All those kernel PT submaps that BSD is so fond of
392 pt_entry_t *CMAP1 = 0;
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 = {
431 #define PMAP_ASSERT_NOT_IN_DI() \
432 KASSERT(curthread->td_md.md_invl_gen.gen == 0, ("DI already started"))
435 * Start a new Delayed Invalidation (DI) block of code, executed by
436 * the current thread. Within a DI block, the current thread may
437 * destroy both the page table and PV list entries for a mapping and
438 * then release the corresponding PV list lock before ensuring that
439 * the mapping is flushed from the TLBs of any processors with the
443 pmap_delayed_invl_started(void)
445 struct pmap_invl_gen *invl_gen;
448 invl_gen = &curthread->td_md.md_invl_gen;
449 PMAP_ASSERT_NOT_IN_DI();
450 mtx_lock(&invl_gen_mtx);
451 if (LIST_EMPTY(&pmap_invl_gen_tracker))
452 currgen = pmap_invl_gen;
454 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
455 invl_gen->gen = currgen + 1;
456 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
457 mtx_unlock(&invl_gen_mtx);
461 * Finish the DI block, previously started by the current thread. All
462 * required TLB flushes for the pages marked by
463 * pmap_delayed_invl_page() must be finished before this function is
466 * This function works by bumping the global DI generation number to
467 * the generation number of the current thread's DI, unless there is a
468 * pending DI that started earlier. In the latter case, bumping the
469 * global DI generation number would incorrectly signal that the
470 * earlier DI had finished. Instead, this function bumps the earlier
471 * DI's generation number to match the generation number of the
472 * current thread's DI.
475 pmap_delayed_invl_finished(void)
477 struct pmap_invl_gen *invl_gen, *next;
478 struct turnstile *ts;
480 invl_gen = &curthread->td_md.md_invl_gen;
481 KASSERT(invl_gen->gen != 0, ("missed invl_started"));
482 mtx_lock(&invl_gen_mtx);
483 next = LIST_NEXT(invl_gen, link);
485 turnstile_chain_lock(&invl_gen_ts);
486 ts = turnstile_lookup(&invl_gen_ts);
487 pmap_invl_gen = invl_gen->gen;
489 turnstile_broadcast(ts, TS_SHARED_QUEUE);
490 turnstile_unpend(ts, TS_SHARED_LOCK);
492 turnstile_chain_unlock(&invl_gen_ts);
494 next->gen = invl_gen->gen;
496 LIST_REMOVE(invl_gen, link);
497 mtx_unlock(&invl_gen_mtx);
502 static long invl_wait;
503 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
504 "Number of times DI invalidation blocked pmap_remove_all/write");
508 pmap_delayed_invl_genp(vm_page_t m)
511 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
515 * Ensure that all currently executing DI blocks, that need to flush
516 * TLB for the given page m, actually flushed the TLB at the time the
517 * function returned. If the page m has an empty PV list and we call
518 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
519 * valid mapping for the page m in either its page table or TLB.
521 * This function works by blocking until the global DI generation
522 * number catches up with the generation number associated with the
523 * given page m and its PV list. Since this function's callers
524 * typically own an object lock and sometimes own a page lock, it
525 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
529 pmap_delayed_invl_wait(vm_page_t m)
532 struct turnstile *ts;
535 bool accounted = false;
539 m_gen = pmap_delayed_invl_genp(m);
540 while (*m_gen > pmap_invl_gen) {
543 atomic_add_long(&invl_wait, 1);
547 ts = turnstile_trywait(&invl_gen_ts);
548 if (*m_gen > pmap_invl_gen)
549 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
551 turnstile_cancel(ts);
556 * Mark the page m's PV list as participating in the current thread's
557 * DI block. Any threads concurrently using m's PV list to remove or
558 * restrict all mappings to m will wait for the current thread's DI
559 * block to complete before proceeding.
561 * The function works by setting the DI generation number for m's PV
562 * list to at least * the number for the current thread. This forces
563 * a caller to pmap_delayed_invl_wait() to spin until current thread
564 * calls pmap_delayed_invl_finished().
567 pmap_delayed_invl_page(vm_page_t m)
571 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
572 gen = curthread->td_md.md_invl_gen.gen;
575 m_gen = pmap_delayed_invl_genp(m);
583 static caddr_t crashdumpmap;
585 static void free_pv_chunk(struct pv_chunk *pc);
586 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
587 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
588 static int popcnt_pc_map_elem_pq(uint64_t elem);
589 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
590 static void reserve_pv_entries(pmap_t pmap, int needed,
591 struct rwlock **lockp);
592 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
593 struct rwlock **lockp);
594 static boolean_t pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
595 struct rwlock **lockp);
596 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
597 struct rwlock **lockp);
598 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
599 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
602 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode);
603 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
604 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
605 vm_offset_t va, struct rwlock **lockp);
606 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
608 static boolean_t pmap_enter_pde(pmap_t pmap, vm_offset_t va, vm_page_t m,
609 vm_prot_t prot, struct rwlock **lockp);
610 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
611 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
612 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
613 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
614 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
615 static vm_page_t pmap_lookup_pt_page(pmap_t pmap, vm_offset_t va);
616 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask);
617 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
618 struct rwlock **lockp);
619 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
621 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
622 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
623 struct spglist *free, struct rwlock **lockp);
624 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
625 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
626 static void pmap_remove_pt_page(pmap_t pmap, vm_page_t mpte);
627 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
628 struct spglist *free);
629 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
630 vm_page_t m, struct rwlock **lockp);
631 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
633 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
635 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
636 struct rwlock **lockp);
637 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
638 struct rwlock **lockp);
639 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
640 struct rwlock **lockp);
642 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
643 struct spglist *free);
644 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
645 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
648 * Move the kernel virtual free pointer to the next
649 * 2MB. This is used to help improve performance
650 * by using a large (2MB) page for much of the kernel
651 * (.text, .data, .bss)
654 pmap_kmem_choose(vm_offset_t addr)
656 vm_offset_t newaddr = addr;
658 newaddr = roundup2(addr, NBPDR);
662 /********************/
663 /* Inline functions */
664 /********************/
666 /* Return a non-clipped PD index for a given VA */
667 static __inline vm_pindex_t
668 pmap_pde_pindex(vm_offset_t va)
670 return (va >> PDRSHIFT);
674 /* Return various clipped indexes for a given VA */
675 static __inline vm_pindex_t
676 pmap_pte_index(vm_offset_t va)
679 return ((va >> PAGE_SHIFT) & ((1ul << NPTEPGSHIFT) - 1));
682 static __inline vm_pindex_t
683 pmap_pde_index(vm_offset_t va)
686 return ((va >> PDRSHIFT) & ((1ul << NPDEPGSHIFT) - 1));
689 static __inline vm_pindex_t
690 pmap_pdpe_index(vm_offset_t va)
693 return ((va >> PDPSHIFT) & ((1ul << NPDPEPGSHIFT) - 1));
696 static __inline vm_pindex_t
697 pmap_pml4e_index(vm_offset_t va)
700 return ((va >> PML4SHIFT) & ((1ul << NPML4EPGSHIFT) - 1));
703 /* Return a pointer to the PML4 slot that corresponds to a VA */
704 static __inline pml4_entry_t *
705 pmap_pml4e(pmap_t pmap, vm_offset_t va)
708 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
711 /* Return a pointer to the PDP slot that corresponds to a VA */
712 static __inline pdp_entry_t *
713 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
717 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
718 return (&pdpe[pmap_pdpe_index(va)]);
721 /* Return a pointer to the PDP slot that corresponds to a VA */
722 static __inline pdp_entry_t *
723 pmap_pdpe(pmap_t pmap, vm_offset_t va)
728 PG_V = pmap_valid_bit(pmap);
729 pml4e = pmap_pml4e(pmap, va);
730 if ((*pml4e & PG_V) == 0)
732 return (pmap_pml4e_to_pdpe(pml4e, va));
735 /* Return a pointer to the PD slot that corresponds to a VA */
736 static __inline pd_entry_t *
737 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
741 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
742 return (&pde[pmap_pde_index(va)]);
745 /* Return a pointer to the PD slot that corresponds to a VA */
746 static __inline pd_entry_t *
747 pmap_pde(pmap_t pmap, vm_offset_t va)
752 PG_V = pmap_valid_bit(pmap);
753 pdpe = pmap_pdpe(pmap, va);
754 if (pdpe == NULL || (*pdpe & PG_V) == 0)
756 return (pmap_pdpe_to_pde(pdpe, va));
759 /* Return a pointer to the PT slot that corresponds to a VA */
760 static __inline pt_entry_t *
761 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
765 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
766 return (&pte[pmap_pte_index(va)]);
769 /* Return a pointer to the PT slot that corresponds to a VA */
770 static __inline pt_entry_t *
771 pmap_pte(pmap_t pmap, vm_offset_t va)
776 PG_V = pmap_valid_bit(pmap);
777 pde = pmap_pde(pmap, va);
778 if (pde == NULL || (*pde & PG_V) == 0)
780 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
781 return ((pt_entry_t *)pde);
782 return (pmap_pde_to_pte(pde, va));
786 pmap_resident_count_inc(pmap_t pmap, int count)
789 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
790 pmap->pm_stats.resident_count += count;
794 pmap_resident_count_dec(pmap_t pmap, int count)
797 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
798 KASSERT(pmap->pm_stats.resident_count >= count,
799 ("pmap %p resident count underflow %ld %d", pmap,
800 pmap->pm_stats.resident_count, count));
801 pmap->pm_stats.resident_count -= count;
804 PMAP_INLINE pt_entry_t *
805 vtopte(vm_offset_t va)
807 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
809 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
811 return (PTmap + ((va >> PAGE_SHIFT) & mask));
814 static __inline pd_entry_t *
815 vtopde(vm_offset_t va)
817 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
819 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
821 return (PDmap + ((va >> PDRSHIFT) & mask));
825 allocpages(vm_paddr_t *firstaddr, int n)
830 bzero((void *)ret, n * PAGE_SIZE);
831 *firstaddr += n * PAGE_SIZE;
835 CTASSERT(powerof2(NDMPML4E));
837 /* number of kernel PDP slots */
838 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
841 nkpt_init(vm_paddr_t addr)
848 pt_pages = howmany(addr, 1 << PDRSHIFT);
849 pt_pages += NKPDPE(pt_pages);
852 * Add some slop beyond the bare minimum required for bootstrapping
855 * This is quite important when allocating KVA for kernel modules.
856 * The modules are required to be linked in the negative 2GB of
857 * the address space. If we run out of KVA in this region then
858 * pmap_growkernel() will need to allocate page table pages to map
859 * the entire 512GB of KVA space which is an unnecessary tax on
862 * Secondly, device memory mapped as part of setting up the low-
863 * level console(s) is taken from KVA, starting at virtual_avail.
864 * This is because cninit() is called after pmap_bootstrap() but
865 * before vm_init() and pmap_init(). 20MB for a frame buffer is
868 pt_pages += 32; /* 64MB additional slop. */
874 create_pagetables(vm_paddr_t *firstaddr)
876 int i, j, ndm1g, nkpdpe;
882 /* Allocate page table pages for the direct map */
883 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
884 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
886 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
887 if (ndmpdpphys > NDMPML4E) {
889 * Each NDMPML4E allows 512 GB, so limit to that,
890 * and then readjust ndmpdp and ndmpdpphys.
892 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
893 Maxmem = atop(NDMPML4E * NBPML4);
894 ndmpdpphys = NDMPML4E;
895 ndmpdp = NDMPML4E * NPDEPG;
897 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
899 if ((amd_feature & AMDID_PAGE1GB) != 0)
900 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
902 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
903 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
906 KPML4phys = allocpages(firstaddr, 1);
907 KPDPphys = allocpages(firstaddr, NKPML4E);
910 * Allocate the initial number of kernel page table pages required to
911 * bootstrap. We defer this until after all memory-size dependent
912 * allocations are done (e.g. direct map), so that we don't have to
913 * build in too much slop in our estimate.
915 * Note that when NKPML4E > 1, we have an empty page underneath
916 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
917 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
919 nkpt_init(*firstaddr);
920 nkpdpe = NKPDPE(nkpt);
922 KPTphys = allocpages(firstaddr, nkpt);
923 KPDphys = allocpages(firstaddr, nkpdpe);
925 /* Fill in the underlying page table pages */
926 /* Nominally read-only (but really R/W) from zero to physfree */
927 /* XXX not fully used, underneath 2M pages */
928 pt_p = (pt_entry_t *)KPTphys;
929 for (i = 0; ptoa(i) < *firstaddr; i++)
930 pt_p[i] = ptoa(i) | X86_PG_RW | X86_PG_V | X86_PG_G;
932 /* Now map the page tables at their location within PTmap */
933 pd_p = (pd_entry_t *)KPDphys;
934 for (i = 0; i < nkpt; i++)
935 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
937 /* Map from zero to end of allocations under 2M pages */
938 /* This replaces some of the KPTphys entries above */
939 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
940 pd_p[i] = (i << PDRSHIFT) | X86_PG_RW | X86_PG_V | PG_PS |
943 /* And connect up the PD to the PDP (leaving room for L4 pages) */
944 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
945 for (i = 0; i < nkpdpe; i++)
946 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
950 * Now, set up the direct map region using 2MB and/or 1GB pages. If
951 * the end of physical memory is not aligned to a 1GB page boundary,
952 * then the residual physical memory is mapped with 2MB pages. Later,
953 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
954 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
955 * that are partially used.
957 pd_p = (pd_entry_t *)DMPDphys;
958 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
959 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
960 /* Preset PG_M and PG_A because demotion expects it. */
961 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | X86_PG_G |
964 pdp_p = (pdp_entry_t *)DMPDPphys;
965 for (i = 0; i < ndm1g; i++) {
966 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
967 /* Preset PG_M and PG_A because demotion expects it. */
968 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | X86_PG_G |
971 for (j = 0; i < ndmpdp; i++, j++) {
972 pdp_p[i] = DMPDphys + ptoa(j);
973 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_U;
976 /* And recursively map PML4 to itself in order to get PTmap */
977 p4_p = (pml4_entry_t *)KPML4phys;
978 p4_p[PML4PML4I] = KPML4phys;
979 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | PG_U;
981 /* Connect the Direct Map slot(s) up to the PML4. */
982 for (i = 0; i < ndmpdpphys; i++) {
983 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
984 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | PG_U;
987 /* Connect the KVA slots up to the PML4 */
988 for (i = 0; i < NKPML4E; i++) {
989 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
990 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V | PG_U;
995 * Bootstrap the system enough to run with virtual memory.
997 * On amd64 this is called after mapping has already been enabled
998 * and just syncs the pmap module with what has already been done.
999 * [We can't call it easily with mapping off since the kernel is not
1000 * mapped with PA == VA, hence we would have to relocate every address
1001 * from the linked base (virtual) address "KERNBASE" to the actual
1002 * (physical) address starting relative to 0]
1005 pmap_bootstrap(vm_paddr_t *firstaddr)
1012 * Create an initial set of page tables to run the kernel in.
1014 create_pagetables(firstaddr);
1017 * Add a physical memory segment (vm_phys_seg) corresponding to the
1018 * preallocated kernel page table pages so that vm_page structures
1019 * representing these pages will be created. The vm_page structures
1020 * are required for promotion of the corresponding kernel virtual
1021 * addresses to superpage mappings.
1023 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1025 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
1026 virtual_avail = pmap_kmem_choose(virtual_avail);
1028 virtual_end = VM_MAX_KERNEL_ADDRESS;
1031 /* XXX do %cr0 as well */
1032 load_cr4(rcr4() | CR4_PGE);
1033 load_cr3(KPML4phys);
1034 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1035 load_cr4(rcr4() | CR4_SMEP);
1038 * Initialize the kernel pmap (which is statically allocated).
1040 PMAP_LOCK_INIT(kernel_pmap);
1041 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1042 kernel_pmap->pm_cr3 = KPML4phys;
1043 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1044 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1045 kernel_pmap->pm_flags = pmap_flags;
1048 * Initialize the TLB invalidations generation number lock.
1050 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1053 * Reserve some special page table entries/VA space for temporary
1056 #define SYSMAP(c, p, v, n) \
1057 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1063 * Crashdump maps. The first page is reused as CMAP1 for the
1066 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1067 CADDR1 = crashdumpmap;
1071 /* Initialize the PAT MSR. */
1074 /* Initialize TLB Context Id. */
1075 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1076 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1077 /* Check for INVPCID support */
1078 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1080 for (i = 0; i < MAXCPU; i++) {
1081 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1082 kernel_pmap->pm_pcids[i].pm_gen = 1;
1084 __pcpu[0].pc_pcid_next = PMAP_PCID_KERN + 1;
1085 __pcpu[0].pc_pcid_gen = 1;
1087 * pcpu area for APs is zeroed during AP startup.
1088 * pc_pcid_next and pc_pcid_gen are initialized by AP
1089 * during pcpu setup.
1091 load_cr4(rcr4() | CR4_PCIDE);
1093 pmap_pcid_enabled = 0;
1098 * Setup the PAT MSR.
1103 int pat_table[PAT_INDEX_SIZE];
1108 /* Bail if this CPU doesn't implement PAT. */
1109 if ((cpu_feature & CPUID_PAT) == 0)
1112 /* Set default PAT index table. */
1113 for (i = 0; i < PAT_INDEX_SIZE; i++)
1115 pat_table[PAT_WRITE_BACK] = 0;
1116 pat_table[PAT_WRITE_THROUGH] = 1;
1117 pat_table[PAT_UNCACHEABLE] = 3;
1118 pat_table[PAT_WRITE_COMBINING] = 3;
1119 pat_table[PAT_WRITE_PROTECTED] = 3;
1120 pat_table[PAT_UNCACHED] = 3;
1122 /* Initialize default PAT entries. */
1123 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1124 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1125 PAT_VALUE(2, PAT_UNCACHED) |
1126 PAT_VALUE(3, PAT_UNCACHEABLE) |
1127 PAT_VALUE(4, PAT_WRITE_BACK) |
1128 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1129 PAT_VALUE(6, PAT_UNCACHED) |
1130 PAT_VALUE(7, PAT_UNCACHEABLE);
1134 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1135 * Program 5 and 6 as WP and WC.
1136 * Leave 4 and 7 as WB and UC.
1138 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1139 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1140 PAT_VALUE(6, PAT_WRITE_COMBINING);
1141 pat_table[PAT_UNCACHED] = 2;
1142 pat_table[PAT_WRITE_PROTECTED] = 5;
1143 pat_table[PAT_WRITE_COMBINING] = 6;
1146 * Just replace PAT Index 2 with WC instead of UC-.
1148 pat_msr &= ~PAT_MASK(2);
1149 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1150 pat_table[PAT_WRITE_COMBINING] = 2;
1155 load_cr4(cr4 & ~CR4_PGE);
1157 /* Disable caches (CD = 1, NW = 0). */
1159 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1161 /* Flushes caches and TLBs. */
1165 /* Update PAT and index table. */
1166 wrmsr(MSR_PAT, pat_msr);
1167 for (i = 0; i < PAT_INDEX_SIZE; i++)
1168 pat_index[i] = pat_table[i];
1170 /* Flush caches and TLBs again. */
1174 /* Restore caches and PGE. */
1180 * Initialize a vm_page's machine-dependent fields.
1183 pmap_page_init(vm_page_t m)
1186 TAILQ_INIT(&m->md.pv_list);
1187 m->md.pat_mode = PAT_WRITE_BACK;
1191 * Initialize the pmap module.
1192 * Called by vm_init, to initialize any structures that the pmap
1193 * system needs to map virtual memory.
1198 struct pmap_preinit_mapping *ppim;
1201 int error, i, pv_npg;
1204 * Initialize the vm page array entries for the kernel pmap's
1207 for (i = 0; i < nkpt; i++) {
1208 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1209 KASSERT(mpte >= vm_page_array &&
1210 mpte < &vm_page_array[vm_page_array_size],
1211 ("pmap_init: page table page is out of range"));
1212 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1213 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1217 * If the kernel is running on a virtual machine, then it must assume
1218 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1219 * be prepared for the hypervisor changing the vendor and family that
1220 * are reported by CPUID. Consequently, the workaround for AMD Family
1221 * 10h Erratum 383 is enabled if the processor's feature set does not
1222 * include at least one feature that is only supported by older Intel
1223 * or newer AMD processors.
1225 if (vm_guest == VM_GUEST_VM && (cpu_feature & CPUID_SS) == 0 &&
1226 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1227 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1229 workaround_erratum383 = 1;
1232 * Are large page mappings enabled?
1234 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1235 if (pg_ps_enabled) {
1236 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1237 ("pmap_init: can't assign to pagesizes[1]"));
1238 pagesizes[1] = NBPDR;
1242 * Initialize the pv chunk list mutex.
1244 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1247 * Initialize the pool of pv list locks.
1249 for (i = 0; i < NPV_LIST_LOCKS; i++)
1250 rw_init(&pv_list_locks[i], "pmap pv list");
1253 * Calculate the size of the pv head table for superpages.
1255 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1258 * Allocate memory for the pv head table for superpages.
1260 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1262 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1264 for (i = 0; i < pv_npg; i++)
1265 TAILQ_INIT(&pv_table[i].pv_list);
1267 pmap_initialized = 1;
1268 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1269 ppim = pmap_preinit_mapping + i;
1272 /* Make the direct map consistent */
1273 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1274 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1275 ppim->sz, ppim->mode);
1279 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1280 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1283 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1284 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1285 (vmem_addr_t *)&qframe);
1287 panic("qframe allocation failed");
1290 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1291 "2MB page mapping counters");
1293 static u_long pmap_pde_demotions;
1294 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1295 &pmap_pde_demotions, 0, "2MB page demotions");
1297 static u_long pmap_pde_mappings;
1298 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1299 &pmap_pde_mappings, 0, "2MB page mappings");
1301 static u_long pmap_pde_p_failures;
1302 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1303 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1305 static u_long pmap_pde_promotions;
1306 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1307 &pmap_pde_promotions, 0, "2MB page promotions");
1309 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1310 "1GB page mapping counters");
1312 static u_long pmap_pdpe_demotions;
1313 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1314 &pmap_pdpe_demotions, 0, "1GB page demotions");
1316 /***************************************************
1317 * Low level helper routines.....
1318 ***************************************************/
1321 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1323 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1325 switch (pmap->pm_type) {
1328 /* Verify that both PAT bits are not set at the same time */
1329 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1330 ("Invalid PAT bits in entry %#lx", entry));
1332 /* Swap the PAT bits if one of them is set */
1333 if ((entry & x86_pat_bits) != 0)
1334 entry ^= x86_pat_bits;
1338 * Nothing to do - the memory attributes are represented
1339 * the same way for regular pages and superpages.
1343 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1350 * Determine the appropriate bits to set in a PTE or PDE for a specified
1354 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1356 int cache_bits, pat_flag, pat_idx;
1358 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1359 panic("Unknown caching mode %d\n", mode);
1361 switch (pmap->pm_type) {
1364 /* The PAT bit is different for PTE's and PDE's. */
1365 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1367 /* Map the caching mode to a PAT index. */
1368 pat_idx = pat_index[mode];
1370 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1373 cache_bits |= pat_flag;
1375 cache_bits |= PG_NC_PCD;
1377 cache_bits |= PG_NC_PWT;
1381 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1385 panic("unsupported pmap type %d", pmap->pm_type);
1388 return (cache_bits);
1392 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1396 switch (pmap->pm_type) {
1399 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1402 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1405 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1411 static __inline boolean_t
1412 pmap_ps_enabled(pmap_t pmap)
1415 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1419 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1422 switch (pmap->pm_type) {
1429 * This is a little bogus since the generation number is
1430 * supposed to be bumped up when a region of the address
1431 * space is invalidated in the page tables.
1433 * In this case the old PDE entry is valid but yet we want
1434 * to make sure that any mappings using the old entry are
1435 * invalidated in the TLB.
1437 * The reason this works as expected is because we rendezvous
1438 * "all" host cpus and force any vcpu context to exit as a
1441 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1444 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1446 pde_store(pde, newpde);
1450 * After changing the page size for the specified virtual address in the page
1451 * table, flush the corresponding entries from the processor's TLB. Only the
1452 * calling processor's TLB is affected.
1454 * The calling thread must be pinned to a processor.
1457 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1461 if (pmap_type_guest(pmap))
1464 KASSERT(pmap->pm_type == PT_X86,
1465 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1467 PG_G = pmap_global_bit(pmap);
1469 if ((newpde & PG_PS) == 0)
1470 /* Demotion: flush a specific 2MB page mapping. */
1472 else if ((newpde & PG_G) == 0)
1474 * Promotion: flush every 4KB page mapping from the TLB
1475 * because there are too many to flush individually.
1480 * Promotion: flush every 4KB page mapping from the TLB,
1481 * including any global (PG_G) mappings.
1489 * For SMP, these functions have to use the IPI mechanism for coherence.
1491 * N.B.: Before calling any of the following TLB invalidation functions,
1492 * the calling processor must ensure that all stores updating a non-
1493 * kernel page table are globally performed. Otherwise, another
1494 * processor could cache an old, pre-update entry without being
1495 * invalidated. This can happen one of two ways: (1) The pmap becomes
1496 * active on another processor after its pm_active field is checked by
1497 * one of the following functions but before a store updating the page
1498 * table is globally performed. (2) The pmap becomes active on another
1499 * processor before its pm_active field is checked but due to
1500 * speculative loads one of the following functions stills reads the
1501 * pmap as inactive on the other processor.
1503 * The kernel page table is exempt because its pm_active field is
1504 * immutable. The kernel page table is always active on every
1509 * Interrupt the cpus that are executing in the guest context.
1510 * This will force the vcpu to exit and the cached EPT mappings
1511 * will be invalidated by the host before the next vmresume.
1513 static __inline void
1514 pmap_invalidate_ept(pmap_t pmap)
1519 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1520 ("pmap_invalidate_ept: absurd pm_active"));
1523 * The TLB mappings associated with a vcpu context are not
1524 * flushed each time a different vcpu is chosen to execute.
1526 * This is in contrast with a process's vtop mappings that
1527 * are flushed from the TLB on each context switch.
1529 * Therefore we need to do more than just a TLB shootdown on
1530 * the active cpus in 'pmap->pm_active'. To do this we keep
1531 * track of the number of invalidations performed on this pmap.
1533 * Each vcpu keeps a cache of this counter and compares it
1534 * just before a vmresume. If the counter is out-of-date an
1535 * invept will be done to flush stale mappings from the TLB.
1537 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1540 * Force the vcpu to exit and trap back into the hypervisor.
1542 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1543 ipi_selected(pmap->pm_active, ipinum);
1548 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1553 if (pmap_type_guest(pmap)) {
1554 pmap_invalidate_ept(pmap);
1558 KASSERT(pmap->pm_type == PT_X86,
1559 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1562 if (pmap == kernel_pmap) {
1566 cpuid = PCPU_GET(cpuid);
1567 if (pmap == PCPU_GET(curpmap))
1569 else if (pmap_pcid_enabled)
1570 pmap->pm_pcids[cpuid].pm_gen = 0;
1571 if (pmap_pcid_enabled) {
1574 pmap->pm_pcids[i].pm_gen = 0;
1577 mask = &pmap->pm_active;
1579 smp_masked_invlpg(*mask, va);
1583 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1584 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1587 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1593 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1594 pmap_invalidate_all(pmap);
1598 if (pmap_type_guest(pmap)) {
1599 pmap_invalidate_ept(pmap);
1603 KASSERT(pmap->pm_type == PT_X86,
1604 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1607 cpuid = PCPU_GET(cpuid);
1608 if (pmap == kernel_pmap) {
1609 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1613 if (pmap == PCPU_GET(curpmap)) {
1614 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1616 } else if (pmap_pcid_enabled) {
1617 pmap->pm_pcids[cpuid].pm_gen = 0;
1619 if (pmap_pcid_enabled) {
1622 pmap->pm_pcids[i].pm_gen = 0;
1625 mask = &pmap->pm_active;
1627 smp_masked_invlpg_range(*mask, sva, eva);
1632 pmap_invalidate_all(pmap_t pmap)
1635 struct invpcid_descr d;
1638 if (pmap_type_guest(pmap)) {
1639 pmap_invalidate_ept(pmap);
1643 KASSERT(pmap->pm_type == PT_X86,
1644 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1647 if (pmap == kernel_pmap) {
1648 if (pmap_pcid_enabled && invpcid_works) {
1649 bzero(&d, sizeof(d));
1650 invpcid(&d, INVPCID_CTXGLOB);
1656 cpuid = PCPU_GET(cpuid);
1657 if (pmap == PCPU_GET(curpmap)) {
1658 if (pmap_pcid_enabled) {
1659 if (invpcid_works) {
1660 d.pcid = pmap->pm_pcids[cpuid].pm_pcid;
1663 invpcid(&d, INVPCID_CTX);
1665 load_cr3(pmap->pm_cr3 | pmap->pm_pcids
1666 [PCPU_GET(cpuid)].pm_pcid);
1671 } else if (pmap_pcid_enabled) {
1672 pmap->pm_pcids[cpuid].pm_gen = 0;
1674 if (pmap_pcid_enabled) {
1677 pmap->pm_pcids[i].pm_gen = 0;
1680 mask = &pmap->pm_active;
1682 smp_masked_invltlb(*mask, pmap);
1687 pmap_invalidate_cache(void)
1697 cpuset_t invalidate; /* processors that invalidate their TLB */
1702 u_int store; /* processor that updates the PDE */
1706 pmap_update_pde_action(void *arg)
1708 struct pde_action *act = arg;
1710 if (act->store == PCPU_GET(cpuid))
1711 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1715 pmap_update_pde_teardown(void *arg)
1717 struct pde_action *act = arg;
1719 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1720 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1724 * Change the page size for the specified virtual address in a way that
1725 * prevents any possibility of the TLB ever having two entries that map the
1726 * same virtual address using different page sizes. This is the recommended
1727 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1728 * machine check exception for a TLB state that is improperly diagnosed as a
1732 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1734 struct pde_action act;
1735 cpuset_t active, other_cpus;
1739 cpuid = PCPU_GET(cpuid);
1740 other_cpus = all_cpus;
1741 CPU_CLR(cpuid, &other_cpus);
1742 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1745 active = pmap->pm_active;
1747 if (CPU_OVERLAP(&active, &other_cpus)) {
1749 act.invalidate = active;
1753 act.newpde = newpde;
1754 CPU_SET(cpuid, &active);
1755 smp_rendezvous_cpus(active,
1756 smp_no_rendevous_barrier, pmap_update_pde_action,
1757 pmap_update_pde_teardown, &act);
1759 pmap_update_pde_store(pmap, pde, newpde);
1760 if (CPU_ISSET(cpuid, &active))
1761 pmap_update_pde_invalidate(pmap, va, newpde);
1767 * Normal, non-SMP, invalidation functions.
1770 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1773 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1777 KASSERT(pmap->pm_type == PT_X86,
1778 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1780 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1782 else if (pmap_pcid_enabled)
1783 pmap->pm_pcids[0].pm_gen = 0;
1787 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1791 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1795 KASSERT(pmap->pm_type == PT_X86,
1796 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1798 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1799 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1801 } else if (pmap_pcid_enabled) {
1802 pmap->pm_pcids[0].pm_gen = 0;
1807 pmap_invalidate_all(pmap_t pmap)
1809 struct invpcid_descr d;
1811 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1815 KASSERT(pmap->pm_type == PT_X86,
1816 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
1818 if (pmap == kernel_pmap) {
1819 if (pmap_pcid_enabled && invpcid_works) {
1820 bzero(&d, sizeof(d));
1821 invpcid(&d, INVPCID_CTXGLOB);
1825 } else if (pmap == PCPU_GET(curpmap)) {
1826 if (pmap_pcid_enabled) {
1827 if (invpcid_works) {
1828 d.pcid = pmap->pm_pcids[0].pm_pcid;
1831 invpcid(&d, INVPCID_CTX);
1833 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[0].
1839 } else if (pmap_pcid_enabled) {
1840 pmap->pm_pcids[0].pm_gen = 0;
1845 pmap_invalidate_cache(void)
1852 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1855 pmap_update_pde_store(pmap, pde, newpde);
1856 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1857 pmap_update_pde_invalidate(pmap, va, newpde);
1859 pmap->pm_pcids[0].pm_gen = 0;
1863 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
1866 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
1870 sva &= ~(vm_offset_t)cpu_clflush_line_size;
1872 KASSERT((sva & PAGE_MASK) == 0,
1873 ("pmap_invalidate_cache_range: sva not page-aligned"));
1874 KASSERT((eva & PAGE_MASK) == 0,
1875 ("pmap_invalidate_cache_range: eva not page-aligned"));
1878 if ((cpu_feature & CPUID_SS) != 0 && !force)
1879 ; /* If "Self Snoop" is supported and allowed, do nothing. */
1880 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
1881 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1883 * XXX: Some CPUs fault, hang, or trash the local APIC
1884 * registers if we use CLFLUSH on the local APIC
1885 * range. The local APIC is always uncached, so we
1886 * don't need to flush for that range anyway.
1888 if (pmap_kextract(sva) == lapic_paddr)
1892 * Otherwise, do per-cache line flush. Use the mfence
1893 * instruction to insure that previous stores are
1894 * included in the write-back. The processor
1895 * propagates flush to other processors in the cache
1899 for (; sva < eva; sva += cpu_clflush_line_size)
1902 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
1903 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1904 if (pmap_kextract(sva) == lapic_paddr)
1907 * Writes are ordered by CLFLUSH on Intel CPUs.
1909 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1911 for (; sva < eva; sva += cpu_clflush_line_size)
1913 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1918 * No targeted cache flush methods are supported by CPU,
1919 * or the supplied range is bigger than 2MB.
1920 * Globally invalidate cache.
1922 pmap_invalidate_cache();
1927 * Remove the specified set of pages from the data and instruction caches.
1929 * In contrast to pmap_invalidate_cache_range(), this function does not
1930 * rely on the CPU's self-snoop feature, because it is intended for use
1931 * when moving pages into a different cache domain.
1934 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1936 vm_offset_t daddr, eva;
1940 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
1941 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1942 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
1943 pmap_invalidate_cache();
1945 if (useclflushopt || cpu_vendor_id != CPU_VENDOR_INTEL)
1947 for (i = 0; i < count; i++) {
1948 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
1949 eva = daddr + PAGE_SIZE;
1950 for (; daddr < eva; daddr += cpu_clflush_line_size) {
1957 if (useclflushopt || cpu_vendor_id != CPU_VENDOR_INTEL)
1963 * Routine: pmap_extract
1965 * Extract the physical page address associated
1966 * with the given map/virtual_address pair.
1969 pmap_extract(pmap_t pmap, vm_offset_t va)
1973 pt_entry_t *pte, PG_V;
1977 PG_V = pmap_valid_bit(pmap);
1979 pdpe = pmap_pdpe(pmap, va);
1980 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
1981 if ((*pdpe & PG_PS) != 0)
1982 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
1984 pde = pmap_pdpe_to_pde(pdpe, va);
1985 if ((*pde & PG_V) != 0) {
1986 if ((*pde & PG_PS) != 0) {
1987 pa = (*pde & PG_PS_FRAME) |
1990 pte = pmap_pde_to_pte(pde, va);
1991 pa = (*pte & PG_FRAME) |
2002 * Routine: pmap_extract_and_hold
2004 * Atomically extract and hold the physical page
2005 * with the given pmap and virtual address pair
2006 * if that mapping permits the given protection.
2009 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
2011 pd_entry_t pde, *pdep;
2012 pt_entry_t pte, PG_RW, PG_V;
2018 PG_RW = pmap_rw_bit(pmap);
2019 PG_V = pmap_valid_bit(pmap);
2022 pdep = pmap_pde(pmap, va);
2023 if (pdep != NULL && (pde = *pdep)) {
2025 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2026 if (vm_page_pa_tryrelock(pmap, (pde &
2027 PG_PS_FRAME) | (va & PDRMASK), &pa))
2029 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
2034 pte = *pmap_pde_to_pte(pdep, va);
2036 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2037 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2040 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
2051 pmap_kextract(vm_offset_t va)
2056 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2057 pa = DMAP_TO_PHYS(va);
2061 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2064 * Beware of a concurrent promotion that changes the
2065 * PDE at this point! For example, vtopte() must not
2066 * be used to access the PTE because it would use the
2067 * new PDE. It is, however, safe to use the old PDE
2068 * because the page table page is preserved by the
2071 pa = *pmap_pde_to_pte(&pde, va);
2072 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2078 /***************************************************
2079 * Low level mapping routines.....
2080 ***************************************************/
2083 * Add a wired page to the kva.
2084 * Note: not SMP coherent.
2087 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2092 pte_store(pte, pa | X86_PG_RW | X86_PG_V | X86_PG_G);
2095 static __inline void
2096 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2102 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2103 pte_store(pte, pa | X86_PG_RW | X86_PG_V | X86_PG_G | cache_bits);
2107 * Remove a page from the kernel pagetables.
2108 * Note: not SMP coherent.
2111 pmap_kremove(vm_offset_t va)
2120 * Used to map a range of physical addresses into kernel
2121 * virtual address space.
2123 * The value passed in '*virt' is a suggested virtual address for
2124 * the mapping. Architectures which can support a direct-mapped
2125 * physical to virtual region can return the appropriate address
2126 * within that region, leaving '*virt' unchanged. Other
2127 * architectures should map the pages starting at '*virt' and
2128 * update '*virt' with the first usable address after the mapped
2132 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2134 return PHYS_TO_DMAP(start);
2139 * Add a list of wired pages to the kva
2140 * this routine is only used for temporary
2141 * kernel mappings that do not need to have
2142 * page modification or references recorded.
2143 * Note that old mappings are simply written
2144 * over. The page *must* be wired.
2145 * Note: SMP coherent. Uses a ranged shootdown IPI.
2148 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2150 pt_entry_t *endpte, oldpte, pa, *pte;
2156 endpte = pte + count;
2157 while (pte < endpte) {
2159 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2160 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2161 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2163 pte_store(pte, pa | X86_PG_G | X86_PG_RW | X86_PG_V);
2167 if (__predict_false((oldpte & X86_PG_V) != 0))
2168 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2173 * This routine tears out page mappings from the
2174 * kernel -- it is meant only for temporary mappings.
2175 * Note: SMP coherent. Uses a ranged shootdown IPI.
2178 pmap_qremove(vm_offset_t sva, int count)
2183 while (count-- > 0) {
2184 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2188 pmap_invalidate_range(kernel_pmap, sva, va);
2191 /***************************************************
2192 * Page table page management routines.....
2193 ***************************************************/
2194 static __inline void
2195 pmap_free_zero_pages(struct spglist *free)
2199 while ((m = SLIST_FIRST(free)) != NULL) {
2200 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2201 /* Preserve the page's PG_ZERO setting. */
2202 vm_page_free_toq(m);
2207 * Schedule the specified unused page table page to be freed. Specifically,
2208 * add the page to the specified list of pages that will be released to the
2209 * physical memory manager after the TLB has been updated.
2211 static __inline void
2212 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2213 boolean_t set_PG_ZERO)
2217 m->flags |= PG_ZERO;
2219 m->flags &= ~PG_ZERO;
2220 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2224 * Inserts the specified page table page into the specified pmap's collection
2225 * of idle page table pages. Each of a pmap's page table pages is responsible
2226 * for mapping a distinct range of virtual addresses. The pmap's collection is
2227 * ordered by this virtual address range.
2230 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2233 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2234 return (vm_radix_insert(&pmap->pm_root, mpte));
2238 * Looks for a page table page mapping the specified virtual address in the
2239 * specified pmap's collection of idle page table pages. Returns NULL if there
2240 * is no page table page corresponding to the specified virtual address.
2242 static __inline vm_page_t
2243 pmap_lookup_pt_page(pmap_t pmap, vm_offset_t va)
2246 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2247 return (vm_radix_lookup(&pmap->pm_root, pmap_pde_pindex(va)));
2251 * Removes the specified page table page from the specified pmap's collection
2252 * of idle page table pages. The specified page table page must be a member of
2253 * the pmap's collection.
2255 static __inline void
2256 pmap_remove_pt_page(pmap_t pmap, vm_page_t mpte)
2259 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2260 vm_radix_remove(&pmap->pm_root, mpte->pindex);
2264 * Decrements a page table page's wire count, which is used to record the
2265 * number of valid page table entries within the page. If the wire count
2266 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2267 * page table page was unmapped and FALSE otherwise.
2269 static inline boolean_t
2270 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2274 if (m->wire_count == 0) {
2275 _pmap_unwire_ptp(pmap, va, m, free);
2282 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2285 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2287 * unmap the page table page
2289 if (m->pindex >= (NUPDE + NUPDPE)) {
2292 pml4 = pmap_pml4e(pmap, va);
2294 } else if (m->pindex >= NUPDE) {
2297 pdp = pmap_pdpe(pmap, va);
2302 pd = pmap_pde(pmap, va);
2305 pmap_resident_count_dec(pmap, 1);
2306 if (m->pindex < NUPDE) {
2307 /* We just released a PT, unhold the matching PD */
2310 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2311 pmap_unwire_ptp(pmap, va, pdpg, free);
2313 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2314 /* We just released a PD, unhold the matching PDP */
2317 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2318 pmap_unwire_ptp(pmap, va, pdppg, free);
2322 * This is a release store so that the ordinary store unmapping
2323 * the page table page is globally performed before TLB shoot-
2326 atomic_subtract_rel_int(&vm_cnt.v_wire_count, 1);
2329 * Put page on a list so that it is released after
2330 * *ALL* TLB shootdown is done
2332 pmap_add_delayed_free_list(m, free, TRUE);
2336 * After removing a page table entry, this routine is used to
2337 * conditionally free the page, and manage the hold/wire counts.
2340 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2341 struct spglist *free)
2345 if (va >= VM_MAXUSER_ADDRESS)
2347 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2348 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2349 return (pmap_unwire_ptp(pmap, va, mpte, free));
2353 pmap_pinit0(pmap_t pmap)
2357 PMAP_LOCK_INIT(pmap);
2358 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2359 pmap->pm_cr3 = KPML4phys;
2360 pmap->pm_root.rt_root = 0;
2361 CPU_ZERO(&pmap->pm_active);
2362 TAILQ_INIT(&pmap->pm_pvchunk);
2363 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2364 pmap->pm_flags = pmap_flags;
2366 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2367 pmap->pm_pcids[i].pm_gen = 0;
2369 PCPU_SET(curpmap, kernel_pmap);
2370 pmap_activate(curthread);
2371 CPU_FILL(&kernel_pmap->pm_active);
2375 * Initialize a preallocated and zeroed pmap structure,
2376 * such as one in a vmspace structure.
2379 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2382 vm_paddr_t pml4phys;
2386 * allocate the page directory page
2388 while ((pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2389 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL)
2392 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2393 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2395 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2396 pmap->pm_pcids[i].pm_gen = 0;
2398 pmap->pm_cr3 = ~0; /* initialize to an invalid value */
2400 if ((pml4pg->flags & PG_ZERO) == 0)
2401 pagezero(pmap->pm_pml4);
2404 * Do not install the host kernel mappings in the nested page
2405 * tables. These mappings are meaningless in the guest physical
2408 if ((pmap->pm_type = pm_type) == PT_X86) {
2409 pmap->pm_cr3 = pml4phys;
2411 /* Wire in kernel global address entries. */
2412 for (i = 0; i < NKPML4E; i++) {
2413 pmap->pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) |
2414 X86_PG_RW | X86_PG_V | PG_U;
2416 for (i = 0; i < ndmpdpphys; i++) {
2417 pmap->pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) |
2418 X86_PG_RW | X86_PG_V | PG_U;
2421 /* install self-referential address mapping entry(s) */
2422 pmap->pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) |
2423 X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
2426 pmap->pm_root.rt_root = 0;
2427 CPU_ZERO(&pmap->pm_active);
2428 TAILQ_INIT(&pmap->pm_pvchunk);
2429 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2430 pmap->pm_flags = flags;
2431 pmap->pm_eptgen = 0;
2437 pmap_pinit(pmap_t pmap)
2440 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2444 * This routine is called if the desired page table page does not exist.
2446 * If page table page allocation fails, this routine may sleep before
2447 * returning NULL. It sleeps only if a lock pointer was given.
2449 * Note: If a page allocation fails at page table level two or three,
2450 * one or two pages may be held during the wait, only to be released
2451 * afterwards. This conservative approach is easily argued to avoid
2455 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2457 vm_page_t m, pdppg, pdpg;
2458 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2460 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2462 PG_A = pmap_accessed_bit(pmap);
2463 PG_M = pmap_modified_bit(pmap);
2464 PG_V = pmap_valid_bit(pmap);
2465 PG_RW = pmap_rw_bit(pmap);
2468 * Allocate a page table page.
2470 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2471 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2472 if (lockp != NULL) {
2473 RELEASE_PV_LIST_LOCK(lockp);
2475 PMAP_ASSERT_NOT_IN_DI();
2481 * Indicate the need to retry. While waiting, the page table
2482 * page may have been allocated.
2486 if ((m->flags & PG_ZERO) == 0)
2490 * Map the pagetable page into the process address space, if
2491 * it isn't already there.
2494 if (ptepindex >= (NUPDE + NUPDPE)) {
2496 vm_pindex_t pml4index;
2498 /* Wire up a new PDPE page */
2499 pml4index = ptepindex - (NUPDE + NUPDPE);
2500 pml4 = &pmap->pm_pml4[pml4index];
2501 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2503 } else if (ptepindex >= NUPDE) {
2504 vm_pindex_t pml4index;
2505 vm_pindex_t pdpindex;
2509 /* Wire up a new PDE page */
2510 pdpindex = ptepindex - NUPDE;
2511 pml4index = pdpindex >> NPML4EPGSHIFT;
2513 pml4 = &pmap->pm_pml4[pml4index];
2514 if ((*pml4 & PG_V) == 0) {
2515 /* Have to allocate a new pdp, recurse */
2516 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2519 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2520 vm_page_free_zero(m);
2524 /* Add reference to pdp page */
2525 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2526 pdppg->wire_count++;
2528 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2530 /* Now find the pdp page */
2531 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2532 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2535 vm_pindex_t pml4index;
2536 vm_pindex_t pdpindex;
2541 /* Wire up a new PTE page */
2542 pdpindex = ptepindex >> NPDPEPGSHIFT;
2543 pml4index = pdpindex >> NPML4EPGSHIFT;
2545 /* First, find the pdp and check that its valid. */
2546 pml4 = &pmap->pm_pml4[pml4index];
2547 if ((*pml4 & PG_V) == 0) {
2548 /* Have to allocate a new pd, recurse */
2549 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2552 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2553 vm_page_free_zero(m);
2556 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2557 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2559 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2560 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2561 if ((*pdp & 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,
2568 vm_page_free_zero(m);
2572 /* Add reference to the pd page */
2573 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2577 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2579 /* Now we know where the page directory page is */
2580 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2581 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2584 pmap_resident_count_inc(pmap, 1);
2590 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2592 vm_pindex_t pdpindex, ptepindex;
2593 pdp_entry_t *pdpe, PG_V;
2596 PG_V = pmap_valid_bit(pmap);
2599 pdpe = pmap_pdpe(pmap, va);
2600 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2601 /* Add a reference to the pd page. */
2602 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2605 /* Allocate a pd page. */
2606 ptepindex = pmap_pde_pindex(va);
2607 pdpindex = ptepindex >> NPDPEPGSHIFT;
2608 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2609 if (pdpg == NULL && lockp != NULL)
2616 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2618 vm_pindex_t ptepindex;
2619 pd_entry_t *pd, PG_V;
2622 PG_V = pmap_valid_bit(pmap);
2625 * Calculate pagetable page index
2627 ptepindex = pmap_pde_pindex(va);
2630 * Get the page directory entry
2632 pd = pmap_pde(pmap, va);
2635 * This supports switching from a 2MB page to a
2638 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2639 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2641 * Invalidation of the 2MB page mapping may have caused
2642 * the deallocation of the underlying PD page.
2649 * If the page table page is mapped, we just increment the
2650 * hold count, and activate it.
2652 if (pd != NULL && (*pd & PG_V) != 0) {
2653 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2657 * Here if the pte page isn't mapped, or if it has been
2660 m = _pmap_allocpte(pmap, ptepindex, lockp);
2661 if (m == NULL && lockp != NULL)
2668 /***************************************************
2669 * Pmap allocation/deallocation routines.
2670 ***************************************************/
2673 * Release any resources held by the given physical map.
2674 * Called when a pmap initialized by pmap_pinit is being released.
2675 * Should only be called if the map contains no valid mappings.
2678 pmap_release(pmap_t pmap)
2683 KASSERT(pmap->pm_stats.resident_count == 0,
2684 ("pmap_release: pmap resident count %ld != 0",
2685 pmap->pm_stats.resident_count));
2686 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2687 ("pmap_release: pmap has reserved page table page(s)"));
2688 KASSERT(CPU_EMPTY(&pmap->pm_active),
2689 ("releasing active pmap %p", pmap));
2691 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2693 for (i = 0; i < NKPML4E; i++) /* KVA */
2694 pmap->pm_pml4[KPML4BASE + i] = 0;
2695 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
2696 pmap->pm_pml4[DMPML4I + i] = 0;
2697 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
2700 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2701 vm_page_free_zero(m);
2705 kvm_size(SYSCTL_HANDLER_ARGS)
2707 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2709 return sysctl_handle_long(oidp, &ksize, 0, req);
2711 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2712 0, 0, kvm_size, "LU", "Size of KVM");
2715 kvm_free(SYSCTL_HANDLER_ARGS)
2717 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2719 return sysctl_handle_long(oidp, &kfree, 0, req);
2721 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2722 0, 0, kvm_free, "LU", "Amount of KVM free");
2725 * grow the number of kernel page table entries, if needed
2728 pmap_growkernel(vm_offset_t addr)
2732 pd_entry_t *pde, newpdir;
2735 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2738 * Return if "addr" is within the range of kernel page table pages
2739 * that were preallocated during pmap bootstrap. Moreover, leave
2740 * "kernel_vm_end" and the kernel page table as they were.
2742 * The correctness of this action is based on the following
2743 * argument: vm_map_insert() allocates contiguous ranges of the
2744 * kernel virtual address space. It calls this function if a range
2745 * ends after "kernel_vm_end". If the kernel is mapped between
2746 * "kernel_vm_end" and "addr", then the range cannot begin at
2747 * "kernel_vm_end". In fact, its beginning address cannot be less
2748 * than the kernel. Thus, there is no immediate need to allocate
2749 * any new kernel page table pages between "kernel_vm_end" and
2752 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
2755 addr = roundup2(addr, NBPDR);
2756 if (addr - 1 >= kernel_map->max_offset)
2757 addr = kernel_map->max_offset;
2758 while (kernel_vm_end < addr) {
2759 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
2760 if ((*pdpe & X86_PG_V) == 0) {
2761 /* We need a new PDP entry */
2762 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
2763 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
2764 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2766 panic("pmap_growkernel: no memory to grow kernel");
2767 if ((nkpg->flags & PG_ZERO) == 0)
2768 pmap_zero_page(nkpg);
2769 paddr = VM_PAGE_TO_PHYS(nkpg);
2770 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
2771 X86_PG_A | X86_PG_M);
2772 continue; /* try again */
2774 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
2775 if ((*pde & X86_PG_V) != 0) {
2776 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2777 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2778 kernel_vm_end = kernel_map->max_offset;
2784 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
2785 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
2788 panic("pmap_growkernel: no memory to grow kernel");
2789 if ((nkpg->flags & PG_ZERO) == 0)
2790 pmap_zero_page(nkpg);
2791 paddr = VM_PAGE_TO_PHYS(nkpg);
2792 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
2793 pde_store(pde, newpdir);
2795 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2796 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2797 kernel_vm_end = kernel_map->max_offset;
2804 /***************************************************
2805 * page management routines.
2806 ***************************************************/
2808 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
2809 CTASSERT(_NPCM == 3);
2810 CTASSERT(_NPCPV == 168);
2812 static __inline struct pv_chunk *
2813 pv_to_chunk(pv_entry_t pv)
2816 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
2819 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
2821 #define PC_FREE0 0xfffffffffffffffful
2822 #define PC_FREE1 0xfffffffffffffffful
2823 #define PC_FREE2 0x000000fffffffffful
2825 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
2828 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2830 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2831 "Current number of pv entry chunks");
2832 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2833 "Current number of pv entry chunks allocated");
2834 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2835 "Current number of pv entry chunks frees");
2836 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
2837 "Number of times tried to get a chunk page but failed.");
2839 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
2840 static int pv_entry_spare;
2842 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2843 "Current number of pv entry frees");
2844 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
2845 "Current number of pv entry allocs");
2846 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2847 "Current number of pv entries");
2848 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2849 "Current number of spare pv entries");
2853 * We are in a serious low memory condition. Resort to
2854 * drastic measures to free some pages so we can allocate
2855 * another pv entry chunk.
2857 * Returns NULL if PV entries were reclaimed from the specified pmap.
2859 * We do not, however, unmap 2mpages because subsequent accesses will
2860 * allocate per-page pv entries until repromotion occurs, thereby
2861 * exacerbating the shortage of free pv entries.
2864 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
2866 struct pch new_tail;
2867 struct pv_chunk *pc;
2868 struct md_page *pvh;
2871 pt_entry_t *pte, tpte;
2872 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
2876 struct spglist free;
2878 int bit, field, freed;
2880 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2881 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
2884 PG_G = PG_A = PG_M = PG_RW = 0;
2886 TAILQ_INIT(&new_tail);
2887 pmap_delayed_invl_started();
2888 mtx_lock(&pv_chunks_mutex);
2889 while ((pc = TAILQ_FIRST(&pv_chunks)) != NULL && SLIST_EMPTY(&free)) {
2890 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2891 mtx_unlock(&pv_chunks_mutex);
2892 if (pmap != pc->pc_pmap) {
2894 pmap_invalidate_all(pmap);
2895 if (pmap != locked_pmap)
2898 pmap_delayed_invl_finished();
2899 pmap_delayed_invl_started();
2901 /* Avoid deadlock and lock recursion. */
2902 if (pmap > locked_pmap) {
2903 RELEASE_PV_LIST_LOCK(lockp);
2905 } else if (pmap != locked_pmap &&
2906 !PMAP_TRYLOCK(pmap)) {
2908 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2909 mtx_lock(&pv_chunks_mutex);
2912 PG_G = pmap_global_bit(pmap);
2913 PG_A = pmap_accessed_bit(pmap);
2914 PG_M = pmap_modified_bit(pmap);
2915 PG_RW = pmap_rw_bit(pmap);
2919 * Destroy every non-wired, 4 KB page mapping in the chunk.
2922 for (field = 0; field < _NPCM; field++) {
2923 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2924 inuse != 0; inuse &= ~(1UL << bit)) {
2926 pv = &pc->pc_pventry[field * 64 + bit];
2928 pde = pmap_pde(pmap, va);
2929 if ((*pde & PG_PS) != 0)
2931 pte = pmap_pde_to_pte(pde, va);
2932 if ((*pte & PG_W) != 0)
2934 tpte = pte_load_clear(pte);
2935 if ((tpte & PG_G) != 0)
2936 pmap_invalidate_page(pmap, va);
2937 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
2938 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
2940 if ((tpte & PG_A) != 0)
2941 vm_page_aflag_set(m, PGA_REFERENCED);
2942 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
2943 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
2945 if (TAILQ_EMPTY(&m->md.pv_list) &&
2946 (m->flags & PG_FICTITIOUS) == 0) {
2947 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
2948 if (TAILQ_EMPTY(&pvh->pv_list)) {
2949 vm_page_aflag_clear(m,
2953 pmap_delayed_invl_page(m);
2954 pc->pc_map[field] |= 1UL << bit;
2955 pmap_unuse_pt(pmap, va, *pde, &free);
2960 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2961 mtx_lock(&pv_chunks_mutex);
2964 /* Every freed mapping is for a 4 KB page. */
2965 pmap_resident_count_dec(pmap, freed);
2966 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
2967 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
2968 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
2969 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2970 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
2971 pc->pc_map[2] == PC_FREE2) {
2972 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
2973 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
2974 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
2975 /* Entire chunk is free; return it. */
2976 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
2977 dump_drop_page(m_pc->phys_addr);
2978 mtx_lock(&pv_chunks_mutex);
2981 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2982 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2983 mtx_lock(&pv_chunks_mutex);
2984 /* One freed pv entry in locked_pmap is sufficient. */
2985 if (pmap == locked_pmap)
2988 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
2989 mtx_unlock(&pv_chunks_mutex);
2991 pmap_invalidate_all(pmap);
2992 if (pmap != locked_pmap)
2995 pmap_delayed_invl_finished();
2996 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
2997 m_pc = SLIST_FIRST(&free);
2998 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2999 /* Recycle a freed page table page. */
3000 m_pc->wire_count = 1;
3001 atomic_add_int(&vm_cnt.v_wire_count, 1);
3003 pmap_free_zero_pages(&free);
3008 * free the pv_entry back to the free list
3011 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3013 struct pv_chunk *pc;
3014 int idx, field, bit;
3016 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3017 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3018 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3019 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3020 pc = pv_to_chunk(pv);
3021 idx = pv - &pc->pc_pventry[0];
3024 pc->pc_map[field] |= 1ul << bit;
3025 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3026 pc->pc_map[2] != PC_FREE2) {
3027 /* 98% of the time, pc is already at the head of the list. */
3028 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3029 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3030 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3034 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3039 free_pv_chunk(struct pv_chunk *pc)
3043 mtx_lock(&pv_chunks_mutex);
3044 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3045 mtx_unlock(&pv_chunks_mutex);
3046 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3047 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3048 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3049 /* entire chunk is free, return it */
3050 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3051 dump_drop_page(m->phys_addr);
3052 vm_page_unwire(m, PQ_NONE);
3057 * Returns a new PV entry, allocating a new PV chunk from the system when
3058 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3059 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3062 * The given PV list lock may be released.
3065 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3069 struct pv_chunk *pc;
3072 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3073 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3075 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3077 for (field = 0; field < _NPCM; field++) {
3078 if (pc->pc_map[field]) {
3079 bit = bsfq(pc->pc_map[field]);
3083 if (field < _NPCM) {
3084 pv = &pc->pc_pventry[field * 64 + bit];
3085 pc->pc_map[field] &= ~(1ul << bit);
3086 /* If this was the last item, move it to tail */
3087 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3088 pc->pc_map[2] == 0) {
3089 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3090 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3093 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3094 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3098 /* No free items, allocate another chunk */
3099 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3102 if (lockp == NULL) {
3103 PV_STAT(pc_chunk_tryfail++);
3106 m = reclaim_pv_chunk(pmap, lockp);
3110 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3111 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3112 dump_add_page(m->phys_addr);
3113 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3115 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3116 pc->pc_map[1] = PC_FREE1;
3117 pc->pc_map[2] = PC_FREE2;
3118 mtx_lock(&pv_chunks_mutex);
3119 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3120 mtx_unlock(&pv_chunks_mutex);
3121 pv = &pc->pc_pventry[0];
3122 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3123 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3124 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3129 * Returns the number of one bits within the given PV chunk map element.
3131 * The erratas for Intel processors state that "POPCNT Instruction May
3132 * Take Longer to Execute Than Expected". It is believed that the
3133 * issue is the spurious dependency on the destination register.
3134 * Provide a hint to the register rename logic that the destination
3135 * value is overwritten, by clearing it, as suggested in the
3136 * optimization manual. It should be cheap for unaffected processors
3139 * Reference numbers for erratas are
3140 * 4th Gen Core: HSD146
3141 * 5th Gen Core: BDM85
3144 popcnt_pc_map_elem_pq(uint64_t elem)
3148 __asm __volatile("xorl %k0,%k0;popcntq %1,%0"
3149 : "=&r" (result) : "rm" (elem));
3154 * Ensure that the number of spare PV entries in the specified pmap meets or
3155 * exceeds the given count, "needed".
3157 * The given PV list lock may be released.
3160 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3162 struct pch new_tail;
3163 struct pv_chunk *pc;
3167 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3168 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3171 * Newly allocated PV chunks must be stored in a private list until
3172 * the required number of PV chunks have been allocated. Otherwise,
3173 * reclaim_pv_chunk() could recycle one of these chunks. In
3174 * contrast, these chunks must be added to the pmap upon allocation.
3176 TAILQ_INIT(&new_tail);
3179 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3181 if ((cpu_feature2 & CPUID2_POPCNT) == 0) {
3182 free = bitcount64(pc->pc_map[0]);
3183 free += bitcount64(pc->pc_map[1]);
3184 free += bitcount64(pc->pc_map[2]);
3188 free = popcnt_pc_map_elem_pq(pc->pc_map[0]);
3189 free += popcnt_pc_map_elem_pq(pc->pc_map[1]);
3190 free += popcnt_pc_map_elem_pq(pc->pc_map[2]);
3195 if (avail >= needed)
3198 for (; avail < needed; avail += _NPCPV) {
3199 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3202 m = reclaim_pv_chunk(pmap, lockp);
3206 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3207 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3208 dump_add_page(m->phys_addr);
3209 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3211 pc->pc_map[0] = PC_FREE0;
3212 pc->pc_map[1] = PC_FREE1;
3213 pc->pc_map[2] = PC_FREE2;
3214 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3215 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3216 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3218 if (!TAILQ_EMPTY(&new_tail)) {
3219 mtx_lock(&pv_chunks_mutex);
3220 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3221 mtx_unlock(&pv_chunks_mutex);
3226 * First find and then remove the pv entry for the specified pmap and virtual
3227 * address from the specified pv list. Returns the pv entry if found and NULL
3228 * otherwise. This operation can be performed on pv lists for either 4KB or
3229 * 2MB page mappings.
3231 static __inline pv_entry_t
3232 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3236 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3237 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3238 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3247 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3248 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3249 * entries for each of the 4KB page mappings.
3252 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3253 struct rwlock **lockp)
3255 struct md_page *pvh;
3256 struct pv_chunk *pc;
3258 vm_offset_t va_last;
3262 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3263 KASSERT((pa & PDRMASK) == 0,
3264 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3265 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3268 * Transfer the 2mpage's pv entry for this mapping to the first
3269 * page's pv list. Once this transfer begins, the pv list lock
3270 * must not be released until the last pv entry is reinstantiated.
3272 pvh = pa_to_pvh(pa);
3273 va = trunc_2mpage(va);
3274 pv = pmap_pvh_remove(pvh, pmap, va);
3275 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3276 m = PHYS_TO_VM_PAGE(pa);
3277 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3279 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3280 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3281 va_last = va + NBPDR - PAGE_SIZE;
3283 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3284 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3285 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3286 for (field = 0; field < _NPCM; field++) {
3287 while (pc->pc_map[field]) {
3288 bit = bsfq(pc->pc_map[field]);
3289 pc->pc_map[field] &= ~(1ul << bit);
3290 pv = &pc->pc_pventry[field * 64 + bit];
3294 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3295 ("pmap_pv_demote_pde: page %p is not managed", m));
3296 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3302 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3303 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3306 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3307 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3308 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3310 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3311 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3315 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3316 * replace the many pv entries for the 4KB page mappings by a single pv entry
3317 * for the 2MB page mapping.
3320 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3321 struct rwlock **lockp)
3323 struct md_page *pvh;
3325 vm_offset_t va_last;
3328 KASSERT((pa & PDRMASK) == 0,
3329 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3330 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3333 * Transfer the first page's pv entry for this mapping to the 2mpage's
3334 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3335 * a transfer avoids the possibility that get_pv_entry() calls
3336 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3337 * mappings that is being promoted.
3339 m = PHYS_TO_VM_PAGE(pa);
3340 va = trunc_2mpage(va);
3341 pv = pmap_pvh_remove(&m->md, pmap, va);
3342 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3343 pvh = pa_to_pvh(pa);
3344 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3346 /* Free the remaining NPTEPG - 1 pv entries. */
3347 va_last = va + NBPDR - PAGE_SIZE;
3351 pmap_pvh_free(&m->md, pmap, va);
3352 } while (va < va_last);
3356 * First find and then destroy the pv entry for the specified pmap and virtual
3357 * address. This operation can be performed on pv lists for either 4KB or 2MB
3361 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3365 pv = pmap_pvh_remove(pvh, pmap, va);
3366 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3367 free_pv_entry(pmap, pv);
3371 * Conditionally create the PV entry for a 4KB page mapping if the required
3372 * memory can be allocated without resorting to reclamation.
3375 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3376 struct rwlock **lockp)
3380 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3381 /* Pass NULL instead of the lock pointer to disable reclamation. */
3382 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3384 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3385 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3393 * Conditionally create the PV entry for a 2MB page mapping if the required
3394 * memory can be allocated without resorting to reclamation.
3397 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3398 struct rwlock **lockp)
3400 struct md_page *pvh;
3403 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3404 /* Pass NULL instead of the lock pointer to disable reclamation. */
3405 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3407 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3408 pvh = pa_to_pvh(pa);
3409 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3417 * Fills a page table page with mappings to consecutive physical pages.
3420 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3424 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3426 newpte += PAGE_SIZE;
3431 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3432 * mapping is invalidated.
3435 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3437 struct rwlock *lock;
3441 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3448 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3449 struct rwlock **lockp)
3451 pd_entry_t newpde, oldpde;
3452 pt_entry_t *firstpte, newpte;
3453 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3456 struct spglist free;
3459 PG_G = pmap_global_bit(pmap);
3460 PG_A = pmap_accessed_bit(pmap);
3461 PG_M = pmap_modified_bit(pmap);
3462 PG_RW = pmap_rw_bit(pmap);
3463 PG_V = pmap_valid_bit(pmap);
3464 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3466 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3468 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3469 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3470 if ((oldpde & PG_A) != 0 && (mpte = pmap_lookup_pt_page(pmap, va)) !=
3472 pmap_remove_pt_page(pmap, mpte);
3474 KASSERT((oldpde & PG_W) == 0,
3475 ("pmap_demote_pde: page table page for a wired mapping"
3479 * Invalidate the 2MB page mapping and return "failure" if the
3480 * mapping was never accessed or the allocation of the new
3481 * page table page fails. If the 2MB page mapping belongs to
3482 * the direct map region of the kernel's address space, then
3483 * the page allocation request specifies the highest possible
3484 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3485 * normal. Page table pages are preallocated for every other
3486 * part of the kernel address space, so the direct map region
3487 * is the only part of the kernel address space that must be
3490 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3491 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3492 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3493 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3495 pmap_remove_pde(pmap, pde, trunc_2mpage(va), &free,
3497 pmap_invalidate_page(pmap, trunc_2mpage(va));
3498 pmap_free_zero_pages(&free);
3499 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3500 " in pmap %p", va, pmap);
3503 if (va < VM_MAXUSER_ADDRESS)
3504 pmap_resident_count_inc(pmap, 1);
3506 mptepa = VM_PAGE_TO_PHYS(mpte);
3507 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3508 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3509 KASSERT((oldpde & PG_A) != 0,
3510 ("pmap_demote_pde: oldpde is missing PG_A"));
3511 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3512 ("pmap_demote_pde: oldpde is missing PG_M"));
3513 newpte = oldpde & ~PG_PS;
3514 newpte = pmap_swap_pat(pmap, newpte);
3517 * If the page table page is new, initialize it.
3519 if (mpte->wire_count == 1) {
3520 mpte->wire_count = NPTEPG;
3521 pmap_fill_ptp(firstpte, newpte);
3523 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3524 ("pmap_demote_pde: firstpte and newpte map different physical"
3528 * If the mapping has changed attributes, update the page table
3531 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3532 pmap_fill_ptp(firstpte, newpte);
3535 * The spare PV entries must be reserved prior to demoting the
3536 * mapping, that is, prior to changing the PDE. Otherwise, the state
3537 * of the PDE and the PV lists will be inconsistent, which can result
3538 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3539 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3540 * PV entry for the 2MB page mapping that is being demoted.
3542 if ((oldpde & PG_MANAGED) != 0)
3543 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3546 * Demote the mapping. This pmap is locked. The old PDE has
3547 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3548 * set. Thus, there is no danger of a race with another
3549 * processor changing the setting of PG_A and/or PG_M between
3550 * the read above and the store below.
3552 if (workaround_erratum383)
3553 pmap_update_pde(pmap, va, pde, newpde);
3555 pde_store(pde, newpde);
3558 * Invalidate a stale recursive mapping of the page table page.
3560 if (va >= VM_MAXUSER_ADDRESS)
3561 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3564 * Demote the PV entry.
3566 if ((oldpde & PG_MANAGED) != 0)
3567 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3569 atomic_add_long(&pmap_pde_demotions, 1);
3570 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3571 " in pmap %p", va, pmap);
3576 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3579 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3585 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3586 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3587 mpte = pmap_lookup_pt_page(pmap, va);
3589 panic("pmap_remove_kernel_pde: Missing pt page.");
3591 pmap_remove_pt_page(pmap, mpte);
3592 mptepa = VM_PAGE_TO_PHYS(mpte);
3593 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3596 * Initialize the page table page.
3598 pagezero((void *)PHYS_TO_DMAP(mptepa));
3601 * Demote the mapping.
3603 if (workaround_erratum383)
3604 pmap_update_pde(pmap, va, pde, newpde);
3606 pde_store(pde, newpde);
3609 * Invalidate a stale recursive mapping of the page table page.
3611 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3615 * pmap_remove_pde: do the things to unmap a superpage in a process
3618 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
3619 struct spglist *free, struct rwlock **lockp)
3621 struct md_page *pvh;
3623 vm_offset_t eva, va;
3625 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3627 PG_G = pmap_global_bit(pmap);
3628 PG_A = pmap_accessed_bit(pmap);
3629 PG_M = pmap_modified_bit(pmap);
3630 PG_RW = pmap_rw_bit(pmap);
3632 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3633 KASSERT((sva & PDRMASK) == 0,
3634 ("pmap_remove_pde: sva is not 2mpage aligned"));
3635 oldpde = pte_load_clear(pdq);
3637 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
3640 * Machines that don't support invlpg, also don't support
3644 pmap_invalidate_page(kernel_pmap, sva);
3645 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
3646 if (oldpde & PG_MANAGED) {
3647 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
3648 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
3649 pmap_pvh_free(pvh, pmap, sva);
3651 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3652 va < eva; va += PAGE_SIZE, m++) {
3653 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3656 vm_page_aflag_set(m, PGA_REFERENCED);
3657 if (TAILQ_EMPTY(&m->md.pv_list) &&
3658 TAILQ_EMPTY(&pvh->pv_list))
3659 vm_page_aflag_clear(m, PGA_WRITEABLE);
3660 pmap_delayed_invl_page(m);
3663 if (pmap == kernel_pmap) {
3664 pmap_remove_kernel_pde(pmap, pdq, sva);
3666 mpte = pmap_lookup_pt_page(pmap, sva);
3668 pmap_remove_pt_page(pmap, mpte);
3669 pmap_resident_count_dec(pmap, 1);
3670 KASSERT(mpte->wire_count == NPTEPG,
3671 ("pmap_remove_pde: pte page wire count error"));
3672 mpte->wire_count = 0;
3673 pmap_add_delayed_free_list(mpte, free, FALSE);
3674 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3677 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
3681 * pmap_remove_pte: do the things to unmap a page in a process
3684 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
3685 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
3687 struct md_page *pvh;
3688 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
3691 PG_A = pmap_accessed_bit(pmap);
3692 PG_M = pmap_modified_bit(pmap);
3693 PG_RW = pmap_rw_bit(pmap);
3695 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3696 oldpte = pte_load_clear(ptq);
3698 pmap->pm_stats.wired_count -= 1;
3699 pmap_resident_count_dec(pmap, 1);
3700 if (oldpte & PG_MANAGED) {
3701 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
3702 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3705 vm_page_aflag_set(m, PGA_REFERENCED);
3706 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3707 pmap_pvh_free(&m->md, pmap, va);
3708 if (TAILQ_EMPTY(&m->md.pv_list) &&
3709 (m->flags & PG_FICTITIOUS) == 0) {
3710 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3711 if (TAILQ_EMPTY(&pvh->pv_list))
3712 vm_page_aflag_clear(m, PGA_WRITEABLE);
3714 pmap_delayed_invl_page(m);
3716 return (pmap_unuse_pt(pmap, va, ptepde, free));
3720 * Remove a single page from a process address space
3723 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
3724 struct spglist *free)
3726 struct rwlock *lock;
3727 pt_entry_t *pte, PG_V;
3729 PG_V = pmap_valid_bit(pmap);
3730 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3731 if ((*pde & PG_V) == 0)
3733 pte = pmap_pde_to_pte(pde, va);
3734 if ((*pte & PG_V) == 0)
3737 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
3740 pmap_invalidate_page(pmap, va);
3744 * Remove the given range of addresses from the specified map.
3746 * It is assumed that the start and end are properly
3747 * rounded to the page size.
3750 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3752 struct rwlock *lock;
3753 vm_offset_t va, va_next;
3754 pml4_entry_t *pml4e;
3756 pd_entry_t ptpaddr, *pde;
3757 pt_entry_t *pte, PG_G, PG_V;
3758 struct spglist free;
3761 PG_G = pmap_global_bit(pmap);
3762 PG_V = pmap_valid_bit(pmap);
3765 * Perform an unsynchronized read. This is, however, safe.
3767 if (pmap->pm_stats.resident_count == 0)
3773 pmap_delayed_invl_started();
3777 * special handling of removing one page. a very
3778 * common operation and easy to short circuit some
3781 if (sva + PAGE_SIZE == eva) {
3782 pde = pmap_pde(pmap, sva);
3783 if (pde && (*pde & PG_PS) == 0) {
3784 pmap_remove_page(pmap, sva, pde, &free);
3790 for (; sva < eva; sva = va_next) {
3792 if (pmap->pm_stats.resident_count == 0)
3795 pml4e = pmap_pml4e(pmap, sva);
3796 if ((*pml4e & PG_V) == 0) {
3797 va_next = (sva + NBPML4) & ~PML4MASK;
3803 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
3804 if ((*pdpe & PG_V) == 0) {
3805 va_next = (sva + NBPDP) & ~PDPMASK;
3812 * Calculate index for next page table.
3814 va_next = (sva + NBPDR) & ~PDRMASK;
3818 pde = pmap_pdpe_to_pde(pdpe, sva);
3822 * Weed out invalid mappings.
3828 * Check for large page.
3830 if ((ptpaddr & PG_PS) != 0) {
3832 * Are we removing the entire large page? If not,
3833 * demote the mapping and fall through.
3835 if (sva + NBPDR == va_next && eva >= va_next) {
3837 * The TLB entry for a PG_G mapping is
3838 * invalidated by pmap_remove_pde().
3840 if ((ptpaddr & PG_G) == 0)
3842 pmap_remove_pde(pmap, pde, sva, &free, &lock);
3844 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
3846 /* The large page mapping was destroyed. */
3853 * Limit our scan to either the end of the va represented
3854 * by the current page table page, or to the end of the
3855 * range being removed.
3861 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
3864 if (va != va_next) {
3865 pmap_invalidate_range(pmap, va, sva);
3870 if ((*pte & PG_G) == 0)
3872 else if (va == va_next)
3874 if (pmap_remove_pte(pmap, pte, sva, ptpaddr, &free,
3881 pmap_invalidate_range(pmap, va, sva);
3887 pmap_invalidate_all(pmap);
3889 pmap_delayed_invl_finished();
3890 pmap_free_zero_pages(&free);
3894 * Routine: pmap_remove_all
3896 * Removes this physical page from
3897 * all physical maps in which it resides.
3898 * Reflects back modify bits to the pager.
3901 * Original versions of this routine were very
3902 * inefficient because they iteratively called
3903 * pmap_remove (slow...)
3907 pmap_remove_all(vm_page_t m)
3909 struct md_page *pvh;
3912 struct rwlock *lock;
3913 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
3916 struct spglist free;
3917 int pvh_gen, md_gen;
3919 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3920 ("pmap_remove_all: page %p is not managed", m));
3922 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3923 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3926 if ((m->flags & PG_FICTITIOUS) != 0)
3927 goto small_mappings;
3928 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
3930 if (!PMAP_TRYLOCK(pmap)) {
3931 pvh_gen = pvh->pv_gen;
3935 if (pvh_gen != pvh->pv_gen) {
3942 pde = pmap_pde(pmap, va);
3943 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
3947 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3949 if (!PMAP_TRYLOCK(pmap)) {
3950 pvh_gen = pvh->pv_gen;
3951 md_gen = m->md.pv_gen;
3955 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
3961 PG_A = pmap_accessed_bit(pmap);
3962 PG_M = pmap_modified_bit(pmap);
3963 PG_RW = pmap_rw_bit(pmap);
3964 pmap_resident_count_dec(pmap, 1);
3965 pde = pmap_pde(pmap, pv->pv_va);
3966 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
3967 " a 2mpage in page %p's pv list", m));
3968 pte = pmap_pde_to_pte(pde, pv->pv_va);
3969 tpte = pte_load_clear(pte);
3971 pmap->pm_stats.wired_count--;
3973 vm_page_aflag_set(m, PGA_REFERENCED);
3976 * Update the vm_page_t clean and reference bits.
3978 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3980 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
3981 pmap_invalidate_page(pmap, pv->pv_va);
3982 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3984 free_pv_entry(pmap, pv);
3987 vm_page_aflag_clear(m, PGA_WRITEABLE);
3989 pmap_delayed_invl_wait(m);
3990 pmap_free_zero_pages(&free);
3994 * pmap_protect_pde: do the things to protect a 2mpage in a process
3997 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
3999 pd_entry_t newpde, oldpde;
4000 vm_offset_t eva, va;
4002 boolean_t anychanged;
4003 pt_entry_t PG_G, PG_M, PG_RW;
4005 PG_G = pmap_global_bit(pmap);
4006 PG_M = pmap_modified_bit(pmap);
4007 PG_RW = pmap_rw_bit(pmap);
4009 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4010 KASSERT((sva & PDRMASK) == 0,
4011 ("pmap_protect_pde: sva is not 2mpage aligned"));
4014 oldpde = newpde = *pde;
4015 if (oldpde & PG_MANAGED) {
4017 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4018 va < eva; va += PAGE_SIZE, m++)
4019 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
4022 if ((prot & VM_PROT_WRITE) == 0)
4023 newpde &= ~(PG_RW | PG_M);
4024 if ((prot & VM_PROT_EXECUTE) == 0)
4026 if (newpde != oldpde) {
4027 if (!atomic_cmpset_long(pde, oldpde, newpde))
4030 pmap_invalidate_page(pmap, sva);
4034 return (anychanged);
4038 * Set the physical protection on the
4039 * specified range of this map as requested.
4042 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4044 vm_offset_t va_next;
4045 pml4_entry_t *pml4e;
4047 pd_entry_t ptpaddr, *pde;
4048 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4049 boolean_t anychanged;
4051 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4052 if (prot == VM_PROT_NONE) {
4053 pmap_remove(pmap, sva, eva);
4057 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4058 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4061 PG_G = pmap_global_bit(pmap);
4062 PG_M = pmap_modified_bit(pmap);
4063 PG_V = pmap_valid_bit(pmap);
4064 PG_RW = pmap_rw_bit(pmap);
4068 for (; sva < eva; sva = va_next) {
4070 pml4e = pmap_pml4e(pmap, sva);
4071 if ((*pml4e & PG_V) == 0) {
4072 va_next = (sva + NBPML4) & ~PML4MASK;
4078 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4079 if ((*pdpe & PG_V) == 0) {
4080 va_next = (sva + NBPDP) & ~PDPMASK;
4086 va_next = (sva + NBPDR) & ~PDRMASK;
4090 pde = pmap_pdpe_to_pde(pdpe, sva);
4094 * Weed out invalid mappings.
4100 * Check for large page.
4102 if ((ptpaddr & PG_PS) != 0) {
4104 * Are we protecting the entire large page? If not,
4105 * demote the mapping and fall through.
4107 if (sva + NBPDR == va_next && eva >= va_next) {
4109 * The TLB entry for a PG_G mapping is
4110 * invalidated by pmap_protect_pde().
4112 if (pmap_protect_pde(pmap, pde, sva, prot))
4115 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4117 * The large page mapping was destroyed.
4126 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4128 pt_entry_t obits, pbits;
4132 obits = pbits = *pte;
4133 if ((pbits & PG_V) == 0)
4136 if ((prot & VM_PROT_WRITE) == 0) {
4137 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4138 (PG_MANAGED | PG_M | PG_RW)) {
4139 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4142 pbits &= ~(PG_RW | PG_M);
4144 if ((prot & VM_PROT_EXECUTE) == 0)
4147 if (pbits != obits) {
4148 if (!atomic_cmpset_long(pte, obits, pbits))
4151 pmap_invalidate_page(pmap, sva);
4158 pmap_invalidate_all(pmap);
4163 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4164 * single page table page (PTP) to a single 2MB page mapping. For promotion
4165 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4166 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4167 * identical characteristics.
4170 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4171 struct rwlock **lockp)
4174 pt_entry_t *firstpte, oldpte, pa, *pte;
4175 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4179 PG_A = pmap_accessed_bit(pmap);
4180 PG_G = pmap_global_bit(pmap);
4181 PG_M = pmap_modified_bit(pmap);
4182 PG_V = pmap_valid_bit(pmap);
4183 PG_RW = pmap_rw_bit(pmap);
4184 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4186 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4189 * Examine the first PTE in the specified PTP. Abort if this PTE is
4190 * either invalid, unused, or does not map the first 4KB physical page
4191 * within a 2MB page.
4193 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4196 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4197 atomic_add_long(&pmap_pde_p_failures, 1);
4198 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4199 " in pmap %p", va, pmap);
4202 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4204 * When PG_M is already clear, PG_RW can be cleared without
4205 * a TLB invalidation.
4207 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4213 * Examine each of the other PTEs in the specified PTP. Abort if this
4214 * PTE maps an unexpected 4KB physical page or does not have identical
4215 * characteristics to the first PTE.
4217 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4218 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4221 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4222 atomic_add_long(&pmap_pde_p_failures, 1);
4223 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4224 " in pmap %p", va, pmap);
4227 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4229 * When PG_M is already clear, PG_RW can be cleared
4230 * without a TLB invalidation.
4232 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4235 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4236 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4237 (va & ~PDRMASK), pmap);
4239 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4240 atomic_add_long(&pmap_pde_p_failures, 1);
4241 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4242 " in pmap %p", va, pmap);
4249 * Save the page table page in its current state until the PDE
4250 * mapping the superpage is demoted by pmap_demote_pde() or
4251 * destroyed by pmap_remove_pde().
4253 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4254 KASSERT(mpte >= vm_page_array &&
4255 mpte < &vm_page_array[vm_page_array_size],
4256 ("pmap_promote_pde: page table page is out of range"));
4257 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4258 ("pmap_promote_pde: page table page's pindex is wrong"));
4259 if (pmap_insert_pt_page(pmap, mpte)) {
4260 atomic_add_long(&pmap_pde_p_failures, 1);
4262 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4268 * Promote the pv entries.
4270 if ((newpde & PG_MANAGED) != 0)
4271 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4274 * Propagate the PAT index to its proper position.
4276 newpde = pmap_swap_pat(pmap, newpde);
4279 * Map the superpage.
4281 if (workaround_erratum383)
4282 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4284 pde_store(pde, PG_PS | newpde);
4286 atomic_add_long(&pmap_pde_promotions, 1);
4287 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4288 " in pmap %p", va, pmap);
4292 * Insert the given physical page (p) at
4293 * the specified virtual address (v) in the
4294 * target physical map with the protection requested.
4296 * If specified, the page will be wired down, meaning
4297 * that the related pte can not be reclaimed.
4299 * NB: This is the only routine which MAY NOT lazy-evaluate
4300 * or lose information. That is, this routine must actually
4301 * insert this page into the given map NOW.
4303 * When destroying both a page table and PV entry, this function
4304 * performs the TLB invalidation before releasing the PV list
4305 * lock, so we do not need pmap_delayed_invl_page() calls here.
4308 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4309 u_int flags, int8_t psind __unused)
4311 struct rwlock *lock;
4313 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4314 pt_entry_t newpte, origpte;
4320 PG_A = pmap_accessed_bit(pmap);
4321 PG_G = pmap_global_bit(pmap);
4322 PG_M = pmap_modified_bit(pmap);
4323 PG_V = pmap_valid_bit(pmap);
4324 PG_RW = pmap_rw_bit(pmap);
4326 va = trunc_page(va);
4327 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4328 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4329 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4331 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4332 va >= kmi.clean_eva,
4333 ("pmap_enter: managed mapping within the clean submap"));
4334 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4335 VM_OBJECT_ASSERT_LOCKED(m->object);
4336 pa = VM_PAGE_TO_PHYS(m);
4337 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4338 if ((flags & VM_PROT_WRITE) != 0)
4340 if ((prot & VM_PROT_WRITE) != 0)
4342 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4343 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4344 if ((prot & VM_PROT_EXECUTE) == 0)
4346 if ((flags & PMAP_ENTER_WIRED) != 0)
4348 if (va < VM_MAXUSER_ADDRESS)
4350 if (pmap == kernel_pmap)
4352 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, 0);
4355 * Set modified bit gratuitously for writeable mappings if
4356 * the page is unmanaged. We do not want to take a fault
4357 * to do the dirty bit accounting for these mappings.
4359 if ((m->oflags & VPO_UNMANAGED) != 0) {
4360 if ((newpte & PG_RW) != 0)
4370 * In the case that a page table page is not
4371 * resident, we are creating it here.
4374 pde = pmap_pde(pmap, va);
4375 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4376 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4377 pte = pmap_pde_to_pte(pde, va);
4378 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4379 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4382 } else if (va < VM_MAXUSER_ADDRESS) {
4384 * Here if the pte page isn't mapped, or if it has been
4387 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4388 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4389 nosleep ? NULL : &lock);
4390 if (mpte == NULL && nosleep) {
4394 return (KERN_RESOURCE_SHORTAGE);
4398 panic("pmap_enter: invalid page directory va=%#lx", va);
4403 * Is the specified virtual address already mapped?
4405 if ((origpte & PG_V) != 0) {
4407 * Wiring change, just update stats. We don't worry about
4408 * wiring PT pages as they remain resident as long as there
4409 * are valid mappings in them. Hence, if a user page is wired,
4410 * the PT page will be also.
4412 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4413 pmap->pm_stats.wired_count++;
4414 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4415 pmap->pm_stats.wired_count--;
4418 * Remove the extra PT page reference.
4422 KASSERT(mpte->wire_count > 0,
4423 ("pmap_enter: missing reference to page table page,"
4428 * Has the physical page changed?
4430 opa = origpte & PG_FRAME;
4433 * No, might be a protection or wiring change.
4435 if ((origpte & PG_MANAGED) != 0) {
4436 newpte |= PG_MANAGED;
4437 if ((newpte & PG_RW) != 0)
4438 vm_page_aflag_set(m, PGA_WRITEABLE);
4440 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4446 * Increment the counters.
4448 if ((newpte & PG_W) != 0)
4449 pmap->pm_stats.wired_count++;
4450 pmap_resident_count_inc(pmap, 1);
4454 * Enter on the PV list if part of our managed memory.
4456 if ((m->oflags & VPO_UNMANAGED) == 0) {
4457 newpte |= PG_MANAGED;
4458 pv = get_pv_entry(pmap, &lock);
4460 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4461 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4463 if ((newpte & PG_RW) != 0)
4464 vm_page_aflag_set(m, PGA_WRITEABLE);
4470 if ((origpte & PG_V) != 0) {
4472 origpte = pte_load_store(pte, newpte);
4473 opa = origpte & PG_FRAME;
4475 if ((origpte & PG_MANAGED) != 0) {
4476 om = PHYS_TO_VM_PAGE(opa);
4477 if ((origpte & (PG_M | PG_RW)) == (PG_M |
4480 if ((origpte & PG_A) != 0)
4481 vm_page_aflag_set(om, PGA_REFERENCED);
4482 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4483 pmap_pvh_free(&om->md, pmap, va);
4484 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4485 TAILQ_EMPTY(&om->md.pv_list) &&
4486 ((om->flags & PG_FICTITIOUS) != 0 ||
4487 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4488 vm_page_aflag_clear(om, PGA_WRITEABLE);
4490 } else if ((newpte & PG_M) == 0 && (origpte & (PG_M |
4491 PG_RW)) == (PG_M | PG_RW)) {
4492 if ((origpte & PG_MANAGED) != 0)
4496 * Although the PTE may still have PG_RW set, TLB
4497 * invalidation may nonetheless be required because
4498 * the PTE no longer has PG_M set.
4500 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4502 * This PTE change does not require TLB invalidation.
4506 if ((origpte & PG_A) != 0)
4507 pmap_invalidate_page(pmap, va);
4509 pte_store(pte, newpte);
4514 * If both the page table page and the reservation are fully
4515 * populated, then attempt promotion.
4517 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4518 pmap_ps_enabled(pmap) &&
4519 (m->flags & PG_FICTITIOUS) == 0 &&
4520 vm_reserv_level_iffullpop(m) == 0)
4521 pmap_promote_pde(pmap, pde, va, &lock);
4526 return (KERN_SUCCESS);
4530 * Tries to create a 2MB page mapping. Returns TRUE if successful and FALSE
4531 * otherwise. Fails if (1) a page table page cannot be allocated without
4532 * blocking, (2) a mapping already exists at the specified virtual address, or
4533 * (3) a pv entry cannot be allocated without reclaiming another pv entry.
4536 pmap_enter_pde(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4537 struct rwlock **lockp)
4539 pd_entry_t *pde, newpde;
4542 struct spglist free;
4544 PG_V = pmap_valid_bit(pmap);
4545 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4547 if ((mpde = pmap_allocpde(pmap, va, NULL)) == NULL) {
4548 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4549 " in pmap %p", va, pmap);
4552 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpde));
4553 pde = &pde[pmap_pde_index(va)];
4554 if ((*pde & PG_V) != 0) {
4555 KASSERT(mpde->wire_count > 1,
4556 ("pmap_enter_pde: mpde's wire count is too low"));
4558 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4559 " in pmap %p", va, pmap);
4562 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
4564 if ((m->oflags & VPO_UNMANAGED) == 0) {
4565 newpde |= PG_MANAGED;
4568 * Abort this mapping if its PV entry could not be created.
4570 if (!pmap_pv_insert_pde(pmap, va, VM_PAGE_TO_PHYS(m),
4573 if (pmap_unwire_ptp(pmap, va, mpde, &free)) {
4575 * Although "va" is not mapped, paging-
4576 * structure caches could nonetheless have
4577 * entries that refer to the freed page table
4578 * pages. Invalidate those entries.
4580 pmap_invalidate_page(pmap, va);
4581 pmap_free_zero_pages(&free);
4583 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4584 " in pmap %p", va, pmap);
4588 if ((prot & VM_PROT_EXECUTE) == 0)
4590 if (va < VM_MAXUSER_ADDRESS)
4594 * Increment counters.
4596 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
4599 * Map the superpage.
4601 pde_store(pde, newpde);
4603 atomic_add_long(&pmap_pde_mappings, 1);
4604 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
4605 " in pmap %p", va, pmap);
4610 * Maps a sequence of resident pages belonging to the same object.
4611 * The sequence begins with the given page m_start. This page is
4612 * mapped at the given virtual address start. Each subsequent page is
4613 * mapped at a virtual address that is offset from start by the same
4614 * amount as the page is offset from m_start within the object. The
4615 * last page in the sequence is the page with the largest offset from
4616 * m_start that can be mapped at a virtual address less than the given
4617 * virtual address end. Not every virtual page between start and end
4618 * is mapped; only those for which a resident page exists with the
4619 * corresponding offset from m_start are mapped.
4622 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
4623 vm_page_t m_start, vm_prot_t prot)
4625 struct rwlock *lock;
4628 vm_pindex_t diff, psize;
4630 VM_OBJECT_ASSERT_LOCKED(m_start->object);
4632 psize = atop(end - start);
4637 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
4638 va = start + ptoa(diff);
4639 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
4640 m->psind == 1 && pmap_ps_enabled(pmap) &&
4641 pmap_enter_pde(pmap, va, m, prot, &lock))
4642 m = &m[NBPDR / PAGE_SIZE - 1];
4644 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
4646 m = TAILQ_NEXT(m, listq);
4654 * this code makes some *MAJOR* assumptions:
4655 * 1. Current pmap & pmap exists.
4658 * 4. No page table pages.
4659 * but is *MUCH* faster than pmap_enter...
4663 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
4665 struct rwlock *lock;
4669 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
4676 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
4677 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
4679 struct spglist free;
4680 pt_entry_t *pte, PG_V;
4683 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
4684 (m->oflags & VPO_UNMANAGED) != 0,
4685 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
4686 PG_V = pmap_valid_bit(pmap);
4687 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4690 * In the case that a page table page is not
4691 * resident, we are creating it here.
4693 if (va < VM_MAXUSER_ADDRESS) {
4694 vm_pindex_t ptepindex;
4698 * Calculate pagetable page index
4700 ptepindex = pmap_pde_pindex(va);
4701 if (mpte && (mpte->pindex == ptepindex)) {
4705 * Get the page directory entry
4707 ptepa = pmap_pde(pmap, va);
4710 * If the page table page is mapped, we just increment
4711 * the hold count, and activate it. Otherwise, we
4712 * attempt to allocate a page table page. If this
4713 * attempt fails, we don't retry. Instead, we give up.
4715 if (ptepa && (*ptepa & PG_V) != 0) {
4718 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
4722 * Pass NULL instead of the PV list lock
4723 * pointer, because we don't intend to sleep.
4725 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
4730 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
4731 pte = &pte[pmap_pte_index(va)];
4745 * Enter on the PV list if part of our managed memory.
4747 if ((m->oflags & VPO_UNMANAGED) == 0 &&
4748 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
4751 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
4753 * Although "va" is not mapped, paging-
4754 * structure caches could nonetheless have
4755 * entries that refer to the freed page table
4756 * pages. Invalidate those entries.
4758 pmap_invalidate_page(pmap, va);
4759 pmap_free_zero_pages(&free);
4767 * Increment counters
4769 pmap_resident_count_inc(pmap, 1);
4771 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
4772 if ((prot & VM_PROT_EXECUTE) == 0)
4776 * Now validate mapping with RO protection
4778 if ((m->oflags & VPO_UNMANAGED) != 0)
4779 pte_store(pte, pa | PG_V | PG_U);
4781 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
4786 * Make a temporary mapping for a physical address. This is only intended
4787 * to be used for panic dumps.
4790 pmap_kenter_temporary(vm_paddr_t pa, int i)
4794 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
4795 pmap_kenter(va, pa);
4797 return ((void *)crashdumpmap);
4801 * This code maps large physical mmap regions into the
4802 * processor address space. Note that some shortcuts
4803 * are taken, but the code works.
4806 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
4807 vm_pindex_t pindex, vm_size_t size)
4810 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
4811 vm_paddr_t pa, ptepa;
4815 PG_A = pmap_accessed_bit(pmap);
4816 PG_M = pmap_modified_bit(pmap);
4817 PG_V = pmap_valid_bit(pmap);
4818 PG_RW = pmap_rw_bit(pmap);
4820 VM_OBJECT_ASSERT_WLOCKED(object);
4821 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
4822 ("pmap_object_init_pt: non-device object"));
4823 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
4824 if (!pmap_ps_enabled(pmap))
4826 if (!vm_object_populate(object, pindex, pindex + atop(size)))
4828 p = vm_page_lookup(object, pindex);
4829 KASSERT(p->valid == VM_PAGE_BITS_ALL,
4830 ("pmap_object_init_pt: invalid page %p", p));
4831 pat_mode = p->md.pat_mode;
4834 * Abort the mapping if the first page is not physically
4835 * aligned to a 2MB page boundary.
4837 ptepa = VM_PAGE_TO_PHYS(p);
4838 if (ptepa & (NBPDR - 1))
4842 * Skip the first page. Abort the mapping if the rest of
4843 * the pages are not physically contiguous or have differing
4844 * memory attributes.
4846 p = TAILQ_NEXT(p, listq);
4847 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
4849 KASSERT(p->valid == VM_PAGE_BITS_ALL,
4850 ("pmap_object_init_pt: invalid page %p", p));
4851 if (pa != VM_PAGE_TO_PHYS(p) ||
4852 pat_mode != p->md.pat_mode)
4854 p = TAILQ_NEXT(p, listq);
4858 * Map using 2MB pages. Since "ptepa" is 2M aligned and
4859 * "size" is a multiple of 2M, adding the PAT setting to "pa"
4860 * will not affect the termination of this loop.
4863 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
4864 pa < ptepa + size; pa += NBPDR) {
4865 pdpg = pmap_allocpde(pmap, addr, NULL);
4868 * The creation of mappings below is only an
4869 * optimization. If a page directory page
4870 * cannot be allocated without blocking,
4871 * continue on to the next mapping rather than
4877 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4878 pde = &pde[pmap_pde_index(addr)];
4879 if ((*pde & PG_V) == 0) {
4880 pde_store(pde, pa | PG_PS | PG_M | PG_A |
4881 PG_U | PG_RW | PG_V);
4882 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
4883 atomic_add_long(&pmap_pde_mappings, 1);
4885 /* Continue on if the PDE is already valid. */
4887 KASSERT(pdpg->wire_count > 0,
4888 ("pmap_object_init_pt: missing reference "
4889 "to page directory page, va: 0x%lx", addr));
4898 * Clear the wired attribute from the mappings for the specified range of
4899 * addresses in the given pmap. Every valid mapping within that range
4900 * must have the wired attribute set. In contrast, invalid mappings
4901 * cannot have the wired attribute set, so they are ignored.
4903 * The wired attribute of the page table entry is not a hardware
4904 * feature, so there is no need to invalidate any TLB entries.
4905 * Since pmap_demote_pde() for the wired entry must never fail,
4906 * pmap_delayed_invl_started()/finished() calls around the
4907 * function are not needed.
4910 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4912 vm_offset_t va_next;
4913 pml4_entry_t *pml4e;
4916 pt_entry_t *pte, PG_V;
4918 PG_V = pmap_valid_bit(pmap);
4920 for (; sva < eva; sva = va_next) {
4921 pml4e = pmap_pml4e(pmap, sva);
4922 if ((*pml4e & PG_V) == 0) {
4923 va_next = (sva + NBPML4) & ~PML4MASK;
4928 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4929 if ((*pdpe & PG_V) == 0) {
4930 va_next = (sva + NBPDP) & ~PDPMASK;
4935 va_next = (sva + NBPDR) & ~PDRMASK;
4938 pde = pmap_pdpe_to_pde(pdpe, sva);
4939 if ((*pde & PG_V) == 0)
4941 if ((*pde & PG_PS) != 0) {
4942 if ((*pde & PG_W) == 0)
4943 panic("pmap_unwire: pde %#jx is missing PG_W",
4947 * Are we unwiring the entire large page? If not,
4948 * demote the mapping and fall through.
4950 if (sva + NBPDR == va_next && eva >= va_next) {
4951 atomic_clear_long(pde, PG_W);
4952 pmap->pm_stats.wired_count -= NBPDR /
4955 } else if (!pmap_demote_pde(pmap, pde, sva))
4956 panic("pmap_unwire: demotion failed");
4960 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4962 if ((*pte & PG_V) == 0)
4964 if ((*pte & PG_W) == 0)
4965 panic("pmap_unwire: pte %#jx is missing PG_W",
4969 * PG_W must be cleared atomically. Although the pmap
4970 * lock synchronizes access to PG_W, another processor
4971 * could be setting PG_M and/or PG_A concurrently.
4973 atomic_clear_long(pte, PG_W);
4974 pmap->pm_stats.wired_count--;
4981 * Copy the range specified by src_addr/len
4982 * from the source map to the range dst_addr/len
4983 * in the destination map.
4985 * This routine is only advisory and need not do anything.
4989 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
4990 vm_offset_t src_addr)
4992 struct rwlock *lock;
4993 struct spglist free;
4995 vm_offset_t end_addr = src_addr + len;
4996 vm_offset_t va_next;
4997 pt_entry_t PG_A, PG_M, PG_V;
4999 if (dst_addr != src_addr)
5002 if (dst_pmap->pm_type != src_pmap->pm_type)
5006 * EPT page table entries that require emulation of A/D bits are
5007 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5008 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5009 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5010 * implementations flag an EPT misconfiguration for exec-only
5011 * mappings we skip this function entirely for emulated pmaps.
5013 if (pmap_emulate_ad_bits(dst_pmap))
5017 if (dst_pmap < src_pmap) {
5018 PMAP_LOCK(dst_pmap);
5019 PMAP_LOCK(src_pmap);
5021 PMAP_LOCK(src_pmap);
5022 PMAP_LOCK(dst_pmap);
5025 PG_A = pmap_accessed_bit(dst_pmap);
5026 PG_M = pmap_modified_bit(dst_pmap);
5027 PG_V = pmap_valid_bit(dst_pmap);
5029 for (addr = src_addr; addr < end_addr; addr = va_next) {
5030 pt_entry_t *src_pte, *dst_pte;
5031 vm_page_t dstmpde, dstmpte, srcmpte;
5032 pml4_entry_t *pml4e;
5034 pd_entry_t srcptepaddr, *pde;
5036 KASSERT(addr < UPT_MIN_ADDRESS,
5037 ("pmap_copy: invalid to pmap_copy page tables"));
5039 pml4e = pmap_pml4e(src_pmap, addr);
5040 if ((*pml4e & PG_V) == 0) {
5041 va_next = (addr + NBPML4) & ~PML4MASK;
5047 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5048 if ((*pdpe & PG_V) == 0) {
5049 va_next = (addr + NBPDP) & ~PDPMASK;
5055 va_next = (addr + NBPDR) & ~PDRMASK;
5059 pde = pmap_pdpe_to_pde(pdpe, addr);
5061 if (srcptepaddr == 0)
5064 if (srcptepaddr & PG_PS) {
5065 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5067 dstmpde = pmap_allocpde(dst_pmap, addr, NULL);
5068 if (dstmpde == NULL)
5070 pde = (pd_entry_t *)
5071 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpde));
5072 pde = &pde[pmap_pde_index(addr)];
5073 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5074 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr &
5075 PG_PS_FRAME, &lock))) {
5076 *pde = srcptepaddr & ~PG_W;
5077 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5078 atomic_add_long(&pmap_pde_mappings, 1);
5080 dstmpde->wire_count--;
5084 srcptepaddr &= PG_FRAME;
5085 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5086 KASSERT(srcmpte->wire_count > 0,
5087 ("pmap_copy: source page table page is unused"));
5089 if (va_next > end_addr)
5092 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5093 src_pte = &src_pte[pmap_pte_index(addr)];
5095 while (addr < va_next) {
5099 * we only virtual copy managed pages
5101 if ((ptetemp & PG_MANAGED) != 0) {
5102 if (dstmpte != NULL &&
5103 dstmpte->pindex == pmap_pde_pindex(addr))
5104 dstmpte->wire_count++;
5105 else if ((dstmpte = pmap_allocpte(dst_pmap,
5106 addr, NULL)) == NULL)
5108 dst_pte = (pt_entry_t *)
5109 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5110 dst_pte = &dst_pte[pmap_pte_index(addr)];
5111 if (*dst_pte == 0 &&
5112 pmap_try_insert_pv_entry(dst_pmap, addr,
5113 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5116 * Clear the wired, modified, and
5117 * accessed (referenced) bits
5120 *dst_pte = ptetemp & ~(PG_W | PG_M |
5122 pmap_resident_count_inc(dst_pmap, 1);
5125 if (pmap_unwire_ptp(dst_pmap, addr,
5128 * Although "addr" is not
5129 * mapped, paging-structure
5130 * caches could nonetheless
5131 * have entries that refer to
5132 * the freed page table pages.
5133 * Invalidate those entries.
5135 pmap_invalidate_page(dst_pmap,
5137 pmap_free_zero_pages(&free);
5141 if (dstmpte->wire_count >= srcmpte->wire_count)
5151 PMAP_UNLOCK(src_pmap);
5152 PMAP_UNLOCK(dst_pmap);
5156 * pmap_zero_page zeros the specified hardware page by mapping
5157 * the page into KVM and using bzero to clear its contents.
5160 pmap_zero_page(vm_page_t m)
5162 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5164 pagezero((void *)va);
5168 * pmap_zero_page_area zeros the specified hardware page by mapping
5169 * the page into KVM and using bzero to clear its contents.
5171 * off and size may not cover an area beyond a single hardware page.
5174 pmap_zero_page_area(vm_page_t m, int off, int size)
5176 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5178 if (off == 0 && size == PAGE_SIZE)
5179 pagezero((void *)va);
5181 bzero((char *)va + off, size);
5185 * pmap_zero_page_idle zeros the specified hardware page by mapping
5186 * the page into KVM and using bzero to clear its contents. This
5187 * is intended to be called from the vm_pagezero process only and
5191 pmap_zero_page_idle(vm_page_t m)
5193 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5195 pagezero((void *)va);
5199 * pmap_copy_page copies the specified (machine independent)
5200 * page by mapping the page into virtual memory and using
5201 * bcopy to copy the page, one machine dependent page at a
5205 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5207 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5208 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5210 pagecopy((void *)src, (void *)dst);
5213 int unmapped_buf_allowed = 1;
5216 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5217 vm_offset_t b_offset, int xfersize)
5221 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5225 while (xfersize > 0) {
5226 a_pg_offset = a_offset & PAGE_MASK;
5227 pages[0] = ma[a_offset >> PAGE_SHIFT];
5228 b_pg_offset = b_offset & PAGE_MASK;
5229 pages[1] = mb[b_offset >> PAGE_SHIFT];
5230 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5231 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5232 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5233 a_cp = (char *)vaddr[0] + a_pg_offset;
5234 b_cp = (char *)vaddr[1] + b_pg_offset;
5235 bcopy(a_cp, b_cp, cnt);
5236 if (__predict_false(mapped))
5237 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5245 * Returns true if the pmap's pv is one of the first
5246 * 16 pvs linked to from this page. This count may
5247 * be changed upwards or downwards in the future; it
5248 * is only necessary that true be returned for a small
5249 * subset of pmaps for proper page aging.
5252 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5254 struct md_page *pvh;
5255 struct rwlock *lock;
5260 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5261 ("pmap_page_exists_quick: page %p is not managed", m));
5263 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5265 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5266 if (PV_PMAP(pv) == pmap) {
5274 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5275 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5276 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5277 if (PV_PMAP(pv) == pmap) {
5291 * pmap_page_wired_mappings:
5293 * Return the number of managed mappings to the given physical page
5297 pmap_page_wired_mappings(vm_page_t m)
5299 struct rwlock *lock;
5300 struct md_page *pvh;
5304 int count, md_gen, pvh_gen;
5306 if ((m->oflags & VPO_UNMANAGED) != 0)
5308 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5312 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5314 if (!PMAP_TRYLOCK(pmap)) {
5315 md_gen = m->md.pv_gen;
5319 if (md_gen != m->md.pv_gen) {
5324 pte = pmap_pte(pmap, pv->pv_va);
5325 if ((*pte & PG_W) != 0)
5329 if ((m->flags & PG_FICTITIOUS) == 0) {
5330 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5331 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5333 if (!PMAP_TRYLOCK(pmap)) {
5334 md_gen = m->md.pv_gen;
5335 pvh_gen = pvh->pv_gen;
5339 if (md_gen != m->md.pv_gen ||
5340 pvh_gen != pvh->pv_gen) {
5345 pte = pmap_pde(pmap, pv->pv_va);
5346 if ((*pte & PG_W) != 0)
5356 * Returns TRUE if the given page is mapped individually or as part of
5357 * a 2mpage. Otherwise, returns FALSE.
5360 pmap_page_is_mapped(vm_page_t m)
5362 struct rwlock *lock;
5365 if ((m->oflags & VPO_UNMANAGED) != 0)
5367 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5369 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5370 ((m->flags & PG_FICTITIOUS) == 0 &&
5371 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5377 * Destroy all managed, non-wired mappings in the given user-space
5378 * pmap. This pmap cannot be active on any processor besides the
5381 * This function cannot be applied to the kernel pmap. Moreover, it
5382 * is not intended for general use. It is only to be used during
5383 * process termination. Consequently, it can be implemented in ways
5384 * that make it faster than pmap_remove(). First, it can more quickly
5385 * destroy mappings by iterating over the pmap's collection of PV
5386 * entries, rather than searching the page table. Second, it doesn't
5387 * have to test and clear the page table entries atomically, because
5388 * no processor is currently accessing the user address space. In
5389 * particular, a page table entry's dirty bit won't change state once
5390 * this function starts.
5393 pmap_remove_pages(pmap_t pmap)
5396 pt_entry_t *pte, tpte;
5397 pt_entry_t PG_M, PG_RW, PG_V;
5398 struct spglist free;
5399 vm_page_t m, mpte, mt;
5401 struct md_page *pvh;
5402 struct pv_chunk *pc, *npc;
5403 struct rwlock *lock;
5405 uint64_t inuse, bitmask;
5406 int allfree, field, freed, idx;
5407 boolean_t superpage;
5411 * Assert that the given pmap is only active on the current
5412 * CPU. Unfortunately, we cannot block another CPU from
5413 * activating the pmap while this function is executing.
5415 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5418 cpuset_t other_cpus;
5420 other_cpus = all_cpus;
5422 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5423 CPU_AND(&other_cpus, &pmap->pm_active);
5425 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5430 PG_M = pmap_modified_bit(pmap);
5431 PG_V = pmap_valid_bit(pmap);
5432 PG_RW = pmap_rw_bit(pmap);
5436 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5439 for (field = 0; field < _NPCM; field++) {
5440 inuse = ~pc->pc_map[field] & pc_freemask[field];
5441 while (inuse != 0) {
5443 bitmask = 1UL << bit;
5444 idx = field * 64 + bit;
5445 pv = &pc->pc_pventry[idx];
5448 pte = pmap_pdpe(pmap, pv->pv_va);
5450 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5452 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5455 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5457 pte = &pte[pmap_pte_index(pv->pv_va)];
5461 * Keep track whether 'tpte' is a
5462 * superpage explicitly instead of
5463 * relying on PG_PS being set.
5465 * This is because PG_PS is numerically
5466 * identical to PG_PTE_PAT and thus a
5467 * regular page could be mistaken for
5473 if ((tpte & PG_V) == 0) {
5474 panic("bad pte va %lx pte %lx",
5479 * We cannot remove wired pages from a process' mapping at this time
5487 pa = tpte & PG_PS_FRAME;
5489 pa = tpte & PG_FRAME;
5491 m = PHYS_TO_VM_PAGE(pa);
5492 KASSERT(m->phys_addr == pa,
5493 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5494 m, (uintmax_t)m->phys_addr,
5497 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5498 m < &vm_page_array[vm_page_array_size],
5499 ("pmap_remove_pages: bad tpte %#jx",
5505 * Update the vm_page_t clean/reference bits.
5507 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5509 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5515 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5518 pc->pc_map[field] |= bitmask;
5520 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
5521 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
5522 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5524 if (TAILQ_EMPTY(&pvh->pv_list)) {
5525 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5526 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
5527 TAILQ_EMPTY(&mt->md.pv_list))
5528 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5530 mpte = pmap_lookup_pt_page(pmap, pv->pv_va);
5532 pmap_remove_pt_page(pmap, mpte);
5533 pmap_resident_count_dec(pmap, 1);
5534 KASSERT(mpte->wire_count == NPTEPG,
5535 ("pmap_remove_pages: pte page wire count error"));
5536 mpte->wire_count = 0;
5537 pmap_add_delayed_free_list(mpte, &free, FALSE);
5538 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
5541 pmap_resident_count_dec(pmap, 1);
5542 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5544 if ((m->aflags & PGA_WRITEABLE) != 0 &&
5545 TAILQ_EMPTY(&m->md.pv_list) &&
5546 (m->flags & PG_FICTITIOUS) == 0) {
5547 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5548 if (TAILQ_EMPTY(&pvh->pv_list))
5549 vm_page_aflag_clear(m, PGA_WRITEABLE);
5552 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
5556 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5557 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5558 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5560 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5566 pmap_invalidate_all(pmap);
5568 pmap_free_zero_pages(&free);
5572 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
5574 struct rwlock *lock;
5576 struct md_page *pvh;
5577 pt_entry_t *pte, mask;
5578 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5580 int md_gen, pvh_gen;
5584 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5587 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5589 if (!PMAP_TRYLOCK(pmap)) {
5590 md_gen = m->md.pv_gen;
5594 if (md_gen != m->md.pv_gen) {
5599 pte = pmap_pte(pmap, pv->pv_va);
5602 PG_M = pmap_modified_bit(pmap);
5603 PG_RW = pmap_rw_bit(pmap);
5604 mask |= PG_RW | PG_M;
5607 PG_A = pmap_accessed_bit(pmap);
5608 PG_V = pmap_valid_bit(pmap);
5609 mask |= PG_V | PG_A;
5611 rv = (*pte & mask) == mask;
5616 if ((m->flags & PG_FICTITIOUS) == 0) {
5617 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5618 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5620 if (!PMAP_TRYLOCK(pmap)) {
5621 md_gen = m->md.pv_gen;
5622 pvh_gen = pvh->pv_gen;
5626 if (md_gen != m->md.pv_gen ||
5627 pvh_gen != pvh->pv_gen) {
5632 pte = pmap_pde(pmap, pv->pv_va);
5635 PG_M = pmap_modified_bit(pmap);
5636 PG_RW = pmap_rw_bit(pmap);
5637 mask |= PG_RW | PG_M;
5640 PG_A = pmap_accessed_bit(pmap);
5641 PG_V = pmap_valid_bit(pmap);
5642 mask |= PG_V | PG_A;
5644 rv = (*pte & mask) == mask;
5658 * Return whether or not the specified physical page was modified
5659 * in any physical maps.
5662 pmap_is_modified(vm_page_t m)
5665 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5666 ("pmap_is_modified: page %p is not managed", m));
5669 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5670 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
5671 * is clear, no PTEs can have PG_M set.
5673 VM_OBJECT_ASSERT_WLOCKED(m->object);
5674 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
5676 return (pmap_page_test_mappings(m, FALSE, TRUE));
5680 * pmap_is_prefaultable:
5682 * Return whether or not the specified virtual address is eligible
5686 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
5689 pt_entry_t *pte, PG_V;
5692 PG_V = pmap_valid_bit(pmap);
5695 pde = pmap_pde(pmap, addr);
5696 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
5697 pte = pmap_pde_to_pte(pde, addr);
5698 rv = (*pte & PG_V) == 0;
5705 * pmap_is_referenced:
5707 * Return whether or not the specified physical page was referenced
5708 * in any physical maps.
5711 pmap_is_referenced(vm_page_t m)
5714 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5715 ("pmap_is_referenced: page %p is not managed", m));
5716 return (pmap_page_test_mappings(m, TRUE, FALSE));
5720 * Clear the write and modified bits in each of the given page's mappings.
5723 pmap_remove_write(vm_page_t m)
5725 struct md_page *pvh;
5727 struct rwlock *lock;
5728 pv_entry_t next_pv, pv;
5730 pt_entry_t oldpte, *pte, PG_M, PG_RW;
5732 int pvh_gen, md_gen;
5734 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5735 ("pmap_remove_write: page %p is not managed", m));
5738 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5739 * set by another thread while the object is locked. Thus,
5740 * if PGA_WRITEABLE is clear, no page table entries need updating.
5742 VM_OBJECT_ASSERT_WLOCKED(m->object);
5743 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
5745 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5746 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5749 if ((m->flags & PG_FICTITIOUS) != 0)
5750 goto small_mappings;
5751 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
5753 if (!PMAP_TRYLOCK(pmap)) {
5754 pvh_gen = pvh->pv_gen;
5758 if (pvh_gen != pvh->pv_gen) {
5764 PG_RW = pmap_rw_bit(pmap);
5766 pde = pmap_pde(pmap, va);
5767 if ((*pde & PG_RW) != 0)
5768 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
5769 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
5770 ("inconsistent pv lock %p %p for page %p",
5771 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
5775 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5777 if (!PMAP_TRYLOCK(pmap)) {
5778 pvh_gen = pvh->pv_gen;
5779 md_gen = m->md.pv_gen;
5783 if (pvh_gen != pvh->pv_gen ||
5784 md_gen != m->md.pv_gen) {
5790 PG_M = pmap_modified_bit(pmap);
5791 PG_RW = pmap_rw_bit(pmap);
5792 pde = pmap_pde(pmap, pv->pv_va);
5793 KASSERT((*pde & PG_PS) == 0,
5794 ("pmap_remove_write: found a 2mpage in page %p's pv list",
5796 pte = pmap_pde_to_pte(pde, pv->pv_va);
5799 if (oldpte & PG_RW) {
5800 if (!atomic_cmpset_long(pte, oldpte, oldpte &
5803 if ((oldpte & PG_M) != 0)
5805 pmap_invalidate_page(pmap, pv->pv_va);
5810 vm_page_aflag_clear(m, PGA_WRITEABLE);
5811 pmap_delayed_invl_wait(m);
5814 static __inline boolean_t
5815 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
5818 if (!pmap_emulate_ad_bits(pmap))
5821 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
5824 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
5825 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
5826 * if the EPT_PG_WRITE bit is set.
5828 if ((pte & EPT_PG_WRITE) != 0)
5832 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
5834 if ((pte & EPT_PG_EXECUTE) == 0 ||
5835 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
5841 #define PMAP_TS_REFERENCED_MAX 5
5844 * pmap_ts_referenced:
5846 * Return a count of reference bits for a page, clearing those bits.
5847 * It is not necessary for every reference bit to be cleared, but it
5848 * is necessary that 0 only be returned when there are truly no
5849 * reference bits set.
5851 * XXX: The exact number of bits to check and clear is a matter that
5852 * should be tested and standardized at some point in the future for
5853 * optimal aging of shared pages.
5855 * A DI block is not needed within this function, because
5856 * invalidations are performed before the PV list lock is
5860 pmap_ts_referenced(vm_page_t m)
5862 struct md_page *pvh;
5865 struct rwlock *lock;
5866 pd_entry_t oldpde, *pde;
5867 pt_entry_t *pte, PG_A;
5870 int cleared, md_gen, not_cleared, pvh_gen;
5871 struct spglist free;
5874 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5875 ("pmap_ts_referenced: page %p is not managed", m));
5878 pa = VM_PAGE_TO_PHYS(m);
5879 lock = PHYS_TO_PV_LIST_LOCK(pa);
5880 pvh = pa_to_pvh(pa);
5884 if ((m->flags & PG_FICTITIOUS) != 0 ||
5885 (pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
5886 goto small_mappings;
5892 if (!PMAP_TRYLOCK(pmap)) {
5893 pvh_gen = pvh->pv_gen;
5897 if (pvh_gen != pvh->pv_gen) {
5902 PG_A = pmap_accessed_bit(pmap);
5904 pde = pmap_pde(pmap, pv->pv_va);
5906 if ((*pde & PG_A) != 0) {
5908 * Since this reference bit is shared by 512 4KB
5909 * pages, it should not be cleared every time it is
5910 * tested. Apply a simple "hash" function on the
5911 * physical page number, the virtual superpage number,
5912 * and the pmap address to select one 4KB page out of
5913 * the 512 on which testing the reference bit will
5914 * result in clearing that reference bit. This
5915 * function is designed to avoid the selection of the
5916 * same 4KB page for every 2MB page mapping.
5918 * On demotion, a mapping that hasn't been referenced
5919 * is simply destroyed. To avoid the possibility of a
5920 * subsequent page fault on a demoted wired mapping,
5921 * always leave its reference bit set. Moreover,
5922 * since the superpage is wired, the current state of
5923 * its reference bit won't affect page replacement.
5925 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
5926 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
5927 (*pde & PG_W) == 0) {
5928 if (safe_to_clear_referenced(pmap, oldpde)) {
5929 atomic_clear_long(pde, PG_A);
5930 pmap_invalidate_page(pmap, pv->pv_va);
5932 } else if (pmap_demote_pde_locked(pmap, pde,
5933 pv->pv_va, &lock)) {
5935 * Remove the mapping to a single page
5936 * so that a subsequent access may
5937 * repromote. Since the underlying
5938 * page table page is fully populated,
5939 * this removal never frees a page
5943 va += VM_PAGE_TO_PHYS(m) - (oldpde &
5945 pte = pmap_pde_to_pte(pde, va);
5946 pmap_remove_pte(pmap, pte, va, *pde,
5948 pmap_invalidate_page(pmap, va);
5954 * The superpage mapping was removed
5955 * entirely and therefore 'pv' is no
5963 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
5964 ("inconsistent pv lock %p %p for page %p",
5965 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
5970 /* Rotate the PV list if it has more than one entry. */
5971 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
5972 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5973 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5976 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
5978 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
5980 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
5987 if (!PMAP_TRYLOCK(pmap)) {
5988 pvh_gen = pvh->pv_gen;
5989 md_gen = m->md.pv_gen;
5993 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
5998 PG_A = pmap_accessed_bit(pmap);
5999 pde = pmap_pde(pmap, pv->pv_va);
6000 KASSERT((*pde & PG_PS) == 0,
6001 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6003 pte = pmap_pde_to_pte(pde, pv->pv_va);
6004 if ((*pte & PG_A) != 0) {
6005 if (safe_to_clear_referenced(pmap, *pte)) {
6006 atomic_clear_long(pte, PG_A);
6007 pmap_invalidate_page(pmap, pv->pv_va);
6009 } else if ((*pte & PG_W) == 0) {
6011 * Wired pages cannot be paged out so
6012 * doing accessed bit emulation for
6013 * them is wasted effort. We do the
6014 * hard work for unwired pages only.
6016 pmap_remove_pte(pmap, pte, pv->pv_va,
6017 *pde, &free, &lock);
6018 pmap_invalidate_page(pmap, pv->pv_va);
6023 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6024 ("inconsistent pv lock %p %p for page %p",
6025 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6030 /* Rotate the PV list if it has more than one entry. */
6031 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6032 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6033 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6036 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6037 not_cleared < PMAP_TS_REFERENCED_MAX);
6040 pmap_free_zero_pages(&free);
6041 return (cleared + not_cleared);
6045 * Apply the given advice to the specified range of addresses within the
6046 * given pmap. Depending on the advice, clear the referenced and/or
6047 * modified flags in each mapping and set the mapped page's dirty field.
6050 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6052 struct rwlock *lock;
6053 pml4_entry_t *pml4e;
6055 pd_entry_t oldpde, *pde;
6056 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6057 vm_offset_t va_next;
6059 boolean_t anychanged;
6061 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6063 pmap_delayed_invl_started();
6066 * A/D bit emulation requires an alternate code path when clearing
6067 * the modified and accessed bits below. Since this function is
6068 * advisory in nature we skip it entirely for pmaps that require
6069 * A/D bit emulation.
6071 if (pmap_emulate_ad_bits(pmap))
6074 PG_A = pmap_accessed_bit(pmap);
6075 PG_G = pmap_global_bit(pmap);
6076 PG_M = pmap_modified_bit(pmap);
6077 PG_V = pmap_valid_bit(pmap);
6078 PG_RW = pmap_rw_bit(pmap);
6081 for (; sva < eva; sva = va_next) {
6082 pml4e = pmap_pml4e(pmap, sva);
6083 if ((*pml4e & PG_V) == 0) {
6084 va_next = (sva + NBPML4) & ~PML4MASK;
6089 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6090 if ((*pdpe & PG_V) == 0) {
6091 va_next = (sva + NBPDP) & ~PDPMASK;
6096 va_next = (sva + NBPDR) & ~PDRMASK;
6099 pde = pmap_pdpe_to_pde(pdpe, sva);
6101 if ((oldpde & PG_V) == 0)
6103 else if ((oldpde & PG_PS) != 0) {
6104 if ((oldpde & PG_MANAGED) == 0)
6107 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6112 * The large page mapping was destroyed.
6118 * Unless the page mappings are wired, remove the
6119 * mapping to a single page so that a subsequent
6120 * access may repromote. Since the underlying page
6121 * table page is fully populated, this removal never
6122 * frees a page table page.
6124 if ((oldpde & PG_W) == 0) {
6125 pte = pmap_pde_to_pte(pde, sva);
6126 KASSERT((*pte & PG_V) != 0,
6127 ("pmap_advise: invalid PTE"));
6128 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6137 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6139 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED |
6142 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6143 if (advice == MADV_DONTNEED) {
6145 * Future calls to pmap_is_modified()
6146 * can be avoided by making the page
6149 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6152 atomic_clear_long(pte, PG_M | PG_A);
6153 } else if ((*pte & PG_A) != 0)
6154 atomic_clear_long(pte, PG_A);
6157 if ((*pte & PG_G) != 0)
6158 pmap_invalidate_page(pmap, sva);
6164 pmap_invalidate_all(pmap);
6166 pmap_delayed_invl_finished();
6170 * Clear the modify bits on the specified physical page.
6173 pmap_clear_modify(vm_page_t m)
6175 struct md_page *pvh;
6177 pv_entry_t next_pv, pv;
6178 pd_entry_t oldpde, *pde;
6179 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6180 struct rwlock *lock;
6182 int md_gen, pvh_gen;
6184 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6185 ("pmap_clear_modify: page %p is not managed", m));
6186 VM_OBJECT_ASSERT_WLOCKED(m->object);
6187 KASSERT(!vm_page_xbusied(m),
6188 ("pmap_clear_modify: page %p is exclusive busied", m));
6191 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6192 * If the object containing the page is locked and the page is not
6193 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6195 if ((m->aflags & PGA_WRITEABLE) == 0)
6197 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6198 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6201 if ((m->flags & PG_FICTITIOUS) != 0)
6202 goto small_mappings;
6203 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6205 if (!PMAP_TRYLOCK(pmap)) {
6206 pvh_gen = pvh->pv_gen;
6210 if (pvh_gen != pvh->pv_gen) {
6215 PG_M = pmap_modified_bit(pmap);
6216 PG_V = pmap_valid_bit(pmap);
6217 PG_RW = pmap_rw_bit(pmap);
6219 pde = pmap_pde(pmap, va);
6221 if ((oldpde & PG_RW) != 0) {
6222 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6223 if ((oldpde & PG_W) == 0) {
6225 * Write protect the mapping to a
6226 * single page so that a subsequent
6227 * write access may repromote.
6229 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6231 pte = pmap_pde_to_pte(pde, va);
6233 if ((oldpte & PG_V) != 0) {
6234 while (!atomic_cmpset_long(pte,
6236 oldpte & ~(PG_M | PG_RW)))
6239 pmap_invalidate_page(pmap, va);
6247 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6249 if (!PMAP_TRYLOCK(pmap)) {
6250 md_gen = m->md.pv_gen;
6251 pvh_gen = pvh->pv_gen;
6255 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6260 PG_M = pmap_modified_bit(pmap);
6261 PG_RW = pmap_rw_bit(pmap);
6262 pde = pmap_pde(pmap, pv->pv_va);
6263 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6264 " a 2mpage in page %p's pv list", m));
6265 pte = pmap_pde_to_pte(pde, pv->pv_va);
6266 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6267 atomic_clear_long(pte, PG_M);
6268 pmap_invalidate_page(pmap, pv->pv_va);
6276 * Miscellaneous support routines follow
6279 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6280 static __inline void
6281 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6286 * The cache mode bits are all in the low 32-bits of the
6287 * PTE, so we can just spin on updating the low 32-bits.
6290 opte = *(u_int *)pte;
6291 npte = opte & ~mask;
6293 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6296 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6297 static __inline void
6298 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6303 * The cache mode bits are all in the low 32-bits of the
6304 * PDE, so we can just spin on updating the low 32-bits.
6307 opde = *(u_int *)pde;
6308 npde = opde & ~mask;
6310 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6314 * Map a set of physical memory pages into the kernel virtual
6315 * address space. Return a pointer to where it is mapped. This
6316 * routine is intended to be used for mapping device memory,
6320 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6322 struct pmap_preinit_mapping *ppim;
6323 vm_offset_t va, offset;
6327 offset = pa & PAGE_MASK;
6328 size = round_page(offset + size);
6329 pa = trunc_page(pa);
6331 if (!pmap_initialized) {
6333 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6334 ppim = pmap_preinit_mapping + i;
6335 if (ppim->va == 0) {
6339 ppim->va = virtual_avail;
6340 virtual_avail += size;
6346 panic("%s: too many preinit mappings", __func__);
6349 * If we have a preinit mapping, re-use it.
6351 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6352 ppim = pmap_preinit_mapping + i;
6353 if (ppim->pa == pa && ppim->sz == size &&
6355 return ((void *)(ppim->va + offset));
6358 * If the specified range of physical addresses fits within
6359 * the direct map window, use the direct map.
6361 if (pa < dmaplimit && pa + size < dmaplimit) {
6362 va = PHYS_TO_DMAP(pa);
6363 if (!pmap_change_attr(va, size, mode))
6364 return ((void *)(va + offset));
6366 va = kva_alloc(size);
6368 panic("%s: Couldn't allocate KVA", __func__);
6370 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6371 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6372 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6373 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6374 return ((void *)(va + offset));
6378 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6381 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6385 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6388 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6392 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6394 struct pmap_preinit_mapping *ppim;
6398 /* If we gave a direct map region in pmap_mapdev, do nothing */
6399 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6401 offset = va & PAGE_MASK;
6402 size = round_page(offset + size);
6403 va = trunc_page(va);
6404 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6405 ppim = pmap_preinit_mapping + i;
6406 if (ppim->va == va && ppim->sz == size) {
6407 if (pmap_initialized)
6413 if (va + size == virtual_avail)
6418 if (pmap_initialized)
6423 * Tries to demote a 1GB page mapping.
6426 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6428 pdp_entry_t newpdpe, oldpdpe;
6429 pd_entry_t *firstpde, newpde, *pde;
6430 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6434 PG_A = pmap_accessed_bit(pmap);
6435 PG_M = pmap_modified_bit(pmap);
6436 PG_V = pmap_valid_bit(pmap);
6437 PG_RW = pmap_rw_bit(pmap);
6439 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6441 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6442 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6443 if ((mpde = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6444 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6445 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6446 " in pmap %p", va, pmap);
6449 mpdepa = VM_PAGE_TO_PHYS(mpde);
6450 firstpde = (pd_entry_t *)PHYS_TO_DMAP(mpdepa);
6451 newpdpe = mpdepa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6452 KASSERT((oldpdpe & PG_A) != 0,
6453 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6454 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6455 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
6459 * Initialize the page directory page.
6461 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
6467 * Demote the mapping.
6472 * Invalidate a stale recursive mapping of the page directory page.
6474 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
6476 pmap_pdpe_demotions++;
6477 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
6478 " in pmap %p", va, pmap);
6483 * Sets the memory attribute for the specified page.
6486 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6489 m->md.pat_mode = ma;
6492 * If "m" is a normal page, update its direct mapping. This update
6493 * can be relied upon to perform any cache operations that are
6494 * required for data coherence.
6496 if ((m->flags & PG_FICTITIOUS) == 0 &&
6497 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6499 panic("memory attribute change on the direct map failed");
6503 * Changes the specified virtual address range's memory type to that given by
6504 * the parameter "mode". The specified virtual address range must be
6505 * completely contained within either the direct map or the kernel map. If
6506 * the virtual address range is contained within the kernel map, then the
6507 * memory type for each of the corresponding ranges of the direct map is also
6508 * changed. (The corresponding ranges of the direct map are those ranges that
6509 * map the same physical pages as the specified virtual address range.) These
6510 * changes to the direct map are necessary because Intel describes the
6511 * behavior of their processors as "undefined" if two or more mappings to the
6512 * same physical page have different memory types.
6514 * Returns zero if the change completed successfully, and either EINVAL or
6515 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6516 * of the virtual address range was not mapped, and ENOMEM is returned if
6517 * there was insufficient memory available to complete the change. In the
6518 * latter case, the memory type may have been changed on some part of the
6519 * virtual address range or the direct map.
6522 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6526 PMAP_LOCK(kernel_pmap);
6527 error = pmap_change_attr_locked(va, size, mode);
6528 PMAP_UNLOCK(kernel_pmap);
6533 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
6535 vm_offset_t base, offset, tmpva;
6536 vm_paddr_t pa_start, pa_end;
6540 int cache_bits_pte, cache_bits_pde, error;
6543 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6544 base = trunc_page(va);
6545 offset = va & PAGE_MASK;
6546 size = round_page(offset + size);
6549 * Only supported on kernel virtual addresses, including the direct
6550 * map but excluding the recursive map.
6552 if (base < DMAP_MIN_ADDRESS)
6555 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
6556 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
6560 * Pages that aren't mapped aren't supported. Also break down 2MB pages
6561 * into 4KB pages if required.
6563 for (tmpva = base; tmpva < base + size; ) {
6564 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6565 if (pdpe == NULL || *pdpe == 0)
6567 if (*pdpe & PG_PS) {
6569 * If the current 1GB page already has the required
6570 * memory type, then we need not demote this page. Just
6571 * increment tmpva to the next 1GB page frame.
6573 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
6574 tmpva = trunc_1gpage(tmpva) + NBPDP;
6579 * If the current offset aligns with a 1GB page frame
6580 * and there is at least 1GB left within the range, then
6581 * we need not break down this page into 2MB pages.
6583 if ((tmpva & PDPMASK) == 0 &&
6584 tmpva + PDPMASK < base + size) {
6588 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
6591 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6596 * If the current 2MB page already has the required
6597 * memory type, then we need not demote this page. Just
6598 * increment tmpva to the next 2MB page frame.
6600 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
6601 tmpva = trunc_2mpage(tmpva) + NBPDR;
6606 * If the current offset aligns with a 2MB page frame
6607 * and there is at least 2MB left within the range, then
6608 * we need not break down this page into 4KB pages.
6610 if ((tmpva & PDRMASK) == 0 &&
6611 tmpva + PDRMASK < base + size) {
6615 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
6618 pte = pmap_pde_to_pte(pde, tmpva);
6626 * Ok, all the pages exist, so run through them updating their
6627 * cache mode if required.
6629 pa_start = pa_end = 0;
6630 for (tmpva = base; tmpva < base + size; ) {
6631 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6632 if (*pdpe & PG_PS) {
6633 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
6634 pmap_pde_attr(pdpe, cache_bits_pde,
6638 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6639 (*pdpe & PG_PS_FRAME) < dmaplimit) {
6640 if (pa_start == pa_end) {
6641 /* Start physical address run. */
6642 pa_start = *pdpe & PG_PS_FRAME;
6643 pa_end = pa_start + NBPDP;
6644 } else if (pa_end == (*pdpe & PG_PS_FRAME))
6647 /* Run ended, update direct map. */
6648 error = pmap_change_attr_locked(
6649 PHYS_TO_DMAP(pa_start),
6650 pa_end - pa_start, mode);
6653 /* Start physical address run. */
6654 pa_start = *pdpe & PG_PS_FRAME;
6655 pa_end = pa_start + NBPDP;
6658 tmpva = trunc_1gpage(tmpva) + NBPDP;
6661 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6663 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
6664 pmap_pde_attr(pde, cache_bits_pde,
6668 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6669 (*pde & PG_PS_FRAME) < dmaplimit) {
6670 if (pa_start == pa_end) {
6671 /* Start physical address run. */
6672 pa_start = *pde & PG_PS_FRAME;
6673 pa_end = pa_start + NBPDR;
6674 } else if (pa_end == (*pde & PG_PS_FRAME))
6677 /* Run ended, update direct map. */
6678 error = pmap_change_attr_locked(
6679 PHYS_TO_DMAP(pa_start),
6680 pa_end - pa_start, mode);
6683 /* Start physical address run. */
6684 pa_start = *pde & PG_PS_FRAME;
6685 pa_end = pa_start + NBPDR;
6688 tmpva = trunc_2mpage(tmpva) + NBPDR;
6690 pte = pmap_pde_to_pte(pde, tmpva);
6691 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
6692 pmap_pte_attr(pte, cache_bits_pte,
6696 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6697 (*pte & PG_PS_FRAME) < dmaplimit) {
6698 if (pa_start == pa_end) {
6699 /* Start physical address run. */
6700 pa_start = *pte & PG_FRAME;
6701 pa_end = pa_start + PAGE_SIZE;
6702 } else if (pa_end == (*pte & PG_FRAME))
6703 pa_end += PAGE_SIZE;
6705 /* Run ended, update direct map. */
6706 error = pmap_change_attr_locked(
6707 PHYS_TO_DMAP(pa_start),
6708 pa_end - pa_start, mode);
6711 /* Start physical address run. */
6712 pa_start = *pte & PG_FRAME;
6713 pa_end = pa_start + PAGE_SIZE;
6719 if (error == 0 && pa_start != pa_end)
6720 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
6721 pa_end - pa_start, mode);
6724 * Flush CPU caches if required to make sure any data isn't cached that
6725 * shouldn't be, etc.
6728 pmap_invalidate_range(kernel_pmap, base, tmpva);
6729 pmap_invalidate_cache_range(base, tmpva, FALSE);
6735 * Demotes any mapping within the direct map region that covers more than the
6736 * specified range of physical addresses. This range's size must be a power
6737 * of two and its starting address must be a multiple of its size. Since the
6738 * demotion does not change any attributes of the mapping, a TLB invalidation
6739 * is not mandatory. The caller may, however, request a TLB invalidation.
6742 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
6751 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
6752 KASSERT((base & (len - 1)) == 0,
6753 ("pmap_demote_DMAP: base is not a multiple of len"));
6754 if (len < NBPDP && base < dmaplimit) {
6755 va = PHYS_TO_DMAP(base);
6757 PMAP_LOCK(kernel_pmap);
6758 pdpe = pmap_pdpe(kernel_pmap, va);
6759 if ((*pdpe & X86_PG_V) == 0)
6760 panic("pmap_demote_DMAP: invalid PDPE");
6761 if ((*pdpe & PG_PS) != 0) {
6762 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
6763 panic("pmap_demote_DMAP: PDPE failed");
6767 pde = pmap_pdpe_to_pde(pdpe, va);
6768 if ((*pde & X86_PG_V) == 0)
6769 panic("pmap_demote_DMAP: invalid PDE");
6770 if ((*pde & PG_PS) != 0) {
6771 if (!pmap_demote_pde(kernel_pmap, pde, va))
6772 panic("pmap_demote_DMAP: PDE failed");
6776 if (changed && invalidate)
6777 pmap_invalidate_page(kernel_pmap, va);
6778 PMAP_UNLOCK(kernel_pmap);
6783 * perform the pmap work for mincore
6786 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
6789 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
6793 PG_A = pmap_accessed_bit(pmap);
6794 PG_M = pmap_modified_bit(pmap);
6795 PG_V = pmap_valid_bit(pmap);
6796 PG_RW = pmap_rw_bit(pmap);
6800 pdep = pmap_pde(pmap, addr);
6801 if (pdep != NULL && (*pdep & PG_V)) {
6802 if (*pdep & PG_PS) {
6804 /* Compute the physical address of the 4KB page. */
6805 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
6807 val = MINCORE_SUPER;
6809 pte = *pmap_pde_to_pte(pdep, addr);
6810 pa = pte & PG_FRAME;
6818 if ((pte & PG_V) != 0) {
6819 val |= MINCORE_INCORE;
6820 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6821 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
6822 if ((pte & PG_A) != 0)
6823 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
6825 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
6826 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
6827 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
6828 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
6829 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
6832 PA_UNLOCK_COND(*locked_pa);
6838 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
6840 uint32_t gen, new_gen, pcid_next;
6842 CRITICAL_ASSERT(curthread);
6843 gen = PCPU_GET(pcid_gen);
6844 if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN ||
6845 pmap->pm_pcids[cpuid].pm_gen == gen)
6846 return (CR3_PCID_SAVE);
6847 pcid_next = PCPU_GET(pcid_next);
6848 KASSERT(pcid_next <= PMAP_PCID_OVERMAX, ("cpu %d pcid_next %#x",
6850 if (pcid_next == PMAP_PCID_OVERMAX) {
6854 PCPU_SET(pcid_gen, new_gen);
6855 pcid_next = PMAP_PCID_KERN + 1;
6859 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
6860 pmap->pm_pcids[cpuid].pm_gen = new_gen;
6861 PCPU_SET(pcid_next, pcid_next + 1);
6866 pmap_activate_sw(struct thread *td)
6868 pmap_t oldpmap, pmap;
6869 uint64_t cached, cr3;
6872 oldpmap = PCPU_GET(curpmap);
6873 pmap = vmspace_pmap(td->td_proc->p_vmspace);
6874 if (oldpmap == pmap)
6876 cpuid = PCPU_GET(cpuid);
6878 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
6880 CPU_SET(cpuid, &pmap->pm_active);
6883 if (pmap_pcid_enabled) {
6884 cached = pmap_pcid_alloc(pmap, cpuid);
6885 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
6886 pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
6887 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
6888 pmap->pm_pcids[cpuid].pm_pcid));
6889 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
6890 pmap == kernel_pmap,
6891 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
6892 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
6893 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
6894 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
6897 PCPU_INC(pm_save_cnt);
6899 } else if (cr3 != pmap->pm_cr3) {
6900 load_cr3(pmap->pm_cr3);
6902 PCPU_SET(curpmap, pmap);
6904 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
6906 CPU_CLR(cpuid, &oldpmap->pm_active);
6911 pmap_activate(struct thread *td)
6915 pmap_activate_sw(td);
6920 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
6925 * Increase the starting virtual address of the given mapping if a
6926 * different alignment might result in more superpage mappings.
6929 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
6930 vm_offset_t *addr, vm_size_t size)
6932 vm_offset_t superpage_offset;
6936 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
6937 offset += ptoa(object->pg_color);
6938 superpage_offset = offset & PDRMASK;
6939 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
6940 (*addr & PDRMASK) == superpage_offset)
6942 if ((*addr & PDRMASK) < superpage_offset)
6943 *addr = (*addr & ~PDRMASK) + superpage_offset;
6945 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
6949 static unsigned long num_dirty_emulations;
6950 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
6951 &num_dirty_emulations, 0, NULL);
6953 static unsigned long num_accessed_emulations;
6954 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
6955 &num_accessed_emulations, 0, NULL);
6957 static unsigned long num_superpage_accessed_emulations;
6958 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
6959 &num_superpage_accessed_emulations, 0, NULL);
6961 static unsigned long ad_emulation_superpage_promotions;
6962 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
6963 &ad_emulation_superpage_promotions, 0, NULL);
6964 #endif /* INVARIANTS */
6967 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
6970 struct rwlock *lock;
6973 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
6975 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
6976 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
6978 if (!pmap_emulate_ad_bits(pmap))
6981 PG_A = pmap_accessed_bit(pmap);
6982 PG_M = pmap_modified_bit(pmap);
6983 PG_V = pmap_valid_bit(pmap);
6984 PG_RW = pmap_rw_bit(pmap);
6990 pde = pmap_pde(pmap, va);
6991 if (pde == NULL || (*pde & PG_V) == 0)
6994 if ((*pde & PG_PS) != 0) {
6995 if (ftype == VM_PROT_READ) {
6997 atomic_add_long(&num_superpage_accessed_emulations, 1);
7005 pte = pmap_pde_to_pte(pde, va);
7006 if ((*pte & PG_V) == 0)
7009 if (ftype == VM_PROT_WRITE) {
7010 if ((*pte & PG_RW) == 0)
7013 * Set the modified and accessed bits simultaneously.
7015 * Intel EPT PTEs that do software emulation of A/D bits map
7016 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7017 * An EPT misconfiguration is triggered if the PTE is writable
7018 * but not readable (WR=10). This is avoided by setting PG_A
7019 * and PG_M simultaneously.
7021 *pte |= PG_M | PG_A;
7026 /* try to promote the mapping */
7027 if (va < VM_MAXUSER_ADDRESS)
7028 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7032 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7034 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7035 pmap_ps_enabled(pmap) &&
7036 (m->flags & PG_FICTITIOUS) == 0 &&
7037 vm_reserv_level_iffullpop(m) == 0) {
7038 pmap_promote_pde(pmap, pde, va, &lock);
7040 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7044 if (ftype == VM_PROT_WRITE)
7045 atomic_add_long(&num_dirty_emulations, 1);
7047 atomic_add_long(&num_accessed_emulations, 1);
7049 rv = 0; /* success */
7058 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7063 pt_entry_t *pte, PG_V;
7067 PG_V = pmap_valid_bit(pmap);
7070 pml4 = pmap_pml4e(pmap, va);
7072 if ((*pml4 & PG_V) == 0)
7075 pdp = pmap_pml4e_to_pdpe(pml4, va);
7077 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7080 pde = pmap_pdpe_to_pde(pdp, va);
7082 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7085 pte = pmap_pde_to_pte(pde, va);
7094 * Get the kernel virtual address of a set of physical pages. If there are
7095 * physical addresses not covered by the DMAP perform a transient mapping
7096 * that will be removed when calling pmap_unmap_io_transient.
7098 * \param page The pages the caller wishes to obtain the virtual
7099 * address on the kernel memory map.
7100 * \param vaddr On return contains the kernel virtual memory address
7101 * of the pages passed in the page parameter.
7102 * \param count Number of pages passed in.
7103 * \param can_fault TRUE if the thread using the mapped pages can take
7104 * page faults, FALSE otherwise.
7106 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7107 * finished or FALSE otherwise.
7111 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7112 boolean_t can_fault)
7115 boolean_t needs_mapping;
7117 int cache_bits, error, i;
7120 * Allocate any KVA space that we need, this is done in a separate
7121 * loop to prevent calling vmem_alloc while pinned.
7123 needs_mapping = FALSE;
7124 for (i = 0; i < count; i++) {
7125 paddr = VM_PAGE_TO_PHYS(page[i]);
7126 if (__predict_false(paddr >= dmaplimit)) {
7127 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7128 M_BESTFIT | M_WAITOK, &vaddr[i]);
7129 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7130 needs_mapping = TRUE;
7132 vaddr[i] = PHYS_TO_DMAP(paddr);
7136 /* Exit early if everything is covered by the DMAP */
7141 * NB: The sequence of updating a page table followed by accesses
7142 * to the corresponding pages used in the !DMAP case is subject to
7143 * the situation described in the "AMD64 Architecture Programmer's
7144 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7145 * Coherency Considerations". Therefore, issuing the INVLPG right
7146 * after modifying the PTE bits is crucial.
7150 for (i = 0; i < count; i++) {
7151 paddr = VM_PAGE_TO_PHYS(page[i]);
7152 if (paddr >= dmaplimit) {
7155 * Slow path, since we can get page faults
7156 * while mappings are active don't pin the
7157 * thread to the CPU and instead add a global
7158 * mapping visible to all CPUs.
7160 pmap_qenter(vaddr[i], &page[i], 1);
7162 pte = vtopte(vaddr[i]);
7163 cache_bits = pmap_cache_bits(kernel_pmap,
7164 page[i]->md.pat_mode, 0);
7165 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7172 return (needs_mapping);
7176 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7177 boolean_t can_fault)
7184 for (i = 0; i < count; i++) {
7185 paddr = VM_PAGE_TO_PHYS(page[i]);
7186 if (paddr >= dmaplimit) {
7188 pmap_qremove(vaddr[i], 1);
7189 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7195 pmap_quick_enter_page(vm_page_t m)
7199 paddr = VM_PAGE_TO_PHYS(m);
7200 if (paddr < dmaplimit)
7201 return (PHYS_TO_DMAP(paddr));
7202 mtx_lock_spin(&qframe_mtx);
7203 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7204 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7205 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7210 pmap_quick_remove_page(vm_offset_t addr)
7215 pte_store(vtopte(qframe), 0);
7217 mtx_unlock_spin(&qframe_mtx);
7220 #include "opt_ddb.h"
7222 #include <ddb/ddb.h>
7224 DB_SHOW_COMMAND(pte, pmap_print_pte)
7230 pt_entry_t *pte, PG_V;
7234 va = (vm_offset_t)addr;
7235 pmap = PCPU_GET(curpmap); /* XXX */
7237 db_printf("show pte addr\n");
7240 PG_V = pmap_valid_bit(pmap);
7241 pml4 = pmap_pml4e(pmap, va);
7242 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
7243 if ((*pml4 & PG_V) == 0) {
7247 pdp = pmap_pml4e_to_pdpe(pml4, va);
7248 db_printf(" pdpe %#016lx", *pdp);
7249 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
7253 pde = pmap_pdpe_to_pde(pdp, va);
7254 db_printf(" pde %#016lx", *pde);
7255 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
7259 pte = pmap_pde_to_pte(pde, va);
7260 db_printf(" pte %#016lx\n", *pte);
7263 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
7268 a = (vm_paddr_t)addr;
7269 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
7271 db_printf("show phys2dmap addr\n");