2 * Copyright (c) 1991 Regents of the University of California.
4 * Copyright (c) 1994 John S. Dyson
6 * Copyright (c) 1994 David Greenman
8 * Copyright (c) 2003 Peter Wemm
10 * Copyright (c) 2005-2010 Alan L. Cox <alc@cs.rice.edu>
11 * All rights reserved.
13 * This code is derived from software contributed to Berkeley by
14 * the Systems Programming Group of the University of Utah Computer
15 * Science Department and William Jolitz of UUNET Technologies Inc.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
25 * 3. All advertising materials mentioning features or use of this software
26 * must display the following acknowledgement:
27 * This product includes software developed by the University of
28 * California, Berkeley and its contributors.
29 * 4. Neither the name of the University nor the names of its contributors
30 * may be used to endorse or promote products derived from this software
31 * without specific prior written permission.
33 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
34 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
35 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
36 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
37 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
38 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
39 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
40 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
41 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
42 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
45 * from: @(#)pmap.c 7.7 (Berkeley) 5/12/91
48 * Copyright (c) 2003 Networks Associates Technology, Inc.
49 * All rights reserved.
51 * This software was developed for the FreeBSD Project by Jake Burkholder,
52 * Safeport Network Services, and Network Associates Laboratories, the
53 * Security Research Division of Network Associates, Inc. under
54 * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
55 * CHATS research program.
57 * Redistribution and use in source and binary forms, with or without
58 * modification, are permitted provided that the following conditions
60 * 1. Redistributions of source code must retain the above copyright
61 * notice, this list of conditions and the following disclaimer.
62 * 2. Redistributions in binary form must reproduce the above copyright
63 * notice, this list of conditions and the following disclaimer in the
64 * documentation and/or other materials provided with the distribution.
66 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
67 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
68 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
69 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
70 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
71 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
72 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
73 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
74 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
75 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
79 #define AMD64_NPT_AWARE
81 #include <sys/cdefs.h>
82 __FBSDID("$FreeBSD$");
85 * Manages physical address maps.
87 * Since the information managed by this module is
88 * also stored by the logical address mapping module,
89 * this module may throw away valid virtual-to-physical
90 * mappings at almost any time. However, invalidations
91 * of virtual-to-physical mappings must be done as
94 * In order to cope with hardware architectures which
95 * make virtual-to-physical map invalidates expensive,
96 * this module may delay invalidate or reduced protection
97 * operations until such time as they are actually
98 * necessary. This module is given full information as
99 * to which processors are currently using which maps,
100 * and to when physical maps must be made correct.
103 #include "opt_pmap.h"
106 #include <sys/param.h>
107 #include <sys/bitstring.h>
109 #include <sys/systm.h>
110 #include <sys/kernel.h>
112 #include <sys/lock.h>
113 #include <sys/malloc.h>
114 #include <sys/mman.h>
115 #include <sys/mutex.h>
116 #include <sys/proc.h>
117 #include <sys/rwlock.h>
119 #include <sys/turnstile.h>
120 #include <sys/vmem.h>
121 #include <sys/vmmeter.h>
122 #include <sys/sched.h>
123 #include <sys/sysctl.h>
127 #include <vm/vm_param.h>
128 #include <vm/vm_kern.h>
129 #include <vm/vm_page.h>
130 #include <vm/vm_map.h>
131 #include <vm/vm_object.h>
132 #include <vm/vm_extern.h>
133 #include <vm/vm_pageout.h>
134 #include <vm/vm_pager.h>
135 #include <vm/vm_phys.h>
136 #include <vm/vm_radix.h>
137 #include <vm/vm_reserv.h>
140 #include <machine/intr_machdep.h>
141 #include <x86/apicvar.h>
142 #include <machine/cpu.h>
143 #include <machine/cputypes.h>
144 #include <machine/md_var.h>
145 #include <machine/pcb.h>
146 #include <machine/specialreg.h>
148 #include <machine/smp.h>
151 static __inline boolean_t
152 pmap_type_guest(pmap_t pmap)
155 return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
158 static __inline boolean_t
159 pmap_emulate_ad_bits(pmap_t pmap)
162 return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
165 static __inline pt_entry_t
166 pmap_valid_bit(pmap_t pmap)
170 switch (pmap->pm_type) {
176 if (pmap_emulate_ad_bits(pmap))
177 mask = EPT_PG_EMUL_V;
182 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
188 static __inline pt_entry_t
189 pmap_rw_bit(pmap_t pmap)
193 switch (pmap->pm_type) {
199 if (pmap_emulate_ad_bits(pmap))
200 mask = EPT_PG_EMUL_RW;
205 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
211 static __inline pt_entry_t
212 pmap_global_bit(pmap_t pmap)
216 switch (pmap->pm_type) {
225 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
231 static __inline pt_entry_t
232 pmap_accessed_bit(pmap_t pmap)
236 switch (pmap->pm_type) {
242 if (pmap_emulate_ad_bits(pmap))
248 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
254 static __inline pt_entry_t
255 pmap_modified_bit(pmap_t pmap)
259 switch (pmap->pm_type) {
265 if (pmap_emulate_ad_bits(pmap))
271 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
277 extern struct pcpu __pcpu[];
279 #if !defined(DIAGNOSTIC)
280 #ifdef __GNUC_GNU_INLINE__
281 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
283 #define PMAP_INLINE extern inline
290 #define PV_STAT(x) do { x ; } while (0)
292 #define PV_STAT(x) do { } while (0)
295 #define pa_index(pa) ((pa) >> PDRSHIFT)
296 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
298 #define NPV_LIST_LOCKS MAXCPU
300 #define PHYS_TO_PV_LIST_LOCK(pa) \
301 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
303 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
304 struct rwlock **_lockp = (lockp); \
305 struct rwlock *_new_lock; \
307 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
308 if (_new_lock != *_lockp) { \
309 if (*_lockp != NULL) \
310 rw_wunlock(*_lockp); \
311 *_lockp = _new_lock; \
316 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
317 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
319 #define RELEASE_PV_LIST_LOCK(lockp) do { \
320 struct rwlock **_lockp = (lockp); \
322 if (*_lockp != NULL) { \
323 rw_wunlock(*_lockp); \
328 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
329 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
331 struct pmap kernel_pmap_store;
333 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
334 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
337 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
338 "Number of kernel page table pages allocated on bootup");
341 vm_paddr_t dmaplimit;
342 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
345 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
347 static int pat_works = 1;
348 SYSCTL_INT(_vm_pmap, OID_AUTO, pat_works, CTLFLAG_RD, &pat_works, 1,
349 "Is page attribute table fully functional?");
351 static int pg_ps_enabled = 1;
352 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
353 &pg_ps_enabled, 0, "Are large page mappings enabled?");
355 #define PAT_INDEX_SIZE 8
356 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
358 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
359 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
360 u_int64_t KPDPphys; /* phys addr of kernel level 3 */
361 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
363 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
364 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
365 static int ndmpdpphys; /* number of DMPDPphys pages */
368 * pmap_mapdev support pre initialization (i.e. console)
370 #define PMAP_PREINIT_MAPPING_COUNT 8
371 static struct pmap_preinit_mapping {
376 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
377 static int pmap_initialized;
380 * Data for the pv entry allocation mechanism.
381 * Updates to pv_invl_gen are protected by the pv_list_locks[]
382 * elements, but reads are not.
384 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
385 static struct mtx pv_chunks_mutex;
386 static struct rwlock pv_list_locks[NPV_LIST_LOCKS];
387 static u_long pv_invl_gen[NPV_LIST_LOCKS];
388 static struct md_page *pv_table;
391 * All those kernel PT submaps that BSD is so fond of
393 pt_entry_t *CMAP1 = 0;
395 static vm_offset_t qframe = 0;
396 static struct mtx qframe_mtx;
398 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
400 int pmap_pcid_enabled = 1;
401 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
402 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
403 int invpcid_works = 0;
404 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
405 "Is the invpcid instruction available ?");
408 pmap_pcid_save_cnt_proc(SYSCTL_HANDLER_ARGS)
415 res += cpuid_to_pcpu[i]->pc_pm_save_cnt;
417 return (sysctl_handle_64(oidp, &res, 0, req));
419 SYSCTL_PROC(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLTYPE_U64 | CTLFLAG_RW |
420 CTLFLAG_MPSAFE, NULL, 0, pmap_pcid_save_cnt_proc, "QU",
421 "Count of saved TLB context on switch");
423 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
424 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
425 static struct mtx invl_gen_mtx;
426 static u_long pmap_invl_gen = 0;
427 /* Fake lock object to satisfy turnstiles interface. */
428 static struct lock_object invl_gen_ts = {
432 #define PMAP_ASSERT_NOT_IN_DI() \
433 KASSERT(curthread->td_md.md_invl_gen.gen == 0, ("DI already started"))
436 * Start a new Delayed Invalidation (DI) block of code, executed by
437 * the current thread. Within a DI block, the current thread may
438 * destroy both the page table and PV list entries for a mapping and
439 * then release the corresponding PV list lock before ensuring that
440 * the mapping is flushed from the TLBs of any processors with the
444 pmap_delayed_invl_started(void)
446 struct pmap_invl_gen *invl_gen;
449 invl_gen = &curthread->td_md.md_invl_gen;
450 PMAP_ASSERT_NOT_IN_DI();
451 mtx_lock(&invl_gen_mtx);
452 if (LIST_EMPTY(&pmap_invl_gen_tracker))
453 currgen = pmap_invl_gen;
455 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
456 invl_gen->gen = currgen + 1;
457 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
458 mtx_unlock(&invl_gen_mtx);
462 * Finish the DI block, previously started by the current thread. All
463 * required TLB flushes for the pages marked by
464 * pmap_delayed_invl_page() must be finished before this function is
467 * This function works by bumping the global DI generation number to
468 * the generation number of the current thread's DI, unless there is a
469 * pending DI that started earlier. In the latter case, bumping the
470 * global DI generation number would incorrectly signal that the
471 * earlier DI had finished. Instead, this function bumps the earlier
472 * DI's generation number to match the generation number of the
473 * current thread's DI.
476 pmap_delayed_invl_finished(void)
478 struct pmap_invl_gen *invl_gen, *next;
479 struct turnstile *ts;
481 invl_gen = &curthread->td_md.md_invl_gen;
482 KASSERT(invl_gen->gen != 0, ("missed invl_started"));
483 mtx_lock(&invl_gen_mtx);
484 next = LIST_NEXT(invl_gen, link);
486 turnstile_chain_lock(&invl_gen_ts);
487 ts = turnstile_lookup(&invl_gen_ts);
488 pmap_invl_gen = invl_gen->gen;
490 turnstile_broadcast(ts, TS_SHARED_QUEUE);
491 turnstile_unpend(ts, TS_SHARED_LOCK);
493 turnstile_chain_unlock(&invl_gen_ts);
495 next->gen = invl_gen->gen;
497 LIST_REMOVE(invl_gen, link);
498 mtx_unlock(&invl_gen_mtx);
503 static long invl_wait;
504 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
505 "Number of times DI invalidation blocked pmap_remove_all/write");
509 pmap_delayed_invl_genp(vm_page_t m)
512 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
516 * Ensure that all currently executing DI blocks, that need to flush
517 * TLB for the given page m, actually flushed the TLB at the time the
518 * function returned. If the page m has an empty PV list and we call
519 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
520 * valid mapping for the page m in either its page table or TLB.
522 * This function works by blocking until the global DI generation
523 * number catches up with the generation number associated with the
524 * given page m and its PV list. Since this function's callers
525 * typically own an object lock and sometimes own a page lock, it
526 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
530 pmap_delayed_invl_wait(vm_page_t m)
533 struct turnstile *ts;
536 bool accounted = false;
540 m_gen = pmap_delayed_invl_genp(m);
541 while (*m_gen > pmap_invl_gen) {
544 atomic_add_long(&invl_wait, 1);
548 ts = turnstile_trywait(&invl_gen_ts);
549 if (*m_gen > pmap_invl_gen)
550 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
552 turnstile_cancel(ts);
557 * Mark the page m's PV list as participating in the current thread's
558 * DI block. Any threads concurrently using m's PV list to remove or
559 * restrict all mappings to m will wait for the current thread's DI
560 * block to complete before proceeding.
562 * The function works by setting the DI generation number for m's PV
563 * list to at least * the number for the current thread. This forces
564 * a caller to pmap_delayed_invl_wait() to spin until current thread
565 * calls pmap_delayed_invl_finished().
568 pmap_delayed_invl_page(vm_page_t m)
572 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
573 gen = curthread->td_md.md_invl_gen.gen;
576 m_gen = pmap_delayed_invl_genp(m);
584 static caddr_t crashdumpmap;
586 static void free_pv_chunk(struct pv_chunk *pc);
587 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
588 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
589 static int popcnt_pc_map_pq(uint64_t *map);
590 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
591 static void reserve_pv_entries(pmap_t pmap, int needed,
592 struct rwlock **lockp);
593 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
594 struct rwlock **lockp);
595 static boolean_t pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
596 struct rwlock **lockp);
597 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
598 struct rwlock **lockp);
599 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
600 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
603 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode);
604 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
605 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
606 vm_offset_t va, struct rwlock **lockp);
607 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
609 static boolean_t pmap_enter_pde(pmap_t pmap, vm_offset_t va, vm_page_t m,
610 vm_prot_t prot, struct rwlock **lockp);
611 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
612 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
613 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
614 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
615 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
616 static vm_page_t pmap_lookup_pt_page(pmap_t pmap, vm_offset_t va);
617 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask);
618 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
619 struct rwlock **lockp);
620 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
622 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
623 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
624 struct spglist *free, struct rwlock **lockp);
625 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
626 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
627 static void pmap_remove_pt_page(pmap_t pmap, vm_page_t mpte);
628 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
629 struct spglist *free);
630 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
631 vm_page_t m, struct rwlock **lockp);
632 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
634 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
636 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
637 struct rwlock **lockp);
638 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
639 struct rwlock **lockp);
640 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
641 struct rwlock **lockp);
643 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
644 struct spglist *free);
645 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
646 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
649 * Move the kernel virtual free pointer to the next
650 * 2MB. This is used to help improve performance
651 * by using a large (2MB) page for much of the kernel
652 * (.text, .data, .bss)
655 pmap_kmem_choose(vm_offset_t addr)
657 vm_offset_t newaddr = addr;
659 newaddr = roundup2(addr, NBPDR);
663 /********************/
664 /* Inline functions */
665 /********************/
667 /* Return a non-clipped PD index for a given VA */
668 static __inline vm_pindex_t
669 pmap_pde_pindex(vm_offset_t va)
671 return (va >> PDRSHIFT);
675 /* Return various clipped indexes for a given VA */
676 static __inline vm_pindex_t
677 pmap_pte_index(vm_offset_t va)
680 return ((va >> PAGE_SHIFT) & ((1ul << NPTEPGSHIFT) - 1));
683 static __inline vm_pindex_t
684 pmap_pde_index(vm_offset_t va)
687 return ((va >> PDRSHIFT) & ((1ul << NPDEPGSHIFT) - 1));
690 static __inline vm_pindex_t
691 pmap_pdpe_index(vm_offset_t va)
694 return ((va >> PDPSHIFT) & ((1ul << NPDPEPGSHIFT) - 1));
697 static __inline vm_pindex_t
698 pmap_pml4e_index(vm_offset_t va)
701 return ((va >> PML4SHIFT) & ((1ul << NPML4EPGSHIFT) - 1));
704 /* Return a pointer to the PML4 slot that corresponds to a VA */
705 static __inline pml4_entry_t *
706 pmap_pml4e(pmap_t pmap, vm_offset_t va)
709 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
712 /* Return a pointer to the PDP slot that corresponds to a VA */
713 static __inline pdp_entry_t *
714 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
718 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
719 return (&pdpe[pmap_pdpe_index(va)]);
722 /* Return a pointer to the PDP slot that corresponds to a VA */
723 static __inline pdp_entry_t *
724 pmap_pdpe(pmap_t pmap, vm_offset_t va)
729 PG_V = pmap_valid_bit(pmap);
730 pml4e = pmap_pml4e(pmap, va);
731 if ((*pml4e & PG_V) == 0)
733 return (pmap_pml4e_to_pdpe(pml4e, va));
736 /* Return a pointer to the PD slot that corresponds to a VA */
737 static __inline pd_entry_t *
738 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
742 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
743 return (&pde[pmap_pde_index(va)]);
746 /* Return a pointer to the PD slot that corresponds to a VA */
747 static __inline pd_entry_t *
748 pmap_pde(pmap_t pmap, vm_offset_t va)
753 PG_V = pmap_valid_bit(pmap);
754 pdpe = pmap_pdpe(pmap, va);
755 if (pdpe == NULL || (*pdpe & PG_V) == 0)
757 return (pmap_pdpe_to_pde(pdpe, va));
760 /* Return a pointer to the PT slot that corresponds to a VA */
761 static __inline pt_entry_t *
762 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
766 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
767 return (&pte[pmap_pte_index(va)]);
770 /* Return a pointer to the PT slot that corresponds to a VA */
771 static __inline pt_entry_t *
772 pmap_pte(pmap_t pmap, vm_offset_t va)
777 PG_V = pmap_valid_bit(pmap);
778 pde = pmap_pde(pmap, va);
779 if (pde == NULL || (*pde & PG_V) == 0)
781 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
782 return ((pt_entry_t *)pde);
783 return (pmap_pde_to_pte(pde, va));
787 pmap_resident_count_inc(pmap_t pmap, int count)
790 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
791 pmap->pm_stats.resident_count += count;
795 pmap_resident_count_dec(pmap_t pmap, int count)
798 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
799 KASSERT(pmap->pm_stats.resident_count >= count,
800 ("pmap %p resident count underflow %ld %d", pmap,
801 pmap->pm_stats.resident_count, count));
802 pmap->pm_stats.resident_count -= count;
805 PMAP_INLINE pt_entry_t *
806 vtopte(vm_offset_t va)
808 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
810 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
812 return (PTmap + ((va >> PAGE_SHIFT) & mask));
815 static __inline pd_entry_t *
816 vtopde(vm_offset_t va)
818 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
820 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
822 return (PDmap + ((va >> PDRSHIFT) & mask));
826 allocpages(vm_paddr_t *firstaddr, int n)
831 bzero((void *)ret, n * PAGE_SIZE);
832 *firstaddr += n * PAGE_SIZE;
836 CTASSERT(powerof2(NDMPML4E));
838 /* number of kernel PDP slots */
839 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
842 nkpt_init(vm_paddr_t addr)
849 pt_pages = howmany(addr, 1 << PDRSHIFT);
850 pt_pages += NKPDPE(pt_pages);
853 * Add some slop beyond the bare minimum required for bootstrapping
856 * This is quite important when allocating KVA for kernel modules.
857 * The modules are required to be linked in the negative 2GB of
858 * the address space. If we run out of KVA in this region then
859 * pmap_growkernel() will need to allocate page table pages to map
860 * the entire 512GB of KVA space which is an unnecessary tax on
863 * Secondly, device memory mapped as part of setting up the low-
864 * level console(s) is taken from KVA, starting at virtual_avail.
865 * This is because cninit() is called after pmap_bootstrap() but
866 * before vm_init() and pmap_init(). 20MB for a frame buffer is
869 pt_pages += 32; /* 64MB additional slop. */
875 create_pagetables(vm_paddr_t *firstaddr)
877 int i, j, ndm1g, nkpdpe;
883 /* Allocate page table pages for the direct map */
884 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
885 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
887 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
888 if (ndmpdpphys > NDMPML4E) {
890 * Each NDMPML4E allows 512 GB, so limit to that,
891 * and then readjust ndmpdp and ndmpdpphys.
893 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
894 Maxmem = atop(NDMPML4E * NBPML4);
895 ndmpdpphys = NDMPML4E;
896 ndmpdp = NDMPML4E * NPDEPG;
898 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
900 if ((amd_feature & AMDID_PAGE1GB) != 0)
901 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
903 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
904 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
907 KPML4phys = allocpages(firstaddr, 1);
908 KPDPphys = allocpages(firstaddr, NKPML4E);
911 * Allocate the initial number of kernel page table pages required to
912 * bootstrap. We defer this until after all memory-size dependent
913 * allocations are done (e.g. direct map), so that we don't have to
914 * build in too much slop in our estimate.
916 * Note that when NKPML4E > 1, we have an empty page underneath
917 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
918 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
920 nkpt_init(*firstaddr);
921 nkpdpe = NKPDPE(nkpt);
923 KPTphys = allocpages(firstaddr, nkpt);
924 KPDphys = allocpages(firstaddr, nkpdpe);
926 /* Fill in the underlying page table pages */
927 /* Nominally read-only (but really R/W) from zero to physfree */
928 /* XXX not fully used, underneath 2M pages */
929 pt_p = (pt_entry_t *)KPTphys;
930 for (i = 0; ptoa(i) < *firstaddr; i++)
931 pt_p[i] = ptoa(i) | X86_PG_RW | X86_PG_V | X86_PG_G;
933 /* Now map the page tables at their location within PTmap */
934 pd_p = (pd_entry_t *)KPDphys;
935 for (i = 0; i < nkpt; i++)
936 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
938 /* Map from zero to end of allocations under 2M pages */
939 /* This replaces some of the KPTphys entries above */
940 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
941 pd_p[i] = (i << PDRSHIFT) | X86_PG_RW | X86_PG_V | PG_PS |
944 /* And connect up the PD to the PDP (leaving room for L4 pages) */
945 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
946 for (i = 0; i < nkpdpe; i++)
947 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
951 * Now, set up the direct map region using 2MB and/or 1GB pages. If
952 * the end of physical memory is not aligned to a 1GB page boundary,
953 * then the residual physical memory is mapped with 2MB pages. Later,
954 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
955 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
956 * that are partially used.
958 pd_p = (pd_entry_t *)DMPDphys;
959 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
960 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
961 /* Preset PG_M and PG_A because demotion expects it. */
962 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | X86_PG_G |
965 pdp_p = (pdp_entry_t *)DMPDPphys;
966 for (i = 0; i < ndm1g; i++) {
967 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
968 /* Preset PG_M and PG_A because demotion expects it. */
969 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | X86_PG_G |
972 for (j = 0; i < ndmpdp; i++, j++) {
973 pdp_p[i] = DMPDphys + ptoa(j);
974 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_U;
977 /* And recursively map PML4 to itself in order to get PTmap */
978 p4_p = (pml4_entry_t *)KPML4phys;
979 p4_p[PML4PML4I] = KPML4phys;
980 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | PG_U;
982 /* Connect the Direct Map slot(s) up to the PML4. */
983 for (i = 0; i < ndmpdpphys; i++) {
984 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
985 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | PG_U;
988 /* Connect the KVA slots up to the PML4 */
989 for (i = 0; i < NKPML4E; i++) {
990 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
991 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V | PG_U;
996 * Bootstrap the system enough to run with virtual memory.
998 * On amd64 this is called after mapping has already been enabled
999 * and just syncs the pmap module with what has already been done.
1000 * [We can't call it easily with mapping off since the kernel is not
1001 * mapped with PA == VA, hence we would have to relocate every address
1002 * from the linked base (virtual) address "KERNBASE" to the actual
1003 * (physical) address starting relative to 0]
1006 pmap_bootstrap(vm_paddr_t *firstaddr)
1013 * Create an initial set of page tables to run the kernel in.
1015 create_pagetables(firstaddr);
1018 * Add a physical memory segment (vm_phys_seg) corresponding to the
1019 * preallocated kernel page table pages so that vm_page structures
1020 * representing these pages will be created. The vm_page structures
1021 * are required for promotion of the corresponding kernel virtual
1022 * addresses to superpage mappings.
1024 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1026 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
1027 virtual_avail = pmap_kmem_choose(virtual_avail);
1029 virtual_end = VM_MAX_KERNEL_ADDRESS;
1032 /* XXX do %cr0 as well */
1033 load_cr4(rcr4() | CR4_PGE);
1034 load_cr3(KPML4phys);
1035 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1036 load_cr4(rcr4() | CR4_SMEP);
1039 * Initialize the kernel pmap (which is statically allocated).
1041 PMAP_LOCK_INIT(kernel_pmap);
1042 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1043 kernel_pmap->pm_cr3 = KPML4phys;
1044 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1045 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1046 kernel_pmap->pm_flags = pmap_flags;
1049 * Initialize the TLB invalidations generation number lock.
1051 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1054 * Reserve some special page table entries/VA space for temporary
1057 #define SYSMAP(c, p, v, n) \
1058 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1064 * Crashdump maps. The first page is reused as CMAP1 for the
1067 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1068 CADDR1 = crashdumpmap;
1072 /* Initialize the PAT MSR. */
1075 /* Initialize TLB Context Id. */
1076 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1077 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1078 /* Check for INVPCID support */
1079 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1081 for (i = 0; i < MAXCPU; i++) {
1082 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1083 kernel_pmap->pm_pcids[i].pm_gen = 1;
1085 __pcpu[0].pc_pcid_next = PMAP_PCID_KERN + 1;
1086 __pcpu[0].pc_pcid_gen = 1;
1088 * pcpu area for APs is zeroed during AP startup.
1089 * pc_pcid_next and pc_pcid_gen are initialized by AP
1090 * during pcpu setup.
1092 load_cr4(rcr4() | CR4_PCIDE);
1094 pmap_pcid_enabled = 0;
1099 * Setup the PAT MSR.
1104 int pat_table[PAT_INDEX_SIZE];
1109 /* Bail if this CPU doesn't implement PAT. */
1110 if ((cpu_feature & CPUID_PAT) == 0)
1113 /* Set default PAT index table. */
1114 for (i = 0; i < PAT_INDEX_SIZE; i++)
1116 pat_table[PAT_WRITE_BACK] = 0;
1117 pat_table[PAT_WRITE_THROUGH] = 1;
1118 pat_table[PAT_UNCACHEABLE] = 3;
1119 pat_table[PAT_WRITE_COMBINING] = 3;
1120 pat_table[PAT_WRITE_PROTECTED] = 3;
1121 pat_table[PAT_UNCACHED] = 3;
1123 /* Initialize default PAT entries. */
1124 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1125 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1126 PAT_VALUE(2, PAT_UNCACHED) |
1127 PAT_VALUE(3, PAT_UNCACHEABLE) |
1128 PAT_VALUE(4, PAT_WRITE_BACK) |
1129 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1130 PAT_VALUE(6, PAT_UNCACHED) |
1131 PAT_VALUE(7, PAT_UNCACHEABLE);
1135 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1136 * Program 5 and 6 as WP and WC.
1137 * Leave 4 and 7 as WB and UC.
1139 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1140 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1141 PAT_VALUE(6, PAT_WRITE_COMBINING);
1142 pat_table[PAT_UNCACHED] = 2;
1143 pat_table[PAT_WRITE_PROTECTED] = 5;
1144 pat_table[PAT_WRITE_COMBINING] = 6;
1147 * Just replace PAT Index 2 with WC instead of UC-.
1149 pat_msr &= ~PAT_MASK(2);
1150 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1151 pat_table[PAT_WRITE_COMBINING] = 2;
1156 load_cr4(cr4 & ~CR4_PGE);
1158 /* Disable caches (CD = 1, NW = 0). */
1160 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1162 /* Flushes caches and TLBs. */
1166 /* Update PAT and index table. */
1167 wrmsr(MSR_PAT, pat_msr);
1168 for (i = 0; i < PAT_INDEX_SIZE; i++)
1169 pat_index[i] = pat_table[i];
1171 /* Flush caches and TLBs again. */
1175 /* Restore caches and PGE. */
1181 * Initialize a vm_page's machine-dependent fields.
1184 pmap_page_init(vm_page_t m)
1187 TAILQ_INIT(&m->md.pv_list);
1188 m->md.pat_mode = PAT_WRITE_BACK;
1192 * Initialize the pmap module.
1193 * Called by vm_init, to initialize any structures that the pmap
1194 * system needs to map virtual memory.
1199 struct pmap_preinit_mapping *ppim;
1202 int error, i, pv_npg;
1205 * Initialize the vm page array entries for the kernel pmap's
1208 for (i = 0; i < nkpt; i++) {
1209 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1210 KASSERT(mpte >= vm_page_array &&
1211 mpte < &vm_page_array[vm_page_array_size],
1212 ("pmap_init: page table page is out of range"));
1213 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1214 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1218 * If the kernel is running on a virtual machine, then it must assume
1219 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1220 * be prepared for the hypervisor changing the vendor and family that
1221 * are reported by CPUID. Consequently, the workaround for AMD Family
1222 * 10h Erratum 383 is enabled if the processor's feature set does not
1223 * include at least one feature that is only supported by older Intel
1224 * or newer AMD processors.
1226 if (vm_guest == VM_GUEST_VM && (cpu_feature & CPUID_SS) == 0 &&
1227 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1228 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1230 workaround_erratum383 = 1;
1233 * Are large page mappings enabled?
1235 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1236 if (pg_ps_enabled) {
1237 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1238 ("pmap_init: can't assign to pagesizes[1]"));
1239 pagesizes[1] = NBPDR;
1243 * Initialize the pv chunk list mutex.
1245 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1248 * Initialize the pool of pv list locks.
1250 for (i = 0; i < NPV_LIST_LOCKS; i++)
1251 rw_init(&pv_list_locks[i], "pmap pv list");
1254 * Calculate the size of the pv head table for superpages.
1256 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1259 * Allocate memory for the pv head table for superpages.
1261 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1263 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1265 for (i = 0; i < pv_npg; i++)
1266 TAILQ_INIT(&pv_table[i].pv_list);
1268 pmap_initialized = 1;
1269 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1270 ppim = pmap_preinit_mapping + i;
1273 /* Make the direct map consistent */
1274 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1275 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1276 ppim->sz, ppim->mode);
1280 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1281 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1284 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1285 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1286 (vmem_addr_t *)&qframe);
1288 panic("qframe allocation failed");
1291 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1292 "2MB page mapping counters");
1294 static u_long pmap_pde_demotions;
1295 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1296 &pmap_pde_demotions, 0, "2MB page demotions");
1298 static u_long pmap_pde_mappings;
1299 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1300 &pmap_pde_mappings, 0, "2MB page mappings");
1302 static u_long pmap_pde_p_failures;
1303 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1304 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1306 static u_long pmap_pde_promotions;
1307 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1308 &pmap_pde_promotions, 0, "2MB page promotions");
1310 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1311 "1GB page mapping counters");
1313 static u_long pmap_pdpe_demotions;
1314 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1315 &pmap_pdpe_demotions, 0, "1GB page demotions");
1317 /***************************************************
1318 * Low level helper routines.....
1319 ***************************************************/
1322 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1324 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1326 switch (pmap->pm_type) {
1329 /* Verify that both PAT bits are not set at the same time */
1330 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1331 ("Invalid PAT bits in entry %#lx", entry));
1333 /* Swap the PAT bits if one of them is set */
1334 if ((entry & x86_pat_bits) != 0)
1335 entry ^= x86_pat_bits;
1339 * Nothing to do - the memory attributes are represented
1340 * the same way for regular pages and superpages.
1344 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1351 * Determine the appropriate bits to set in a PTE or PDE for a specified
1355 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1357 int cache_bits, pat_flag, pat_idx;
1359 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1360 panic("Unknown caching mode %d\n", mode);
1362 switch (pmap->pm_type) {
1365 /* The PAT bit is different for PTE's and PDE's. */
1366 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1368 /* Map the caching mode to a PAT index. */
1369 pat_idx = pat_index[mode];
1371 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1374 cache_bits |= pat_flag;
1376 cache_bits |= PG_NC_PCD;
1378 cache_bits |= PG_NC_PWT;
1382 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1386 panic("unsupported pmap type %d", pmap->pm_type);
1389 return (cache_bits);
1393 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1397 switch (pmap->pm_type) {
1400 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1403 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1406 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1412 static __inline boolean_t
1413 pmap_ps_enabled(pmap_t pmap)
1416 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1420 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1423 switch (pmap->pm_type) {
1430 * This is a little bogus since the generation number is
1431 * supposed to be bumped up when a region of the address
1432 * space is invalidated in the page tables.
1434 * In this case the old PDE entry is valid but yet we want
1435 * to make sure that any mappings using the old entry are
1436 * invalidated in the TLB.
1438 * The reason this works as expected is because we rendezvous
1439 * "all" host cpus and force any vcpu context to exit as a
1442 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1445 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1447 pde_store(pde, newpde);
1451 * After changing the page size for the specified virtual address in the page
1452 * table, flush the corresponding entries from the processor's TLB. Only the
1453 * calling processor's TLB is affected.
1455 * The calling thread must be pinned to a processor.
1458 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1462 if (pmap_type_guest(pmap))
1465 KASSERT(pmap->pm_type == PT_X86,
1466 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1468 PG_G = pmap_global_bit(pmap);
1470 if ((newpde & PG_PS) == 0)
1471 /* Demotion: flush a specific 2MB page mapping. */
1473 else if ((newpde & PG_G) == 0)
1475 * Promotion: flush every 4KB page mapping from the TLB
1476 * because there are too many to flush individually.
1481 * Promotion: flush every 4KB page mapping from the TLB,
1482 * including any global (PG_G) mappings.
1490 * For SMP, these functions have to use the IPI mechanism for coherence.
1492 * N.B.: Before calling any of the following TLB invalidation functions,
1493 * the calling processor must ensure that all stores updating a non-
1494 * kernel page table are globally performed. Otherwise, another
1495 * processor could cache an old, pre-update entry without being
1496 * invalidated. This can happen one of two ways: (1) The pmap becomes
1497 * active on another processor after its pm_active field is checked by
1498 * one of the following functions but before a store updating the page
1499 * table is globally performed. (2) The pmap becomes active on another
1500 * processor before its pm_active field is checked but due to
1501 * speculative loads one of the following functions stills reads the
1502 * pmap as inactive on the other processor.
1504 * The kernel page table is exempt because its pm_active field is
1505 * immutable. The kernel page table is always active on every
1510 * Interrupt the cpus that are executing in the guest context.
1511 * This will force the vcpu to exit and the cached EPT mappings
1512 * will be invalidated by the host before the next vmresume.
1514 static __inline void
1515 pmap_invalidate_ept(pmap_t pmap)
1520 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1521 ("pmap_invalidate_ept: absurd pm_active"));
1524 * The TLB mappings associated with a vcpu context are not
1525 * flushed each time a different vcpu is chosen to execute.
1527 * This is in contrast with a process's vtop mappings that
1528 * are flushed from the TLB on each context switch.
1530 * Therefore we need to do more than just a TLB shootdown on
1531 * the active cpus in 'pmap->pm_active'. To do this we keep
1532 * track of the number of invalidations performed on this pmap.
1534 * Each vcpu keeps a cache of this counter and compares it
1535 * just before a vmresume. If the counter is out-of-date an
1536 * invept will be done to flush stale mappings from the TLB.
1538 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1541 * Force the vcpu to exit and trap back into the hypervisor.
1543 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1544 ipi_selected(pmap->pm_active, ipinum);
1549 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1554 if (pmap_type_guest(pmap)) {
1555 pmap_invalidate_ept(pmap);
1559 KASSERT(pmap->pm_type == PT_X86,
1560 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1563 if (pmap == kernel_pmap) {
1567 cpuid = PCPU_GET(cpuid);
1568 if (pmap == PCPU_GET(curpmap))
1570 else if (pmap_pcid_enabled)
1571 pmap->pm_pcids[cpuid].pm_gen = 0;
1572 if (pmap_pcid_enabled) {
1575 pmap->pm_pcids[i].pm_gen = 0;
1578 mask = &pmap->pm_active;
1580 smp_masked_invlpg(*mask, va);
1584 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1585 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1588 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1594 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1595 pmap_invalidate_all(pmap);
1599 if (pmap_type_guest(pmap)) {
1600 pmap_invalidate_ept(pmap);
1604 KASSERT(pmap->pm_type == PT_X86,
1605 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1608 cpuid = PCPU_GET(cpuid);
1609 if (pmap == kernel_pmap) {
1610 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1614 if (pmap == PCPU_GET(curpmap)) {
1615 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1617 } else if (pmap_pcid_enabled) {
1618 pmap->pm_pcids[cpuid].pm_gen = 0;
1620 if (pmap_pcid_enabled) {
1623 pmap->pm_pcids[i].pm_gen = 0;
1626 mask = &pmap->pm_active;
1628 smp_masked_invlpg_range(*mask, sva, eva);
1633 pmap_invalidate_all(pmap_t pmap)
1636 struct invpcid_descr d;
1639 if (pmap_type_guest(pmap)) {
1640 pmap_invalidate_ept(pmap);
1644 KASSERT(pmap->pm_type == PT_X86,
1645 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1648 if (pmap == kernel_pmap) {
1649 if (pmap_pcid_enabled && invpcid_works) {
1650 bzero(&d, sizeof(d));
1651 invpcid(&d, INVPCID_CTXGLOB);
1657 cpuid = PCPU_GET(cpuid);
1658 if (pmap == PCPU_GET(curpmap)) {
1659 if (pmap_pcid_enabled) {
1660 if (invpcid_works) {
1661 d.pcid = pmap->pm_pcids[cpuid].pm_pcid;
1664 invpcid(&d, INVPCID_CTX);
1666 load_cr3(pmap->pm_cr3 | pmap->pm_pcids
1667 [PCPU_GET(cpuid)].pm_pcid);
1672 } else if (pmap_pcid_enabled) {
1673 pmap->pm_pcids[cpuid].pm_gen = 0;
1675 if (pmap_pcid_enabled) {
1678 pmap->pm_pcids[i].pm_gen = 0;
1681 mask = &pmap->pm_active;
1683 smp_masked_invltlb(*mask, pmap);
1688 pmap_invalidate_cache(void)
1698 cpuset_t invalidate; /* processors that invalidate their TLB */
1703 u_int store; /* processor that updates the PDE */
1707 pmap_update_pde_action(void *arg)
1709 struct pde_action *act = arg;
1711 if (act->store == PCPU_GET(cpuid))
1712 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1716 pmap_update_pde_teardown(void *arg)
1718 struct pde_action *act = arg;
1720 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1721 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1725 * Change the page size for the specified virtual address in a way that
1726 * prevents any possibility of the TLB ever having two entries that map the
1727 * same virtual address using different page sizes. This is the recommended
1728 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1729 * machine check exception for a TLB state that is improperly diagnosed as a
1733 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1735 struct pde_action act;
1736 cpuset_t active, other_cpus;
1740 cpuid = PCPU_GET(cpuid);
1741 other_cpus = all_cpus;
1742 CPU_CLR(cpuid, &other_cpus);
1743 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1746 active = pmap->pm_active;
1748 if (CPU_OVERLAP(&active, &other_cpus)) {
1750 act.invalidate = active;
1754 act.newpde = newpde;
1755 CPU_SET(cpuid, &active);
1756 smp_rendezvous_cpus(active,
1757 smp_no_rendevous_barrier, pmap_update_pde_action,
1758 pmap_update_pde_teardown, &act);
1760 pmap_update_pde_store(pmap, pde, newpde);
1761 if (CPU_ISSET(cpuid, &active))
1762 pmap_update_pde_invalidate(pmap, va, newpde);
1768 * Normal, non-SMP, invalidation functions.
1771 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1774 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1778 KASSERT(pmap->pm_type == PT_X86,
1779 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1781 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1783 else if (pmap_pcid_enabled)
1784 pmap->pm_pcids[0].pm_gen = 0;
1788 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1792 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1796 KASSERT(pmap->pm_type == PT_X86,
1797 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1799 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1800 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1802 } else if (pmap_pcid_enabled) {
1803 pmap->pm_pcids[0].pm_gen = 0;
1808 pmap_invalidate_all(pmap_t pmap)
1810 struct invpcid_descr d;
1812 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1816 KASSERT(pmap->pm_type == PT_X86,
1817 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
1819 if (pmap == kernel_pmap) {
1820 if (pmap_pcid_enabled && invpcid_works) {
1821 bzero(&d, sizeof(d));
1822 invpcid(&d, INVPCID_CTXGLOB);
1826 } else if (pmap == PCPU_GET(curpmap)) {
1827 if (pmap_pcid_enabled) {
1828 if (invpcid_works) {
1829 d.pcid = pmap->pm_pcids[0].pm_pcid;
1832 invpcid(&d, INVPCID_CTX);
1834 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[0].
1840 } else if (pmap_pcid_enabled) {
1841 pmap->pm_pcids[0].pm_gen = 0;
1846 pmap_invalidate_cache(void)
1853 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1856 pmap_update_pde_store(pmap, pde, newpde);
1857 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1858 pmap_update_pde_invalidate(pmap, va, newpde);
1860 pmap->pm_pcids[0].pm_gen = 0;
1864 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
1867 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
1871 sva &= ~(vm_offset_t)cpu_clflush_line_size;
1873 KASSERT((sva & PAGE_MASK) == 0,
1874 ("pmap_invalidate_cache_range: sva not page-aligned"));
1875 KASSERT((eva & PAGE_MASK) == 0,
1876 ("pmap_invalidate_cache_range: eva not page-aligned"));
1879 if ((cpu_feature & CPUID_SS) != 0 && !force)
1880 ; /* If "Self Snoop" is supported and allowed, do nothing. */
1881 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
1882 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1884 * XXX: Some CPUs fault, hang, or trash the local APIC
1885 * registers if we use CLFLUSH on the local APIC
1886 * range. The local APIC is always uncached, so we
1887 * don't need to flush for that range anyway.
1889 if (pmap_kextract(sva) == lapic_paddr)
1893 * Otherwise, do per-cache line flush. Use the mfence
1894 * instruction to insure that previous stores are
1895 * included in the write-back. The processor
1896 * propagates flush to other processors in the cache
1900 for (; sva < eva; sva += cpu_clflush_line_size)
1903 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
1904 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1905 if (pmap_kextract(sva) == lapic_paddr)
1908 * Writes are ordered by CLFLUSH on Intel CPUs.
1910 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1912 for (; sva < eva; sva += cpu_clflush_line_size)
1914 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1919 * No targeted cache flush methods are supported by CPU,
1920 * or the supplied range is bigger than 2MB.
1921 * Globally invalidate cache.
1923 pmap_invalidate_cache();
1928 * Remove the specified set of pages from the data and instruction caches.
1930 * In contrast to pmap_invalidate_cache_range(), this function does not
1931 * rely on the CPU's self-snoop feature, because it is intended for use
1932 * when moving pages into a different cache domain.
1935 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1937 vm_offset_t daddr, eva;
1941 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
1942 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1943 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
1944 pmap_invalidate_cache();
1946 if (useclflushopt || cpu_vendor_id != CPU_VENDOR_INTEL)
1948 for (i = 0; i < count; i++) {
1949 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
1950 eva = daddr + PAGE_SIZE;
1951 for (; daddr < eva; daddr += cpu_clflush_line_size) {
1958 if (useclflushopt || cpu_vendor_id != CPU_VENDOR_INTEL)
1964 * Routine: pmap_extract
1966 * Extract the physical page address associated
1967 * with the given map/virtual_address pair.
1970 pmap_extract(pmap_t pmap, vm_offset_t va)
1974 pt_entry_t *pte, PG_V;
1978 PG_V = pmap_valid_bit(pmap);
1980 pdpe = pmap_pdpe(pmap, va);
1981 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
1982 if ((*pdpe & PG_PS) != 0)
1983 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
1985 pde = pmap_pdpe_to_pde(pdpe, va);
1986 if ((*pde & PG_V) != 0) {
1987 if ((*pde & PG_PS) != 0) {
1988 pa = (*pde & PG_PS_FRAME) |
1991 pte = pmap_pde_to_pte(pde, va);
1992 pa = (*pte & PG_FRAME) |
2003 * Routine: pmap_extract_and_hold
2005 * Atomically extract and hold the physical page
2006 * with the given pmap and virtual address pair
2007 * if that mapping permits the given protection.
2010 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
2012 pd_entry_t pde, *pdep;
2013 pt_entry_t pte, PG_RW, PG_V;
2019 PG_RW = pmap_rw_bit(pmap);
2020 PG_V = pmap_valid_bit(pmap);
2023 pdep = pmap_pde(pmap, va);
2024 if (pdep != NULL && (pde = *pdep)) {
2026 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2027 if (vm_page_pa_tryrelock(pmap, (pde &
2028 PG_PS_FRAME) | (va & PDRMASK), &pa))
2030 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
2035 pte = *pmap_pde_to_pte(pdep, va);
2037 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2038 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2041 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
2052 pmap_kextract(vm_offset_t va)
2057 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2058 pa = DMAP_TO_PHYS(va);
2062 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2065 * Beware of a concurrent promotion that changes the
2066 * PDE at this point! For example, vtopte() must not
2067 * be used to access the PTE because it would use the
2068 * new PDE. It is, however, safe to use the old PDE
2069 * because the page table page is preserved by the
2072 pa = *pmap_pde_to_pte(&pde, va);
2073 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2079 /***************************************************
2080 * Low level mapping routines.....
2081 ***************************************************/
2084 * Add a wired page to the kva.
2085 * Note: not SMP coherent.
2088 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2093 pte_store(pte, pa | X86_PG_RW | X86_PG_V | X86_PG_G);
2096 static __inline void
2097 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2103 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2104 pte_store(pte, pa | X86_PG_RW | X86_PG_V | X86_PG_G | cache_bits);
2108 * Remove a page from the kernel pagetables.
2109 * Note: not SMP coherent.
2112 pmap_kremove(vm_offset_t va)
2121 * Used to map a range of physical addresses into kernel
2122 * virtual address space.
2124 * The value passed in '*virt' is a suggested virtual address for
2125 * the mapping. Architectures which can support a direct-mapped
2126 * physical to virtual region can return the appropriate address
2127 * within that region, leaving '*virt' unchanged. Other
2128 * architectures should map the pages starting at '*virt' and
2129 * update '*virt' with the first usable address after the mapped
2133 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2135 return PHYS_TO_DMAP(start);
2140 * Add a list of wired pages to the kva
2141 * this routine is only used for temporary
2142 * kernel mappings that do not need to have
2143 * page modification or references recorded.
2144 * Note that old mappings are simply written
2145 * over. The page *must* be wired.
2146 * Note: SMP coherent. Uses a ranged shootdown IPI.
2149 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2151 pt_entry_t *endpte, oldpte, pa, *pte;
2157 endpte = pte + count;
2158 while (pte < endpte) {
2160 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2161 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2162 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2164 pte_store(pte, pa | X86_PG_G | X86_PG_RW | X86_PG_V);
2168 if (__predict_false((oldpte & X86_PG_V) != 0))
2169 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2174 * This routine tears out page mappings from the
2175 * kernel -- it is meant only for temporary mappings.
2176 * Note: SMP coherent. Uses a ranged shootdown IPI.
2179 pmap_qremove(vm_offset_t sva, int count)
2184 while (count-- > 0) {
2185 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2189 pmap_invalidate_range(kernel_pmap, sva, va);
2192 /***************************************************
2193 * Page table page management routines.....
2194 ***************************************************/
2195 static __inline void
2196 pmap_free_zero_pages(struct spglist *free)
2200 while ((m = SLIST_FIRST(free)) != NULL) {
2201 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2202 /* Preserve the page's PG_ZERO setting. */
2203 vm_page_free_toq(m);
2208 * Schedule the specified unused page table page to be freed. Specifically,
2209 * add the page to the specified list of pages that will be released to the
2210 * physical memory manager after the TLB has been updated.
2212 static __inline void
2213 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2214 boolean_t set_PG_ZERO)
2218 m->flags |= PG_ZERO;
2220 m->flags &= ~PG_ZERO;
2221 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2225 * Inserts the specified page table page into the specified pmap's collection
2226 * of idle page table pages. Each of a pmap's page table pages is responsible
2227 * for mapping a distinct range of virtual addresses. The pmap's collection is
2228 * ordered by this virtual address range.
2231 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2234 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2235 return (vm_radix_insert(&pmap->pm_root, mpte));
2239 * Looks for a page table page mapping the specified virtual address in the
2240 * specified pmap's collection of idle page table pages. Returns NULL if there
2241 * is no page table page corresponding to the specified virtual address.
2243 static __inline vm_page_t
2244 pmap_lookup_pt_page(pmap_t pmap, vm_offset_t va)
2247 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2248 return (vm_radix_lookup(&pmap->pm_root, pmap_pde_pindex(va)));
2252 * Removes the specified page table page from the specified pmap's collection
2253 * of idle page table pages. The specified page table page must be a member of
2254 * the pmap's collection.
2256 static __inline void
2257 pmap_remove_pt_page(pmap_t pmap, vm_page_t mpte)
2260 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2261 vm_radix_remove(&pmap->pm_root, mpte->pindex);
2265 * Decrements a page table page's wire count, which is used to record the
2266 * number of valid page table entries within the page. If the wire count
2267 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2268 * page table page was unmapped and FALSE otherwise.
2270 static inline boolean_t
2271 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2275 if (m->wire_count == 0) {
2276 _pmap_unwire_ptp(pmap, va, m, free);
2283 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2286 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2288 * unmap the page table page
2290 if (m->pindex >= (NUPDE + NUPDPE)) {
2293 pml4 = pmap_pml4e(pmap, va);
2295 } else if (m->pindex >= NUPDE) {
2298 pdp = pmap_pdpe(pmap, va);
2303 pd = pmap_pde(pmap, va);
2306 pmap_resident_count_dec(pmap, 1);
2307 if (m->pindex < NUPDE) {
2308 /* We just released a PT, unhold the matching PD */
2311 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2312 pmap_unwire_ptp(pmap, va, pdpg, free);
2314 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2315 /* We just released a PD, unhold the matching PDP */
2318 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2319 pmap_unwire_ptp(pmap, va, pdppg, free);
2323 * This is a release store so that the ordinary store unmapping
2324 * the page table page is globally performed before TLB shoot-
2327 atomic_subtract_rel_int(&vm_cnt.v_wire_count, 1);
2330 * Put page on a list so that it is released after
2331 * *ALL* TLB shootdown is done
2333 pmap_add_delayed_free_list(m, free, TRUE);
2337 * After removing a page table entry, this routine is used to
2338 * conditionally free the page, and manage the hold/wire counts.
2341 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2342 struct spglist *free)
2346 if (va >= VM_MAXUSER_ADDRESS)
2348 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2349 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2350 return (pmap_unwire_ptp(pmap, va, mpte, free));
2354 pmap_pinit0(pmap_t pmap)
2358 PMAP_LOCK_INIT(pmap);
2359 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2360 pmap->pm_cr3 = KPML4phys;
2361 pmap->pm_root.rt_root = 0;
2362 CPU_ZERO(&pmap->pm_active);
2363 TAILQ_INIT(&pmap->pm_pvchunk);
2364 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2365 pmap->pm_flags = pmap_flags;
2367 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2368 pmap->pm_pcids[i].pm_gen = 0;
2370 PCPU_SET(curpmap, kernel_pmap);
2371 pmap_activate(curthread);
2372 CPU_FILL(&kernel_pmap->pm_active);
2376 * Initialize a preallocated and zeroed pmap structure,
2377 * such as one in a vmspace structure.
2380 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2383 vm_paddr_t pml4phys;
2387 * allocate the page directory page
2389 while ((pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2390 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL)
2393 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2394 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2396 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2397 pmap->pm_pcids[i].pm_gen = 0;
2399 pmap->pm_cr3 = ~0; /* initialize to an invalid value */
2401 if ((pml4pg->flags & PG_ZERO) == 0)
2402 pagezero(pmap->pm_pml4);
2405 * Do not install the host kernel mappings in the nested page
2406 * tables. These mappings are meaningless in the guest physical
2409 if ((pmap->pm_type = pm_type) == PT_X86) {
2410 pmap->pm_cr3 = pml4phys;
2412 /* Wire in kernel global address entries. */
2413 for (i = 0; i < NKPML4E; i++) {
2414 pmap->pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) |
2415 X86_PG_RW | X86_PG_V | PG_U;
2417 for (i = 0; i < ndmpdpphys; i++) {
2418 pmap->pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) |
2419 X86_PG_RW | X86_PG_V | PG_U;
2422 /* install self-referential address mapping entry(s) */
2423 pmap->pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) |
2424 X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
2427 pmap->pm_root.rt_root = 0;
2428 CPU_ZERO(&pmap->pm_active);
2429 TAILQ_INIT(&pmap->pm_pvchunk);
2430 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2431 pmap->pm_flags = flags;
2432 pmap->pm_eptgen = 0;
2438 pmap_pinit(pmap_t pmap)
2441 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2445 * This routine is called if the desired page table page does not exist.
2447 * If page table page allocation fails, this routine may sleep before
2448 * returning NULL. It sleeps only if a lock pointer was given.
2450 * Note: If a page allocation fails at page table level two or three,
2451 * one or two pages may be held during the wait, only to be released
2452 * afterwards. This conservative approach is easily argued to avoid
2456 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2458 vm_page_t m, pdppg, pdpg;
2459 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2461 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2463 PG_A = pmap_accessed_bit(pmap);
2464 PG_M = pmap_modified_bit(pmap);
2465 PG_V = pmap_valid_bit(pmap);
2466 PG_RW = pmap_rw_bit(pmap);
2469 * Allocate a page table page.
2471 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2472 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2473 if (lockp != NULL) {
2474 RELEASE_PV_LIST_LOCK(lockp);
2476 PMAP_ASSERT_NOT_IN_DI();
2482 * Indicate the need to retry. While waiting, the page table
2483 * page may have been allocated.
2487 if ((m->flags & PG_ZERO) == 0)
2491 * Map the pagetable page into the process address space, if
2492 * it isn't already there.
2495 if (ptepindex >= (NUPDE + NUPDPE)) {
2497 vm_pindex_t pml4index;
2499 /* Wire up a new PDPE page */
2500 pml4index = ptepindex - (NUPDE + NUPDPE);
2501 pml4 = &pmap->pm_pml4[pml4index];
2502 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2504 } else if (ptepindex >= NUPDE) {
2505 vm_pindex_t pml4index;
2506 vm_pindex_t pdpindex;
2510 /* Wire up a new PDE page */
2511 pdpindex = ptepindex - NUPDE;
2512 pml4index = pdpindex >> NPML4EPGSHIFT;
2514 pml4 = &pmap->pm_pml4[pml4index];
2515 if ((*pml4 & PG_V) == 0) {
2516 /* Have to allocate a new pdp, recurse */
2517 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2520 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2521 vm_page_free_zero(m);
2525 /* Add reference to pdp page */
2526 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2527 pdppg->wire_count++;
2529 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2531 /* Now find the pdp page */
2532 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2533 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2536 vm_pindex_t pml4index;
2537 vm_pindex_t pdpindex;
2542 /* Wire up a new PTE page */
2543 pdpindex = ptepindex >> NPDPEPGSHIFT;
2544 pml4index = pdpindex >> NPML4EPGSHIFT;
2546 /* First, find the pdp and check that its valid. */
2547 pml4 = &pmap->pm_pml4[pml4index];
2548 if ((*pml4 & PG_V) == 0) {
2549 /* Have to allocate a new pd, recurse */
2550 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2553 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2554 vm_page_free_zero(m);
2557 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2558 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2560 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2561 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2562 if ((*pdp & PG_V) == 0) {
2563 /* Have to allocate a new pd, recurse */
2564 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2567 atomic_subtract_int(&vm_cnt.v_wire_count,
2569 vm_page_free_zero(m);
2573 /* Add reference to the pd page */
2574 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2578 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2580 /* Now we know where the page directory page is */
2581 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2582 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2585 pmap_resident_count_inc(pmap, 1);
2591 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2593 vm_pindex_t pdpindex, ptepindex;
2594 pdp_entry_t *pdpe, PG_V;
2597 PG_V = pmap_valid_bit(pmap);
2600 pdpe = pmap_pdpe(pmap, va);
2601 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2602 /* Add a reference to the pd page. */
2603 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2606 /* Allocate a pd page. */
2607 ptepindex = pmap_pde_pindex(va);
2608 pdpindex = ptepindex >> NPDPEPGSHIFT;
2609 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2610 if (pdpg == NULL && lockp != NULL)
2617 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2619 vm_pindex_t ptepindex;
2620 pd_entry_t *pd, PG_V;
2623 PG_V = pmap_valid_bit(pmap);
2626 * Calculate pagetable page index
2628 ptepindex = pmap_pde_pindex(va);
2631 * Get the page directory entry
2633 pd = pmap_pde(pmap, va);
2636 * This supports switching from a 2MB page to a
2639 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2640 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2642 * Invalidation of the 2MB page mapping may have caused
2643 * the deallocation of the underlying PD page.
2650 * If the page table page is mapped, we just increment the
2651 * hold count, and activate it.
2653 if (pd != NULL && (*pd & PG_V) != 0) {
2654 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2658 * Here if the pte page isn't mapped, or if it has been
2661 m = _pmap_allocpte(pmap, ptepindex, lockp);
2662 if (m == NULL && lockp != NULL)
2669 /***************************************************
2670 * Pmap allocation/deallocation routines.
2671 ***************************************************/
2674 * Release any resources held by the given physical map.
2675 * Called when a pmap initialized by pmap_pinit is being released.
2676 * Should only be called if the map contains no valid mappings.
2679 pmap_release(pmap_t pmap)
2684 KASSERT(pmap->pm_stats.resident_count == 0,
2685 ("pmap_release: pmap resident count %ld != 0",
2686 pmap->pm_stats.resident_count));
2687 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2688 ("pmap_release: pmap has reserved page table page(s)"));
2689 KASSERT(CPU_EMPTY(&pmap->pm_active),
2690 ("releasing active pmap %p", pmap));
2692 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2694 for (i = 0; i < NKPML4E; i++) /* KVA */
2695 pmap->pm_pml4[KPML4BASE + i] = 0;
2696 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
2697 pmap->pm_pml4[DMPML4I + i] = 0;
2698 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
2701 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2702 vm_page_free_zero(m);
2706 kvm_size(SYSCTL_HANDLER_ARGS)
2708 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2710 return sysctl_handle_long(oidp, &ksize, 0, req);
2712 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2713 0, 0, kvm_size, "LU", "Size of KVM");
2716 kvm_free(SYSCTL_HANDLER_ARGS)
2718 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2720 return sysctl_handle_long(oidp, &kfree, 0, req);
2722 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2723 0, 0, kvm_free, "LU", "Amount of KVM free");
2726 * grow the number of kernel page table entries, if needed
2729 pmap_growkernel(vm_offset_t addr)
2733 pd_entry_t *pde, newpdir;
2736 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2739 * Return if "addr" is within the range of kernel page table pages
2740 * that were preallocated during pmap bootstrap. Moreover, leave
2741 * "kernel_vm_end" and the kernel page table as they were.
2743 * The correctness of this action is based on the following
2744 * argument: vm_map_insert() allocates contiguous ranges of the
2745 * kernel virtual address space. It calls this function if a range
2746 * ends after "kernel_vm_end". If the kernel is mapped between
2747 * "kernel_vm_end" and "addr", then the range cannot begin at
2748 * "kernel_vm_end". In fact, its beginning address cannot be less
2749 * than the kernel. Thus, there is no immediate need to allocate
2750 * any new kernel page table pages between "kernel_vm_end" and
2753 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
2756 addr = roundup2(addr, NBPDR);
2757 if (addr - 1 >= kernel_map->max_offset)
2758 addr = kernel_map->max_offset;
2759 while (kernel_vm_end < addr) {
2760 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
2761 if ((*pdpe & X86_PG_V) == 0) {
2762 /* We need a new PDP entry */
2763 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
2764 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
2765 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2767 panic("pmap_growkernel: no memory to grow kernel");
2768 if ((nkpg->flags & PG_ZERO) == 0)
2769 pmap_zero_page(nkpg);
2770 paddr = VM_PAGE_TO_PHYS(nkpg);
2771 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
2772 X86_PG_A | X86_PG_M);
2773 continue; /* try again */
2775 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
2776 if ((*pde & X86_PG_V) != 0) {
2777 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2778 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2779 kernel_vm_end = kernel_map->max_offset;
2785 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
2786 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
2789 panic("pmap_growkernel: no memory to grow kernel");
2790 if ((nkpg->flags & PG_ZERO) == 0)
2791 pmap_zero_page(nkpg);
2792 paddr = VM_PAGE_TO_PHYS(nkpg);
2793 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
2794 pde_store(pde, newpdir);
2796 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2797 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2798 kernel_vm_end = kernel_map->max_offset;
2805 /***************************************************
2806 * page management routines.
2807 ***************************************************/
2809 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
2810 CTASSERT(_NPCM == 3);
2811 CTASSERT(_NPCPV == 168);
2813 static __inline struct pv_chunk *
2814 pv_to_chunk(pv_entry_t pv)
2817 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
2820 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
2822 #define PC_FREE0 0xfffffffffffffffful
2823 #define PC_FREE1 0xfffffffffffffffful
2824 #define PC_FREE2 0x000000fffffffffful
2826 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
2829 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2831 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2832 "Current number of pv entry chunks");
2833 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2834 "Current number of pv entry chunks allocated");
2835 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2836 "Current number of pv entry chunks frees");
2837 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
2838 "Number of times tried to get a chunk page but failed.");
2840 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
2841 static int pv_entry_spare;
2843 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2844 "Current number of pv entry frees");
2845 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
2846 "Current number of pv entry allocs");
2847 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2848 "Current number of pv entries");
2849 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2850 "Current number of spare pv entries");
2854 * We are in a serious low memory condition. Resort to
2855 * drastic measures to free some pages so we can allocate
2856 * another pv entry chunk.
2858 * Returns NULL if PV entries were reclaimed from the specified pmap.
2860 * We do not, however, unmap 2mpages because subsequent accesses will
2861 * allocate per-page pv entries until repromotion occurs, thereby
2862 * exacerbating the shortage of free pv entries.
2865 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
2867 struct pch new_tail;
2868 struct pv_chunk *pc;
2869 struct md_page *pvh;
2872 pt_entry_t *pte, tpte;
2873 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
2877 struct spglist free;
2879 int bit, field, freed;
2881 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2882 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
2885 PG_G = PG_A = PG_M = PG_RW = 0;
2887 TAILQ_INIT(&new_tail);
2888 pmap_delayed_invl_started();
2889 mtx_lock(&pv_chunks_mutex);
2890 while ((pc = TAILQ_FIRST(&pv_chunks)) != NULL && SLIST_EMPTY(&free)) {
2891 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2892 mtx_unlock(&pv_chunks_mutex);
2893 if (pmap != pc->pc_pmap) {
2895 pmap_invalidate_all(pmap);
2896 if (pmap != locked_pmap)
2899 pmap_delayed_invl_finished();
2900 pmap_delayed_invl_started();
2902 /* Avoid deadlock and lock recursion. */
2903 if (pmap > locked_pmap) {
2904 RELEASE_PV_LIST_LOCK(lockp);
2906 } else if (pmap != locked_pmap &&
2907 !PMAP_TRYLOCK(pmap)) {
2909 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2910 mtx_lock(&pv_chunks_mutex);
2913 PG_G = pmap_global_bit(pmap);
2914 PG_A = pmap_accessed_bit(pmap);
2915 PG_M = pmap_modified_bit(pmap);
2916 PG_RW = pmap_rw_bit(pmap);
2920 * Destroy every non-wired, 4 KB page mapping in the chunk.
2923 for (field = 0; field < _NPCM; field++) {
2924 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2925 inuse != 0; inuse &= ~(1UL << bit)) {
2927 pv = &pc->pc_pventry[field * 64 + bit];
2929 pde = pmap_pde(pmap, va);
2930 if ((*pde & PG_PS) != 0)
2932 pte = pmap_pde_to_pte(pde, va);
2933 if ((*pte & PG_W) != 0)
2935 tpte = pte_load_clear(pte);
2936 if ((tpte & PG_G) != 0)
2937 pmap_invalidate_page(pmap, va);
2938 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
2939 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
2941 if ((tpte & PG_A) != 0)
2942 vm_page_aflag_set(m, PGA_REFERENCED);
2943 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
2944 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
2946 if (TAILQ_EMPTY(&m->md.pv_list) &&
2947 (m->flags & PG_FICTITIOUS) == 0) {
2948 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
2949 if (TAILQ_EMPTY(&pvh->pv_list)) {
2950 vm_page_aflag_clear(m,
2954 pmap_delayed_invl_page(m);
2955 pc->pc_map[field] |= 1UL << bit;
2956 pmap_unuse_pt(pmap, va, *pde, &free);
2961 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2962 mtx_lock(&pv_chunks_mutex);
2965 /* Every freed mapping is for a 4 KB page. */
2966 pmap_resident_count_dec(pmap, freed);
2967 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
2968 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
2969 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
2970 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2971 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
2972 pc->pc_map[2] == PC_FREE2) {
2973 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
2974 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
2975 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
2976 /* Entire chunk is free; return it. */
2977 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
2978 dump_drop_page(m_pc->phys_addr);
2979 mtx_lock(&pv_chunks_mutex);
2982 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2983 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2984 mtx_lock(&pv_chunks_mutex);
2985 /* One freed pv entry in locked_pmap is sufficient. */
2986 if (pmap == locked_pmap)
2989 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
2990 mtx_unlock(&pv_chunks_mutex);
2992 pmap_invalidate_all(pmap);
2993 if (pmap != locked_pmap)
2996 pmap_delayed_invl_finished();
2997 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
2998 m_pc = SLIST_FIRST(&free);
2999 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3000 /* Recycle a freed page table page. */
3001 m_pc->wire_count = 1;
3002 atomic_add_int(&vm_cnt.v_wire_count, 1);
3004 pmap_free_zero_pages(&free);
3009 * free the pv_entry back to the free list
3012 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3014 struct pv_chunk *pc;
3015 int idx, field, bit;
3017 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3018 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3019 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3020 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3021 pc = pv_to_chunk(pv);
3022 idx = pv - &pc->pc_pventry[0];
3025 pc->pc_map[field] |= 1ul << bit;
3026 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3027 pc->pc_map[2] != PC_FREE2) {
3028 /* 98% of the time, pc is already at the head of the list. */
3029 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3030 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3031 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3035 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3040 free_pv_chunk(struct pv_chunk *pc)
3044 mtx_lock(&pv_chunks_mutex);
3045 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3046 mtx_unlock(&pv_chunks_mutex);
3047 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3048 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3049 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3050 /* entire chunk is free, return it */
3051 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3052 dump_drop_page(m->phys_addr);
3053 vm_page_unwire(m, PQ_NONE);
3058 * Returns a new PV entry, allocating a new PV chunk from the system when
3059 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3060 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3063 * The given PV list lock may be released.
3066 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3070 struct pv_chunk *pc;
3073 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3074 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3076 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3078 for (field = 0; field < _NPCM; field++) {
3079 if (pc->pc_map[field]) {
3080 bit = bsfq(pc->pc_map[field]);
3084 if (field < _NPCM) {
3085 pv = &pc->pc_pventry[field * 64 + bit];
3086 pc->pc_map[field] &= ~(1ul << bit);
3087 /* If this was the last item, move it to tail */
3088 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3089 pc->pc_map[2] == 0) {
3090 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3091 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3094 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3095 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3099 /* No free items, allocate another chunk */
3100 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3103 if (lockp == NULL) {
3104 PV_STAT(pc_chunk_tryfail++);
3107 m = reclaim_pv_chunk(pmap, lockp);
3111 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3112 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3113 dump_add_page(m->phys_addr);
3114 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3116 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3117 pc->pc_map[1] = PC_FREE1;
3118 pc->pc_map[2] = PC_FREE2;
3119 mtx_lock(&pv_chunks_mutex);
3120 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3121 mtx_unlock(&pv_chunks_mutex);
3122 pv = &pc->pc_pventry[0];
3123 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3124 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3125 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3130 * Returns the number of one bits within the given PV chunk map.
3132 * The erratas for Intel processors state that "POPCNT Instruction May
3133 * Take Longer to Execute Than Expected". It is believed that the
3134 * issue is the spurious dependency on the destination register.
3135 * Provide a hint to the register rename logic that the destination
3136 * value is overwritten, by clearing it, as suggested in the
3137 * optimization manual. It should be cheap for unaffected processors
3140 * Reference numbers for erratas are
3141 * 4th Gen Core: HSD146
3142 * 5th Gen Core: BDM85
3143 * 6th Gen Core: SKL029
3146 popcnt_pc_map_pq(uint64_t *map)
3150 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3151 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3152 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3153 : "=&r" (result), "=&r" (tmp)
3154 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3159 * Ensure that the number of spare PV entries in the specified pmap meets or
3160 * exceeds the given count, "needed".
3162 * The given PV list lock may be released.
3165 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3167 struct pch new_tail;
3168 struct pv_chunk *pc;
3172 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3173 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3176 * Newly allocated PV chunks must be stored in a private list until
3177 * the required number of PV chunks have been allocated. Otherwise,
3178 * reclaim_pv_chunk() could recycle one of these chunks. In
3179 * contrast, these chunks must be added to the pmap upon allocation.
3181 TAILQ_INIT(&new_tail);
3184 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3186 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3187 bit_count((bitstr_t *)pc->pc_map, 0,
3188 sizeof(pc->pc_map) * NBBY, &free);
3191 free = popcnt_pc_map_pq(pc->pc_map);
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)
6065 * A/D bit emulation requires an alternate code path when clearing
6066 * the modified and accessed bits below. Since this function is
6067 * advisory in nature we skip it entirely for pmaps that require
6068 * A/D bit emulation.
6070 if (pmap_emulate_ad_bits(pmap))
6073 PG_A = pmap_accessed_bit(pmap);
6074 PG_G = pmap_global_bit(pmap);
6075 PG_M = pmap_modified_bit(pmap);
6076 PG_V = pmap_valid_bit(pmap);
6077 PG_RW = pmap_rw_bit(pmap);
6079 pmap_delayed_invl_started();
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");