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;
389 static struct md_page pv_dummy;
392 * All those kernel PT submaps that BSD is so fond of
394 pt_entry_t *CMAP1 = 0;
396 static vm_offset_t qframe = 0;
397 static struct mtx qframe_mtx;
399 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
401 int pmap_pcid_enabled = 1;
402 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
403 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
404 int invpcid_works = 0;
405 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
406 "Is the invpcid instruction available ?");
409 pmap_pcid_save_cnt_proc(SYSCTL_HANDLER_ARGS)
416 res += cpuid_to_pcpu[i]->pc_pm_save_cnt;
418 return (sysctl_handle_64(oidp, &res, 0, req));
420 SYSCTL_PROC(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLTYPE_U64 | CTLFLAG_RW |
421 CTLFLAG_MPSAFE, NULL, 0, pmap_pcid_save_cnt_proc, "QU",
422 "Count of saved TLB context on switch");
424 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
425 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
426 static struct mtx invl_gen_mtx;
427 static u_long pmap_invl_gen = 0;
428 /* Fake lock object to satisfy turnstiles interface. */
429 static struct lock_object invl_gen_ts = {
433 #define PMAP_ASSERT_NOT_IN_DI() \
434 KASSERT(curthread->td_md.md_invl_gen.gen == 0, ("DI already started"))
437 * Start a new Delayed Invalidation (DI) block of code, executed by
438 * the current thread. Within a DI block, the current thread may
439 * destroy both the page table and PV list entries for a mapping and
440 * then release the corresponding PV list lock before ensuring that
441 * the mapping is flushed from the TLBs of any processors with the
445 pmap_delayed_invl_started(void)
447 struct pmap_invl_gen *invl_gen;
450 invl_gen = &curthread->td_md.md_invl_gen;
451 PMAP_ASSERT_NOT_IN_DI();
452 mtx_lock(&invl_gen_mtx);
453 if (LIST_EMPTY(&pmap_invl_gen_tracker))
454 currgen = pmap_invl_gen;
456 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
457 invl_gen->gen = currgen + 1;
458 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
459 mtx_unlock(&invl_gen_mtx);
463 * Finish the DI block, previously started by the current thread. All
464 * required TLB flushes for the pages marked by
465 * pmap_delayed_invl_page() must be finished before this function is
468 * This function works by bumping the global DI generation number to
469 * the generation number of the current thread's DI, unless there is a
470 * pending DI that started earlier. In the latter case, bumping the
471 * global DI generation number would incorrectly signal that the
472 * earlier DI had finished. Instead, this function bumps the earlier
473 * DI's generation number to match the generation number of the
474 * current thread's DI.
477 pmap_delayed_invl_finished(void)
479 struct pmap_invl_gen *invl_gen, *next;
480 struct turnstile *ts;
482 invl_gen = &curthread->td_md.md_invl_gen;
483 KASSERT(invl_gen->gen != 0, ("missed invl_started"));
484 mtx_lock(&invl_gen_mtx);
485 next = LIST_NEXT(invl_gen, link);
487 turnstile_chain_lock(&invl_gen_ts);
488 ts = turnstile_lookup(&invl_gen_ts);
489 pmap_invl_gen = invl_gen->gen;
491 turnstile_broadcast(ts, TS_SHARED_QUEUE);
492 turnstile_unpend(ts, TS_SHARED_LOCK);
494 turnstile_chain_unlock(&invl_gen_ts);
496 next->gen = invl_gen->gen;
498 LIST_REMOVE(invl_gen, link);
499 mtx_unlock(&invl_gen_mtx);
504 static long invl_wait;
505 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
506 "Number of times DI invalidation blocked pmap_remove_all/write");
510 pmap_delayed_invl_genp(vm_page_t m)
513 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
517 * Ensure that all currently executing DI blocks, that need to flush
518 * TLB for the given page m, actually flushed the TLB at the time the
519 * function returned. If the page m has an empty PV list and we call
520 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
521 * valid mapping for the page m in either its page table or TLB.
523 * This function works by blocking until the global DI generation
524 * number catches up with the generation number associated with the
525 * given page m and its PV list. Since this function's callers
526 * typically own an object lock and sometimes own a page lock, it
527 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
531 pmap_delayed_invl_wait(vm_page_t m)
534 struct turnstile *ts;
537 bool accounted = false;
541 m_gen = pmap_delayed_invl_genp(m);
542 while (*m_gen > pmap_invl_gen) {
545 atomic_add_long(&invl_wait, 1);
549 ts = turnstile_trywait(&invl_gen_ts);
550 if (*m_gen > pmap_invl_gen)
551 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
553 turnstile_cancel(ts);
558 * Mark the page m's PV list as participating in the current thread's
559 * DI block. Any threads concurrently using m's PV list to remove or
560 * restrict all mappings to m will wait for the current thread's DI
561 * block to complete before proceeding.
563 * The function works by setting the DI generation number for m's PV
564 * list to at least the DI generation number of the current thread.
565 * This forces a caller of pmap_delayed_invl_wait() to block until
566 * current thread calls pmap_delayed_invl_finished().
569 pmap_delayed_invl_page(vm_page_t m)
573 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
574 gen = curthread->td_md.md_invl_gen.gen;
577 m_gen = pmap_delayed_invl_genp(m);
585 static caddr_t crashdumpmap;
587 static void free_pv_chunk(struct pv_chunk *pc);
588 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
589 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
590 static int popcnt_pc_map_pq(uint64_t *map);
591 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
592 static void reserve_pv_entries(pmap_t pmap, int needed,
593 struct rwlock **lockp);
594 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
595 struct rwlock **lockp);
596 static boolean_t pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
597 struct rwlock **lockp);
598 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
599 struct rwlock **lockp);
600 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
601 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
604 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode);
605 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
606 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
607 vm_offset_t va, struct rwlock **lockp);
608 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
610 static boolean_t pmap_enter_pde(pmap_t pmap, vm_offset_t va, vm_page_t m,
611 vm_prot_t prot, struct rwlock **lockp);
612 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
613 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
614 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
615 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
616 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
617 static vm_page_t pmap_lookup_pt_page(pmap_t pmap, vm_offset_t va);
618 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask);
619 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
620 struct rwlock **lockp);
621 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
623 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
624 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
625 struct spglist *free, struct rwlock **lockp);
626 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
627 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
628 static void pmap_remove_pt_page(pmap_t pmap, vm_page_t mpte);
629 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
630 struct spglist *free);
631 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
632 vm_page_t m, struct rwlock **lockp);
633 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
635 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
637 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
638 struct rwlock **lockp);
639 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
640 struct rwlock **lockp);
641 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
642 struct rwlock **lockp);
644 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
645 struct spglist *free);
646 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
647 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
650 * Move the kernel virtual free pointer to the next
651 * 2MB. This is used to help improve performance
652 * by using a large (2MB) page for much of the kernel
653 * (.text, .data, .bss)
656 pmap_kmem_choose(vm_offset_t addr)
658 vm_offset_t newaddr = addr;
660 newaddr = roundup2(addr, NBPDR);
664 /********************/
665 /* Inline functions */
666 /********************/
668 /* Return a non-clipped PD index for a given VA */
669 static __inline vm_pindex_t
670 pmap_pde_pindex(vm_offset_t va)
672 return (va >> PDRSHIFT);
676 /* Return a pointer to the PML4 slot that corresponds to a VA */
677 static __inline pml4_entry_t *
678 pmap_pml4e(pmap_t pmap, vm_offset_t va)
681 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
684 /* Return a pointer to the PDP slot that corresponds to a VA */
685 static __inline pdp_entry_t *
686 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
690 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
691 return (&pdpe[pmap_pdpe_index(va)]);
694 /* Return a pointer to the PDP slot that corresponds to a VA */
695 static __inline pdp_entry_t *
696 pmap_pdpe(pmap_t pmap, vm_offset_t va)
701 PG_V = pmap_valid_bit(pmap);
702 pml4e = pmap_pml4e(pmap, va);
703 if ((*pml4e & PG_V) == 0)
705 return (pmap_pml4e_to_pdpe(pml4e, va));
708 /* Return a pointer to the PD slot that corresponds to a VA */
709 static __inline pd_entry_t *
710 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
714 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
715 return (&pde[pmap_pde_index(va)]);
718 /* Return a pointer to the PD slot that corresponds to a VA */
719 static __inline pd_entry_t *
720 pmap_pde(pmap_t pmap, vm_offset_t va)
725 PG_V = pmap_valid_bit(pmap);
726 pdpe = pmap_pdpe(pmap, va);
727 if (pdpe == NULL || (*pdpe & PG_V) == 0)
729 return (pmap_pdpe_to_pde(pdpe, va));
732 /* Return a pointer to the PT slot that corresponds to a VA */
733 static __inline pt_entry_t *
734 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
738 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
739 return (&pte[pmap_pte_index(va)]);
742 /* Return a pointer to the PT slot that corresponds to a VA */
743 static __inline pt_entry_t *
744 pmap_pte(pmap_t pmap, vm_offset_t va)
749 PG_V = pmap_valid_bit(pmap);
750 pde = pmap_pde(pmap, va);
751 if (pde == NULL || (*pde & PG_V) == 0)
753 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
754 return ((pt_entry_t *)pde);
755 return (pmap_pde_to_pte(pde, va));
759 pmap_resident_count_inc(pmap_t pmap, int count)
762 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
763 pmap->pm_stats.resident_count += count;
767 pmap_resident_count_dec(pmap_t pmap, int count)
770 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
771 KASSERT(pmap->pm_stats.resident_count >= count,
772 ("pmap %p resident count underflow %ld %d", pmap,
773 pmap->pm_stats.resident_count, count));
774 pmap->pm_stats.resident_count -= count;
777 PMAP_INLINE pt_entry_t *
778 vtopte(vm_offset_t va)
780 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
782 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
784 return (PTmap + ((va >> PAGE_SHIFT) & mask));
787 static __inline pd_entry_t *
788 vtopde(vm_offset_t va)
790 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
792 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
794 return (PDmap + ((va >> PDRSHIFT) & mask));
798 allocpages(vm_paddr_t *firstaddr, int n)
803 bzero((void *)ret, n * PAGE_SIZE);
804 *firstaddr += n * PAGE_SIZE;
808 CTASSERT(powerof2(NDMPML4E));
810 /* number of kernel PDP slots */
811 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
814 nkpt_init(vm_paddr_t addr)
821 pt_pages = howmany(addr, 1 << PDRSHIFT);
822 pt_pages += NKPDPE(pt_pages);
825 * Add some slop beyond the bare minimum required for bootstrapping
828 * This is quite important when allocating KVA for kernel modules.
829 * The modules are required to be linked in the negative 2GB of
830 * the address space. If we run out of KVA in this region then
831 * pmap_growkernel() will need to allocate page table pages to map
832 * the entire 512GB of KVA space which is an unnecessary tax on
835 * Secondly, device memory mapped as part of setting up the low-
836 * level console(s) is taken from KVA, starting at virtual_avail.
837 * This is because cninit() is called after pmap_bootstrap() but
838 * before vm_init() and pmap_init(). 20MB for a frame buffer is
841 pt_pages += 32; /* 64MB additional slop. */
847 create_pagetables(vm_paddr_t *firstaddr)
849 int i, j, ndm1g, nkpdpe;
855 /* Allocate page table pages for the direct map */
856 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
857 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
859 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
860 if (ndmpdpphys > NDMPML4E) {
862 * Each NDMPML4E allows 512 GB, so limit to that,
863 * and then readjust ndmpdp and ndmpdpphys.
865 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
866 Maxmem = atop(NDMPML4E * NBPML4);
867 ndmpdpphys = NDMPML4E;
868 ndmpdp = NDMPML4E * NPDEPG;
870 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
872 if ((amd_feature & AMDID_PAGE1GB) != 0)
873 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
875 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
876 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
879 KPML4phys = allocpages(firstaddr, 1);
880 KPDPphys = allocpages(firstaddr, NKPML4E);
883 * Allocate the initial number of kernel page table pages required to
884 * bootstrap. We defer this until after all memory-size dependent
885 * allocations are done (e.g. direct map), so that we don't have to
886 * build in too much slop in our estimate.
888 * Note that when NKPML4E > 1, we have an empty page underneath
889 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
890 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
892 nkpt_init(*firstaddr);
893 nkpdpe = NKPDPE(nkpt);
895 KPTphys = allocpages(firstaddr, nkpt);
896 KPDphys = allocpages(firstaddr, nkpdpe);
898 /* Fill in the underlying page table pages */
899 /* Nominally read-only (but really R/W) from zero to physfree */
900 /* XXX not fully used, underneath 2M pages */
901 pt_p = (pt_entry_t *)KPTphys;
902 for (i = 0; ptoa(i) < *firstaddr; i++)
903 pt_p[i] = ptoa(i) | X86_PG_RW | X86_PG_V | X86_PG_G;
905 /* Now map the page tables at their location within PTmap */
906 pd_p = (pd_entry_t *)KPDphys;
907 for (i = 0; i < nkpt; i++)
908 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
910 /* Map from zero to end of allocations under 2M pages */
911 /* This replaces some of the KPTphys entries above */
912 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
913 pd_p[i] = (i << PDRSHIFT) | X86_PG_RW | X86_PG_V | PG_PS |
916 /* And connect up the PD to the PDP (leaving room for L4 pages) */
917 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
918 for (i = 0; i < nkpdpe; i++)
919 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
923 * Now, set up the direct map region using 2MB and/or 1GB pages. If
924 * the end of physical memory is not aligned to a 1GB page boundary,
925 * then the residual physical memory is mapped with 2MB pages. Later,
926 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
927 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
928 * that are partially used.
930 pd_p = (pd_entry_t *)DMPDphys;
931 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
932 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
933 /* Preset PG_M and PG_A because demotion expects it. */
934 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | X86_PG_G |
937 pdp_p = (pdp_entry_t *)DMPDPphys;
938 for (i = 0; i < ndm1g; i++) {
939 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
940 /* Preset PG_M and PG_A because demotion expects it. */
941 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | X86_PG_G |
944 for (j = 0; i < ndmpdp; i++, j++) {
945 pdp_p[i] = DMPDphys + ptoa(j);
946 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_U;
949 /* And recursively map PML4 to itself in order to get PTmap */
950 p4_p = (pml4_entry_t *)KPML4phys;
951 p4_p[PML4PML4I] = KPML4phys;
952 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | PG_U;
954 /* Connect the Direct Map slot(s) up to the PML4. */
955 for (i = 0; i < ndmpdpphys; i++) {
956 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
957 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | PG_U;
960 /* Connect the KVA slots up to the PML4 */
961 for (i = 0; i < NKPML4E; i++) {
962 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
963 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V | PG_U;
968 * Bootstrap the system enough to run with virtual memory.
970 * On amd64 this is called after mapping has already been enabled
971 * and just syncs the pmap module with what has already been done.
972 * [We can't call it easily with mapping off since the kernel is not
973 * mapped with PA == VA, hence we would have to relocate every address
974 * from the linked base (virtual) address "KERNBASE" to the actual
975 * (physical) address starting relative to 0]
978 pmap_bootstrap(vm_paddr_t *firstaddr)
985 * Create an initial set of page tables to run the kernel in.
987 create_pagetables(firstaddr);
990 * Add a physical memory segment (vm_phys_seg) corresponding to the
991 * preallocated kernel page table pages so that vm_page structures
992 * representing these pages will be created. The vm_page structures
993 * are required for promotion of the corresponding kernel virtual
994 * addresses to superpage mappings.
996 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
998 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
999 virtual_avail = pmap_kmem_choose(virtual_avail);
1001 virtual_end = VM_MAX_KERNEL_ADDRESS;
1004 /* XXX do %cr0 as well */
1005 load_cr4(rcr4() | CR4_PGE);
1006 load_cr3(KPML4phys);
1007 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1008 load_cr4(rcr4() | CR4_SMEP);
1011 * Initialize the kernel pmap (which is statically allocated).
1013 PMAP_LOCK_INIT(kernel_pmap);
1014 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1015 kernel_pmap->pm_cr3 = KPML4phys;
1016 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1017 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1018 kernel_pmap->pm_flags = pmap_flags;
1021 * Initialize the TLB invalidations generation number lock.
1023 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1026 * Reserve some special page table entries/VA space for temporary
1029 #define SYSMAP(c, p, v, n) \
1030 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1036 * Crashdump maps. The first page is reused as CMAP1 for the
1039 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1040 CADDR1 = crashdumpmap;
1045 * Initialize the PAT MSR.
1046 * pmap_init_pat() clears and sets CR4_PGE, which, as a
1047 * side-effect, invalidates stale PG_G TLB entries that might
1048 * have been created in our pre-boot environment.
1052 /* Initialize TLB Context Id. */
1053 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1054 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1055 /* Check for INVPCID support */
1056 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1058 for (i = 0; i < MAXCPU; i++) {
1059 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1060 kernel_pmap->pm_pcids[i].pm_gen = 1;
1062 __pcpu[0].pc_pcid_next = PMAP_PCID_KERN + 1;
1063 __pcpu[0].pc_pcid_gen = 1;
1065 * pcpu area for APs is zeroed during AP startup.
1066 * pc_pcid_next and pc_pcid_gen are initialized by AP
1067 * during pcpu setup.
1069 load_cr4(rcr4() | CR4_PCIDE);
1071 pmap_pcid_enabled = 0;
1076 * Setup the PAT MSR.
1081 int pat_table[PAT_INDEX_SIZE];
1086 /* Bail if this CPU doesn't implement PAT. */
1087 if ((cpu_feature & CPUID_PAT) == 0)
1090 /* Set default PAT index table. */
1091 for (i = 0; i < PAT_INDEX_SIZE; i++)
1093 pat_table[PAT_WRITE_BACK] = 0;
1094 pat_table[PAT_WRITE_THROUGH] = 1;
1095 pat_table[PAT_UNCACHEABLE] = 3;
1096 pat_table[PAT_WRITE_COMBINING] = 3;
1097 pat_table[PAT_WRITE_PROTECTED] = 3;
1098 pat_table[PAT_UNCACHED] = 3;
1100 /* Initialize default PAT entries. */
1101 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1102 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1103 PAT_VALUE(2, PAT_UNCACHED) |
1104 PAT_VALUE(3, PAT_UNCACHEABLE) |
1105 PAT_VALUE(4, PAT_WRITE_BACK) |
1106 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1107 PAT_VALUE(6, PAT_UNCACHED) |
1108 PAT_VALUE(7, PAT_UNCACHEABLE);
1112 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1113 * Program 5 and 6 as WP and WC.
1114 * Leave 4 and 7 as WB and UC.
1116 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1117 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1118 PAT_VALUE(6, PAT_WRITE_COMBINING);
1119 pat_table[PAT_UNCACHED] = 2;
1120 pat_table[PAT_WRITE_PROTECTED] = 5;
1121 pat_table[PAT_WRITE_COMBINING] = 6;
1124 * Just replace PAT Index 2 with WC instead of UC-.
1126 pat_msr &= ~PAT_MASK(2);
1127 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1128 pat_table[PAT_WRITE_COMBINING] = 2;
1133 load_cr4(cr4 & ~CR4_PGE);
1135 /* Disable caches (CD = 1, NW = 0). */
1137 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1139 /* Flushes caches and TLBs. */
1143 /* Update PAT and index table. */
1144 wrmsr(MSR_PAT, pat_msr);
1145 for (i = 0; i < PAT_INDEX_SIZE; i++)
1146 pat_index[i] = pat_table[i];
1148 /* Flush caches and TLBs again. */
1152 /* Restore caches and PGE. */
1158 * Initialize a vm_page's machine-dependent fields.
1161 pmap_page_init(vm_page_t m)
1164 TAILQ_INIT(&m->md.pv_list);
1165 m->md.pat_mode = PAT_WRITE_BACK;
1169 * Initialize the pmap module.
1170 * Called by vm_init, to initialize any structures that the pmap
1171 * system needs to map virtual memory.
1176 struct pmap_preinit_mapping *ppim;
1179 int error, i, pv_npg;
1182 * Initialize the vm page array entries for the kernel pmap's
1185 for (i = 0; i < nkpt; i++) {
1186 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1187 KASSERT(mpte >= vm_page_array &&
1188 mpte < &vm_page_array[vm_page_array_size],
1189 ("pmap_init: page table page is out of range"));
1190 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1191 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1195 * If the kernel is running on a virtual machine, then it must assume
1196 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1197 * be prepared for the hypervisor changing the vendor and family that
1198 * are reported by CPUID. Consequently, the workaround for AMD Family
1199 * 10h Erratum 383 is enabled if the processor's feature set does not
1200 * include at least one feature that is only supported by older Intel
1201 * or newer AMD processors.
1203 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1204 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1205 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1207 workaround_erratum383 = 1;
1210 * Are large page mappings enabled?
1212 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1213 if (pg_ps_enabled) {
1214 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1215 ("pmap_init: can't assign to pagesizes[1]"));
1216 pagesizes[1] = NBPDR;
1220 * Initialize the pv chunk list mutex.
1222 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1225 * Initialize the pool of pv list locks.
1227 for (i = 0; i < NPV_LIST_LOCKS; i++)
1228 rw_init(&pv_list_locks[i], "pmap pv list");
1231 * Calculate the size of the pv head table for superpages.
1233 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1236 * Allocate memory for the pv head table for superpages.
1238 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1240 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1242 for (i = 0; i < pv_npg; i++)
1243 TAILQ_INIT(&pv_table[i].pv_list);
1244 TAILQ_INIT(&pv_dummy.pv_list);
1246 pmap_initialized = 1;
1247 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1248 ppim = pmap_preinit_mapping + i;
1251 /* Make the direct map consistent */
1252 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1253 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1254 ppim->sz, ppim->mode);
1258 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1259 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1262 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1263 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1264 (vmem_addr_t *)&qframe);
1266 panic("qframe allocation failed");
1269 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1270 "2MB page mapping counters");
1272 static u_long pmap_pde_demotions;
1273 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1274 &pmap_pde_demotions, 0, "2MB page demotions");
1276 static u_long pmap_pde_mappings;
1277 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1278 &pmap_pde_mappings, 0, "2MB page mappings");
1280 static u_long pmap_pde_p_failures;
1281 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1282 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1284 static u_long pmap_pde_promotions;
1285 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1286 &pmap_pde_promotions, 0, "2MB page promotions");
1288 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1289 "1GB page mapping counters");
1291 static u_long pmap_pdpe_demotions;
1292 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1293 &pmap_pdpe_demotions, 0, "1GB page demotions");
1295 /***************************************************
1296 * Low level helper routines.....
1297 ***************************************************/
1300 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1302 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1304 switch (pmap->pm_type) {
1307 /* Verify that both PAT bits are not set at the same time */
1308 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1309 ("Invalid PAT bits in entry %#lx", entry));
1311 /* Swap the PAT bits if one of them is set */
1312 if ((entry & x86_pat_bits) != 0)
1313 entry ^= x86_pat_bits;
1317 * Nothing to do - the memory attributes are represented
1318 * the same way for regular pages and superpages.
1322 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1329 * Determine the appropriate bits to set in a PTE or PDE for a specified
1333 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1335 int cache_bits, pat_flag, pat_idx;
1337 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1338 panic("Unknown caching mode %d\n", mode);
1340 switch (pmap->pm_type) {
1343 /* The PAT bit is different for PTE's and PDE's. */
1344 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1346 /* Map the caching mode to a PAT index. */
1347 pat_idx = pat_index[mode];
1349 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1352 cache_bits |= pat_flag;
1354 cache_bits |= PG_NC_PCD;
1356 cache_bits |= PG_NC_PWT;
1360 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1364 panic("unsupported pmap type %d", pmap->pm_type);
1367 return (cache_bits);
1371 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1375 switch (pmap->pm_type) {
1378 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1381 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1384 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1390 static __inline boolean_t
1391 pmap_ps_enabled(pmap_t pmap)
1394 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1398 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1401 switch (pmap->pm_type) {
1408 * This is a little bogus since the generation number is
1409 * supposed to be bumped up when a region of the address
1410 * space is invalidated in the page tables.
1412 * In this case the old PDE entry is valid but yet we want
1413 * to make sure that any mappings using the old entry are
1414 * invalidated in the TLB.
1416 * The reason this works as expected is because we rendezvous
1417 * "all" host cpus and force any vcpu context to exit as a
1420 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1423 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1425 pde_store(pde, newpde);
1429 * After changing the page size for the specified virtual address in the page
1430 * table, flush the corresponding entries from the processor's TLB. Only the
1431 * calling processor's TLB is affected.
1433 * The calling thread must be pinned to a processor.
1436 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1440 if (pmap_type_guest(pmap))
1443 KASSERT(pmap->pm_type == PT_X86,
1444 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1446 PG_G = pmap_global_bit(pmap);
1448 if ((newpde & PG_PS) == 0)
1449 /* Demotion: flush a specific 2MB page mapping. */
1451 else if ((newpde & PG_G) == 0)
1453 * Promotion: flush every 4KB page mapping from the TLB
1454 * because there are too many to flush individually.
1459 * Promotion: flush every 4KB page mapping from the TLB,
1460 * including any global (PG_G) mappings.
1468 * For SMP, these functions have to use the IPI mechanism for coherence.
1470 * N.B.: Before calling any of the following TLB invalidation functions,
1471 * the calling processor must ensure that all stores updating a non-
1472 * kernel page table are globally performed. Otherwise, another
1473 * processor could cache an old, pre-update entry without being
1474 * invalidated. This can happen one of two ways: (1) The pmap becomes
1475 * active on another processor after its pm_active field is checked by
1476 * one of the following functions but before a store updating the page
1477 * table is globally performed. (2) The pmap becomes active on another
1478 * processor before its pm_active field is checked but due to
1479 * speculative loads one of the following functions stills reads the
1480 * pmap as inactive on the other processor.
1482 * The kernel page table is exempt because its pm_active field is
1483 * immutable. The kernel page table is always active on every
1488 * Interrupt the cpus that are executing in the guest context.
1489 * This will force the vcpu to exit and the cached EPT mappings
1490 * will be invalidated by the host before the next vmresume.
1492 static __inline void
1493 pmap_invalidate_ept(pmap_t pmap)
1498 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1499 ("pmap_invalidate_ept: absurd pm_active"));
1502 * The TLB mappings associated with a vcpu context are not
1503 * flushed each time a different vcpu is chosen to execute.
1505 * This is in contrast with a process's vtop mappings that
1506 * are flushed from the TLB on each context switch.
1508 * Therefore we need to do more than just a TLB shootdown on
1509 * the active cpus in 'pmap->pm_active'. To do this we keep
1510 * track of the number of invalidations performed on this pmap.
1512 * Each vcpu keeps a cache of this counter and compares it
1513 * just before a vmresume. If the counter is out-of-date an
1514 * invept will be done to flush stale mappings from the TLB.
1516 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1519 * Force the vcpu to exit and trap back into the hypervisor.
1521 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1522 ipi_selected(pmap->pm_active, ipinum);
1527 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1532 if (pmap_type_guest(pmap)) {
1533 pmap_invalidate_ept(pmap);
1537 KASSERT(pmap->pm_type == PT_X86,
1538 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1541 if (pmap == kernel_pmap) {
1545 cpuid = PCPU_GET(cpuid);
1546 if (pmap == PCPU_GET(curpmap))
1548 else if (pmap_pcid_enabled)
1549 pmap->pm_pcids[cpuid].pm_gen = 0;
1550 if (pmap_pcid_enabled) {
1553 pmap->pm_pcids[i].pm_gen = 0;
1556 mask = &pmap->pm_active;
1558 smp_masked_invlpg(*mask, va);
1562 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1563 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1566 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1572 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1573 pmap_invalidate_all(pmap);
1577 if (pmap_type_guest(pmap)) {
1578 pmap_invalidate_ept(pmap);
1582 KASSERT(pmap->pm_type == PT_X86,
1583 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1586 cpuid = PCPU_GET(cpuid);
1587 if (pmap == kernel_pmap) {
1588 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1592 if (pmap == PCPU_GET(curpmap)) {
1593 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1595 } else if (pmap_pcid_enabled) {
1596 pmap->pm_pcids[cpuid].pm_gen = 0;
1598 if (pmap_pcid_enabled) {
1601 pmap->pm_pcids[i].pm_gen = 0;
1604 mask = &pmap->pm_active;
1606 smp_masked_invlpg_range(*mask, sva, eva);
1611 pmap_invalidate_all(pmap_t pmap)
1614 struct invpcid_descr d;
1617 if (pmap_type_guest(pmap)) {
1618 pmap_invalidate_ept(pmap);
1622 KASSERT(pmap->pm_type == PT_X86,
1623 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1626 if (pmap == kernel_pmap) {
1627 if (pmap_pcid_enabled && invpcid_works) {
1628 bzero(&d, sizeof(d));
1629 invpcid(&d, INVPCID_CTXGLOB);
1635 cpuid = PCPU_GET(cpuid);
1636 if (pmap == PCPU_GET(curpmap)) {
1637 if (pmap_pcid_enabled) {
1638 if (invpcid_works) {
1639 d.pcid = pmap->pm_pcids[cpuid].pm_pcid;
1642 invpcid(&d, INVPCID_CTX);
1644 load_cr3(pmap->pm_cr3 | pmap->pm_pcids
1645 [PCPU_GET(cpuid)].pm_pcid);
1650 } else if (pmap_pcid_enabled) {
1651 pmap->pm_pcids[cpuid].pm_gen = 0;
1653 if (pmap_pcid_enabled) {
1656 pmap->pm_pcids[i].pm_gen = 0;
1659 mask = &pmap->pm_active;
1661 smp_masked_invltlb(*mask, pmap);
1666 pmap_invalidate_cache(void)
1676 cpuset_t invalidate; /* processors that invalidate their TLB */
1681 u_int store; /* processor that updates the PDE */
1685 pmap_update_pde_action(void *arg)
1687 struct pde_action *act = arg;
1689 if (act->store == PCPU_GET(cpuid))
1690 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1694 pmap_update_pde_teardown(void *arg)
1696 struct pde_action *act = arg;
1698 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1699 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1703 * Change the page size for the specified virtual address in a way that
1704 * prevents any possibility of the TLB ever having two entries that map the
1705 * same virtual address using different page sizes. This is the recommended
1706 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1707 * machine check exception for a TLB state that is improperly diagnosed as a
1711 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1713 struct pde_action act;
1714 cpuset_t active, other_cpus;
1718 cpuid = PCPU_GET(cpuid);
1719 other_cpus = all_cpus;
1720 CPU_CLR(cpuid, &other_cpus);
1721 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1724 active = pmap->pm_active;
1726 if (CPU_OVERLAP(&active, &other_cpus)) {
1728 act.invalidate = active;
1732 act.newpde = newpde;
1733 CPU_SET(cpuid, &active);
1734 smp_rendezvous_cpus(active,
1735 smp_no_rendevous_barrier, pmap_update_pde_action,
1736 pmap_update_pde_teardown, &act);
1738 pmap_update_pde_store(pmap, pde, newpde);
1739 if (CPU_ISSET(cpuid, &active))
1740 pmap_update_pde_invalidate(pmap, va, newpde);
1746 * Normal, non-SMP, invalidation functions.
1749 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1752 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1756 KASSERT(pmap->pm_type == PT_X86,
1757 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1759 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1761 else if (pmap_pcid_enabled)
1762 pmap->pm_pcids[0].pm_gen = 0;
1766 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1770 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1774 KASSERT(pmap->pm_type == PT_X86,
1775 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1777 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1778 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1780 } else if (pmap_pcid_enabled) {
1781 pmap->pm_pcids[0].pm_gen = 0;
1786 pmap_invalidate_all(pmap_t pmap)
1788 struct invpcid_descr d;
1790 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1794 KASSERT(pmap->pm_type == PT_X86,
1795 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
1797 if (pmap == kernel_pmap) {
1798 if (pmap_pcid_enabled && invpcid_works) {
1799 bzero(&d, sizeof(d));
1800 invpcid(&d, INVPCID_CTXGLOB);
1804 } else if (pmap == PCPU_GET(curpmap)) {
1805 if (pmap_pcid_enabled) {
1806 if (invpcid_works) {
1807 d.pcid = pmap->pm_pcids[0].pm_pcid;
1810 invpcid(&d, INVPCID_CTX);
1812 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[0].
1818 } else if (pmap_pcid_enabled) {
1819 pmap->pm_pcids[0].pm_gen = 0;
1824 pmap_invalidate_cache(void)
1831 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1834 pmap_update_pde_store(pmap, pde, newpde);
1835 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1836 pmap_update_pde_invalidate(pmap, va, newpde);
1838 pmap->pm_pcids[0].pm_gen = 0;
1842 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
1845 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
1849 sva &= ~(vm_offset_t)cpu_clflush_line_size;
1851 KASSERT((sva & PAGE_MASK) == 0,
1852 ("pmap_invalidate_cache_range: sva not page-aligned"));
1853 KASSERT((eva & PAGE_MASK) == 0,
1854 ("pmap_invalidate_cache_range: eva not page-aligned"));
1857 if ((cpu_feature & CPUID_SS) != 0 && !force)
1858 ; /* If "Self Snoop" is supported and allowed, do nothing. */
1859 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
1860 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1862 * XXX: Some CPUs fault, hang, or trash the local APIC
1863 * registers if we use CLFLUSH on the local APIC
1864 * range. The local APIC is always uncached, so we
1865 * don't need to flush for that range anyway.
1867 if (pmap_kextract(sva) == lapic_paddr)
1871 * Otherwise, do per-cache line flush. Use the sfence
1872 * instruction to insure that previous stores are
1873 * included in the write-back. The processor
1874 * propagates flush to other processors in the cache
1878 for (; sva < eva; sva += cpu_clflush_line_size)
1881 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
1882 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1883 if (pmap_kextract(sva) == lapic_paddr)
1886 * Writes are ordered by CLFLUSH on Intel CPUs.
1888 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1890 for (; sva < eva; sva += cpu_clflush_line_size)
1892 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1897 * No targeted cache flush methods are supported by CPU,
1898 * or the supplied range is bigger than 2MB.
1899 * Globally invalidate cache.
1901 pmap_invalidate_cache();
1906 * Remove the specified set of pages from the data and instruction caches.
1908 * In contrast to pmap_invalidate_cache_range(), this function does not
1909 * rely on the CPU's self-snoop feature, because it is intended for use
1910 * when moving pages into a different cache domain.
1913 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1915 vm_offset_t daddr, eva;
1919 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
1920 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1921 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
1922 pmap_invalidate_cache();
1926 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
1928 for (i = 0; i < count; i++) {
1929 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
1930 eva = daddr + PAGE_SIZE;
1931 for (; daddr < eva; daddr += cpu_clflush_line_size) {
1940 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
1946 * Routine: pmap_extract
1948 * Extract the physical page address associated
1949 * with the given map/virtual_address pair.
1952 pmap_extract(pmap_t pmap, vm_offset_t va)
1956 pt_entry_t *pte, PG_V;
1960 PG_V = pmap_valid_bit(pmap);
1962 pdpe = pmap_pdpe(pmap, va);
1963 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
1964 if ((*pdpe & PG_PS) != 0)
1965 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
1967 pde = pmap_pdpe_to_pde(pdpe, va);
1968 if ((*pde & PG_V) != 0) {
1969 if ((*pde & PG_PS) != 0) {
1970 pa = (*pde & PG_PS_FRAME) |
1973 pte = pmap_pde_to_pte(pde, va);
1974 pa = (*pte & PG_FRAME) |
1985 * Routine: pmap_extract_and_hold
1987 * Atomically extract and hold the physical page
1988 * with the given pmap and virtual address pair
1989 * if that mapping permits the given protection.
1992 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1994 pd_entry_t pde, *pdep;
1995 pt_entry_t pte, PG_RW, PG_V;
2001 PG_RW = pmap_rw_bit(pmap);
2002 PG_V = pmap_valid_bit(pmap);
2005 pdep = pmap_pde(pmap, va);
2006 if (pdep != NULL && (pde = *pdep)) {
2008 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2009 if (vm_page_pa_tryrelock(pmap, (pde &
2010 PG_PS_FRAME) | (va & PDRMASK), &pa))
2012 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
2017 pte = *pmap_pde_to_pte(pdep, va);
2019 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2020 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2023 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
2034 pmap_kextract(vm_offset_t va)
2039 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2040 pa = DMAP_TO_PHYS(va);
2044 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2047 * Beware of a concurrent promotion that changes the
2048 * PDE at this point! For example, vtopte() must not
2049 * be used to access the PTE because it would use the
2050 * new PDE. It is, however, safe to use the old PDE
2051 * because the page table page is preserved by the
2054 pa = *pmap_pde_to_pte(&pde, va);
2055 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2061 /***************************************************
2062 * Low level mapping routines.....
2063 ***************************************************/
2066 * Add a wired page to the kva.
2067 * Note: not SMP coherent.
2070 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2075 pte_store(pte, pa | X86_PG_RW | X86_PG_V | X86_PG_G);
2078 static __inline void
2079 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2085 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2086 pte_store(pte, pa | X86_PG_RW | X86_PG_V | X86_PG_G | cache_bits);
2090 * Remove a page from the kernel pagetables.
2091 * Note: not SMP coherent.
2094 pmap_kremove(vm_offset_t va)
2103 * Used to map a range of physical addresses into kernel
2104 * virtual address space.
2106 * The value passed in '*virt' is a suggested virtual address for
2107 * the mapping. Architectures which can support a direct-mapped
2108 * physical to virtual region can return the appropriate address
2109 * within that region, leaving '*virt' unchanged. Other
2110 * architectures should map the pages starting at '*virt' and
2111 * update '*virt' with the first usable address after the mapped
2115 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2117 return PHYS_TO_DMAP(start);
2122 * Add a list of wired pages to the kva
2123 * this routine is only used for temporary
2124 * kernel mappings that do not need to have
2125 * page modification or references recorded.
2126 * Note that old mappings are simply written
2127 * over. The page *must* be wired.
2128 * Note: SMP coherent. Uses a ranged shootdown IPI.
2131 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2133 pt_entry_t *endpte, oldpte, pa, *pte;
2139 endpte = pte + count;
2140 while (pte < endpte) {
2142 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2143 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2144 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2146 pte_store(pte, pa | X86_PG_G | X86_PG_RW | X86_PG_V);
2150 if (__predict_false((oldpte & X86_PG_V) != 0))
2151 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2156 * This routine tears out page mappings from the
2157 * kernel -- it is meant only for temporary mappings.
2158 * Note: SMP coherent. Uses a ranged shootdown IPI.
2161 pmap_qremove(vm_offset_t sva, int count)
2166 while (count-- > 0) {
2167 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2171 pmap_invalidate_range(kernel_pmap, sva, va);
2174 /***************************************************
2175 * Page table page management routines.....
2176 ***************************************************/
2177 static __inline void
2178 pmap_free_zero_pages(struct spglist *free)
2182 while ((m = SLIST_FIRST(free)) != NULL) {
2183 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2184 /* Preserve the page's PG_ZERO setting. */
2185 vm_page_free_toq(m);
2190 * Schedule the specified unused page table page to be freed. Specifically,
2191 * add the page to the specified list of pages that will be released to the
2192 * physical memory manager after the TLB has been updated.
2194 static __inline void
2195 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2196 boolean_t set_PG_ZERO)
2200 m->flags |= PG_ZERO;
2202 m->flags &= ~PG_ZERO;
2203 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2207 * Inserts the specified page table page into the specified pmap's collection
2208 * of idle page table pages. Each of a pmap's page table pages is responsible
2209 * for mapping a distinct range of virtual addresses. The pmap's collection is
2210 * ordered by this virtual address range.
2213 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2216 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2217 return (vm_radix_insert(&pmap->pm_root, mpte));
2221 * Looks for a page table page mapping the specified virtual address in the
2222 * specified pmap's collection of idle page table pages. Returns NULL if there
2223 * is no page table page corresponding to the specified virtual address.
2225 static __inline vm_page_t
2226 pmap_lookup_pt_page(pmap_t pmap, vm_offset_t va)
2229 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2230 return (vm_radix_lookup(&pmap->pm_root, pmap_pde_pindex(va)));
2234 * Removes the specified page table page from the specified pmap's collection
2235 * of idle page table pages. The specified page table page must be a member of
2236 * the pmap's collection.
2238 static __inline void
2239 pmap_remove_pt_page(pmap_t pmap, vm_page_t mpte)
2242 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2243 vm_radix_remove(&pmap->pm_root, mpte->pindex);
2247 * Decrements a page table page's wire count, which is used to record the
2248 * number of valid page table entries within the page. If the wire count
2249 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2250 * page table page was unmapped and FALSE otherwise.
2252 static inline boolean_t
2253 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2257 if (m->wire_count == 0) {
2258 _pmap_unwire_ptp(pmap, va, m, free);
2265 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2268 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2270 * unmap the page table page
2272 if (m->pindex >= (NUPDE + NUPDPE)) {
2275 pml4 = pmap_pml4e(pmap, va);
2277 } else if (m->pindex >= NUPDE) {
2280 pdp = pmap_pdpe(pmap, va);
2285 pd = pmap_pde(pmap, va);
2288 pmap_resident_count_dec(pmap, 1);
2289 if (m->pindex < NUPDE) {
2290 /* We just released a PT, unhold the matching PD */
2293 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2294 pmap_unwire_ptp(pmap, va, pdpg, free);
2296 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2297 /* We just released a PD, unhold the matching PDP */
2300 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2301 pmap_unwire_ptp(pmap, va, pdppg, free);
2305 * This is a release store so that the ordinary store unmapping
2306 * the page table page is globally performed before TLB shoot-
2309 atomic_subtract_rel_int(&vm_cnt.v_wire_count, 1);
2312 * Put page on a list so that it is released after
2313 * *ALL* TLB shootdown is done
2315 pmap_add_delayed_free_list(m, free, TRUE);
2319 * After removing a page table entry, this routine is used to
2320 * conditionally free the page, and manage the hold/wire counts.
2323 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2324 struct spglist *free)
2328 if (va >= VM_MAXUSER_ADDRESS)
2330 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2331 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2332 return (pmap_unwire_ptp(pmap, va, mpte, free));
2336 pmap_pinit0(pmap_t pmap)
2340 PMAP_LOCK_INIT(pmap);
2341 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2342 pmap->pm_cr3 = KPML4phys;
2343 pmap->pm_root.rt_root = 0;
2344 CPU_ZERO(&pmap->pm_active);
2345 TAILQ_INIT(&pmap->pm_pvchunk);
2346 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2347 pmap->pm_flags = pmap_flags;
2349 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2350 pmap->pm_pcids[i].pm_gen = 0;
2352 PCPU_SET(curpmap, kernel_pmap);
2353 pmap_activate(curthread);
2354 CPU_FILL(&kernel_pmap->pm_active);
2358 pmap_pinit_pml4(vm_page_t pml4pg)
2360 pml4_entry_t *pm_pml4;
2363 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2365 /* Wire in kernel global address entries. */
2366 for (i = 0; i < NKPML4E; i++) {
2367 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2370 for (i = 0; i < ndmpdpphys; i++) {
2371 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2375 /* install self-referential address mapping entry(s) */
2376 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2377 X86_PG_A | X86_PG_M;
2381 * Initialize a preallocated and zeroed pmap structure,
2382 * such as one in a vmspace structure.
2385 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2388 vm_paddr_t pml4phys;
2392 * allocate the page directory page
2394 while ((pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2395 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL)
2398 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2399 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2401 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2402 pmap->pm_pcids[i].pm_gen = 0;
2404 pmap->pm_cr3 = ~0; /* initialize to an invalid value */
2406 if ((pml4pg->flags & PG_ZERO) == 0)
2407 pagezero(pmap->pm_pml4);
2410 * Do not install the host kernel mappings in the nested page
2411 * tables. These mappings are meaningless in the guest physical
2414 if ((pmap->pm_type = pm_type) == PT_X86) {
2415 pmap->pm_cr3 = pml4phys;
2416 pmap_pinit_pml4(pml4pg);
2419 pmap->pm_root.rt_root = 0;
2420 CPU_ZERO(&pmap->pm_active);
2421 TAILQ_INIT(&pmap->pm_pvchunk);
2422 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2423 pmap->pm_flags = flags;
2424 pmap->pm_eptgen = 0;
2430 pmap_pinit(pmap_t pmap)
2433 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2437 * This routine is called if the desired page table page does not exist.
2439 * If page table page allocation fails, this routine may sleep before
2440 * returning NULL. It sleeps only if a lock pointer was given.
2442 * Note: If a page allocation fails at page table level two or three,
2443 * one or two pages may be held during the wait, only to be released
2444 * afterwards. This conservative approach is easily argued to avoid
2448 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2450 vm_page_t m, pdppg, pdpg;
2451 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2453 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2455 PG_A = pmap_accessed_bit(pmap);
2456 PG_M = pmap_modified_bit(pmap);
2457 PG_V = pmap_valid_bit(pmap);
2458 PG_RW = pmap_rw_bit(pmap);
2461 * Allocate a page table page.
2463 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2464 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2465 if (lockp != NULL) {
2466 RELEASE_PV_LIST_LOCK(lockp);
2468 PMAP_ASSERT_NOT_IN_DI();
2474 * Indicate the need to retry. While waiting, the page table
2475 * page may have been allocated.
2479 if ((m->flags & PG_ZERO) == 0)
2483 * Map the pagetable page into the process address space, if
2484 * it isn't already there.
2487 if (ptepindex >= (NUPDE + NUPDPE)) {
2489 vm_pindex_t pml4index;
2491 /* Wire up a new PDPE page */
2492 pml4index = ptepindex - (NUPDE + NUPDPE);
2493 pml4 = &pmap->pm_pml4[pml4index];
2494 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2496 } else if (ptepindex >= NUPDE) {
2497 vm_pindex_t pml4index;
2498 vm_pindex_t pdpindex;
2502 /* Wire up a new PDE page */
2503 pdpindex = ptepindex - NUPDE;
2504 pml4index = pdpindex >> NPML4EPGSHIFT;
2506 pml4 = &pmap->pm_pml4[pml4index];
2507 if ((*pml4 & PG_V) == 0) {
2508 /* Have to allocate a new pdp, recurse */
2509 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2512 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2513 vm_page_free_zero(m);
2517 /* Add reference to pdp page */
2518 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2519 pdppg->wire_count++;
2521 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2523 /* Now find the pdp page */
2524 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2525 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2528 vm_pindex_t pml4index;
2529 vm_pindex_t pdpindex;
2534 /* Wire up a new PTE page */
2535 pdpindex = ptepindex >> NPDPEPGSHIFT;
2536 pml4index = pdpindex >> NPML4EPGSHIFT;
2538 /* First, find the pdp and check that its valid. */
2539 pml4 = &pmap->pm_pml4[pml4index];
2540 if ((*pml4 & PG_V) == 0) {
2541 /* Have to allocate a new pd, recurse */
2542 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2545 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2546 vm_page_free_zero(m);
2549 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2550 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2552 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2553 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2554 if ((*pdp & PG_V) == 0) {
2555 /* Have to allocate a new pd, recurse */
2556 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2559 atomic_subtract_int(&vm_cnt.v_wire_count,
2561 vm_page_free_zero(m);
2565 /* Add reference to the pd page */
2566 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2570 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2572 /* Now we know where the page directory page is */
2573 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2574 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2577 pmap_resident_count_inc(pmap, 1);
2583 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2585 vm_pindex_t pdpindex, ptepindex;
2586 pdp_entry_t *pdpe, PG_V;
2589 PG_V = pmap_valid_bit(pmap);
2592 pdpe = pmap_pdpe(pmap, va);
2593 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2594 /* Add a reference to the pd page. */
2595 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2598 /* Allocate a pd page. */
2599 ptepindex = pmap_pde_pindex(va);
2600 pdpindex = ptepindex >> NPDPEPGSHIFT;
2601 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2602 if (pdpg == NULL && lockp != NULL)
2609 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2611 vm_pindex_t ptepindex;
2612 pd_entry_t *pd, PG_V;
2615 PG_V = pmap_valid_bit(pmap);
2618 * Calculate pagetable page index
2620 ptepindex = pmap_pde_pindex(va);
2623 * Get the page directory entry
2625 pd = pmap_pde(pmap, va);
2628 * This supports switching from a 2MB page to a
2631 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2632 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2634 * Invalidation of the 2MB page mapping may have caused
2635 * the deallocation of the underlying PD page.
2642 * If the page table page is mapped, we just increment the
2643 * hold count, and activate it.
2645 if (pd != NULL && (*pd & PG_V) != 0) {
2646 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2650 * Here if the pte page isn't mapped, or if it has been
2653 m = _pmap_allocpte(pmap, ptepindex, lockp);
2654 if (m == NULL && lockp != NULL)
2661 /***************************************************
2662 * Pmap allocation/deallocation routines.
2663 ***************************************************/
2666 * Release any resources held by the given physical map.
2667 * Called when a pmap initialized by pmap_pinit is being released.
2668 * Should only be called if the map contains no valid mappings.
2671 pmap_release(pmap_t pmap)
2676 KASSERT(pmap->pm_stats.resident_count == 0,
2677 ("pmap_release: pmap resident count %ld != 0",
2678 pmap->pm_stats.resident_count));
2679 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2680 ("pmap_release: pmap has reserved page table page(s)"));
2681 KASSERT(CPU_EMPTY(&pmap->pm_active),
2682 ("releasing active pmap %p", pmap));
2684 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2686 for (i = 0; i < NKPML4E; i++) /* KVA */
2687 pmap->pm_pml4[KPML4BASE + i] = 0;
2688 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
2689 pmap->pm_pml4[DMPML4I + i] = 0;
2690 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
2693 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2694 vm_page_free_zero(m);
2698 kvm_size(SYSCTL_HANDLER_ARGS)
2700 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2702 return sysctl_handle_long(oidp, &ksize, 0, req);
2704 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2705 0, 0, kvm_size, "LU", "Size of KVM");
2708 kvm_free(SYSCTL_HANDLER_ARGS)
2710 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2712 return sysctl_handle_long(oidp, &kfree, 0, req);
2714 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2715 0, 0, kvm_free, "LU", "Amount of KVM free");
2718 * grow the number of kernel page table entries, if needed
2721 pmap_growkernel(vm_offset_t addr)
2725 pd_entry_t *pde, newpdir;
2728 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2731 * Return if "addr" is within the range of kernel page table pages
2732 * that were preallocated during pmap bootstrap. Moreover, leave
2733 * "kernel_vm_end" and the kernel page table as they were.
2735 * The correctness of this action is based on the following
2736 * argument: vm_map_insert() allocates contiguous ranges of the
2737 * kernel virtual address space. It calls this function if a range
2738 * ends after "kernel_vm_end". If the kernel is mapped between
2739 * "kernel_vm_end" and "addr", then the range cannot begin at
2740 * "kernel_vm_end". In fact, its beginning address cannot be less
2741 * than the kernel. Thus, there is no immediate need to allocate
2742 * any new kernel page table pages between "kernel_vm_end" and
2745 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
2748 addr = roundup2(addr, NBPDR);
2749 if (addr - 1 >= kernel_map->max_offset)
2750 addr = kernel_map->max_offset;
2751 while (kernel_vm_end < addr) {
2752 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
2753 if ((*pdpe & X86_PG_V) == 0) {
2754 /* We need a new PDP entry */
2755 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
2756 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
2757 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2759 panic("pmap_growkernel: no memory to grow kernel");
2760 if ((nkpg->flags & PG_ZERO) == 0)
2761 pmap_zero_page(nkpg);
2762 paddr = VM_PAGE_TO_PHYS(nkpg);
2763 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
2764 X86_PG_A | X86_PG_M);
2765 continue; /* try again */
2767 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
2768 if ((*pde & X86_PG_V) != 0) {
2769 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2770 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2771 kernel_vm_end = kernel_map->max_offset;
2777 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
2778 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
2781 panic("pmap_growkernel: no memory to grow kernel");
2782 if ((nkpg->flags & PG_ZERO) == 0)
2783 pmap_zero_page(nkpg);
2784 paddr = VM_PAGE_TO_PHYS(nkpg);
2785 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
2786 pde_store(pde, newpdir);
2788 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2789 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2790 kernel_vm_end = kernel_map->max_offset;
2797 /***************************************************
2798 * page management routines.
2799 ***************************************************/
2801 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
2802 CTASSERT(_NPCM == 3);
2803 CTASSERT(_NPCPV == 168);
2805 static __inline struct pv_chunk *
2806 pv_to_chunk(pv_entry_t pv)
2809 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
2812 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
2814 #define PC_FREE0 0xfffffffffffffffful
2815 #define PC_FREE1 0xfffffffffffffffful
2816 #define PC_FREE2 0x000000fffffffffful
2818 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
2821 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2823 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2824 "Current number of pv entry chunks");
2825 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2826 "Current number of pv entry chunks allocated");
2827 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2828 "Current number of pv entry chunks frees");
2829 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
2830 "Number of times tried to get a chunk page but failed.");
2832 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
2833 static int pv_entry_spare;
2835 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2836 "Current number of pv entry frees");
2837 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
2838 "Current number of pv entry allocs");
2839 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2840 "Current number of pv entries");
2841 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2842 "Current number of spare pv entries");
2846 * We are in a serious low memory condition. Resort to
2847 * drastic measures to free some pages so we can allocate
2848 * another pv entry chunk.
2850 * Returns NULL if PV entries were reclaimed from the specified pmap.
2852 * We do not, however, unmap 2mpages because subsequent accesses will
2853 * allocate per-page pv entries until repromotion occurs, thereby
2854 * exacerbating the shortage of free pv entries.
2857 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
2859 struct pch new_tail;
2860 struct pv_chunk *pc;
2861 struct md_page *pvh;
2864 pt_entry_t *pte, tpte;
2865 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
2869 struct spglist free;
2871 int bit, field, freed;
2873 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2874 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
2877 PG_G = PG_A = PG_M = PG_RW = 0;
2879 TAILQ_INIT(&new_tail);
2880 pmap_delayed_invl_started();
2881 mtx_lock(&pv_chunks_mutex);
2882 while ((pc = TAILQ_FIRST(&pv_chunks)) != NULL && SLIST_EMPTY(&free)) {
2883 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2884 mtx_unlock(&pv_chunks_mutex);
2885 if (pmap != pc->pc_pmap) {
2887 pmap_invalidate_all(pmap);
2888 if (pmap != locked_pmap)
2891 pmap_delayed_invl_finished();
2892 pmap_delayed_invl_started();
2894 /* Avoid deadlock and lock recursion. */
2895 if (pmap > locked_pmap) {
2896 RELEASE_PV_LIST_LOCK(lockp);
2898 } else if (pmap != locked_pmap &&
2899 !PMAP_TRYLOCK(pmap)) {
2901 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2902 mtx_lock(&pv_chunks_mutex);
2905 PG_G = pmap_global_bit(pmap);
2906 PG_A = pmap_accessed_bit(pmap);
2907 PG_M = pmap_modified_bit(pmap);
2908 PG_RW = pmap_rw_bit(pmap);
2912 * Destroy every non-wired, 4 KB page mapping in the chunk.
2915 for (field = 0; field < _NPCM; field++) {
2916 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2917 inuse != 0; inuse &= ~(1UL << bit)) {
2919 pv = &pc->pc_pventry[field * 64 + bit];
2921 pde = pmap_pde(pmap, va);
2922 if ((*pde & PG_PS) != 0)
2924 pte = pmap_pde_to_pte(pde, va);
2925 if ((*pte & PG_W) != 0)
2927 tpte = pte_load_clear(pte);
2928 if ((tpte & PG_G) != 0)
2929 pmap_invalidate_page(pmap, va);
2930 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
2931 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
2933 if ((tpte & PG_A) != 0)
2934 vm_page_aflag_set(m, PGA_REFERENCED);
2935 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
2936 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
2938 if (TAILQ_EMPTY(&m->md.pv_list) &&
2939 (m->flags & PG_FICTITIOUS) == 0) {
2940 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
2941 if (TAILQ_EMPTY(&pvh->pv_list)) {
2942 vm_page_aflag_clear(m,
2946 pmap_delayed_invl_page(m);
2947 pc->pc_map[field] |= 1UL << bit;
2948 pmap_unuse_pt(pmap, va, *pde, &free);
2953 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2954 mtx_lock(&pv_chunks_mutex);
2957 /* Every freed mapping is for a 4 KB page. */
2958 pmap_resident_count_dec(pmap, freed);
2959 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
2960 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
2961 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
2962 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2963 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
2964 pc->pc_map[2] == PC_FREE2) {
2965 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
2966 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
2967 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
2968 /* Entire chunk is free; return it. */
2969 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
2970 dump_drop_page(m_pc->phys_addr);
2971 mtx_lock(&pv_chunks_mutex);
2974 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2975 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2976 mtx_lock(&pv_chunks_mutex);
2977 /* One freed pv entry in locked_pmap is sufficient. */
2978 if (pmap == locked_pmap)
2981 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
2982 mtx_unlock(&pv_chunks_mutex);
2984 pmap_invalidate_all(pmap);
2985 if (pmap != locked_pmap)
2988 pmap_delayed_invl_finished();
2989 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
2990 m_pc = SLIST_FIRST(&free);
2991 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2992 /* Recycle a freed page table page. */
2993 m_pc->wire_count = 1;
2994 atomic_add_int(&vm_cnt.v_wire_count, 1);
2996 pmap_free_zero_pages(&free);
3001 * free the pv_entry back to the free list
3004 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3006 struct pv_chunk *pc;
3007 int idx, field, bit;
3009 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3010 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3011 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3012 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3013 pc = pv_to_chunk(pv);
3014 idx = pv - &pc->pc_pventry[0];
3017 pc->pc_map[field] |= 1ul << bit;
3018 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3019 pc->pc_map[2] != PC_FREE2) {
3020 /* 98% of the time, pc is already at the head of the list. */
3021 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3022 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3023 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3027 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3032 free_pv_chunk(struct pv_chunk *pc)
3036 mtx_lock(&pv_chunks_mutex);
3037 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3038 mtx_unlock(&pv_chunks_mutex);
3039 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3040 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3041 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3042 /* entire chunk is free, return it */
3043 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3044 dump_drop_page(m->phys_addr);
3045 vm_page_unwire(m, PQ_NONE);
3050 * Returns a new PV entry, allocating a new PV chunk from the system when
3051 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3052 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3055 * The given PV list lock may be released.
3058 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3062 struct pv_chunk *pc;
3065 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3066 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3068 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3070 for (field = 0; field < _NPCM; field++) {
3071 if (pc->pc_map[field]) {
3072 bit = bsfq(pc->pc_map[field]);
3076 if (field < _NPCM) {
3077 pv = &pc->pc_pventry[field * 64 + bit];
3078 pc->pc_map[field] &= ~(1ul << bit);
3079 /* If this was the last item, move it to tail */
3080 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3081 pc->pc_map[2] == 0) {
3082 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3083 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3086 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3087 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3091 /* No free items, allocate another chunk */
3092 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3095 if (lockp == NULL) {
3096 PV_STAT(pc_chunk_tryfail++);
3099 m = reclaim_pv_chunk(pmap, lockp);
3103 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3104 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3105 dump_add_page(m->phys_addr);
3106 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3108 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3109 pc->pc_map[1] = PC_FREE1;
3110 pc->pc_map[2] = PC_FREE2;
3111 mtx_lock(&pv_chunks_mutex);
3112 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3113 mtx_unlock(&pv_chunks_mutex);
3114 pv = &pc->pc_pventry[0];
3115 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3116 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3117 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3122 * Returns the number of one bits within the given PV chunk map.
3124 * The erratas for Intel processors state that "POPCNT Instruction May
3125 * Take Longer to Execute Than Expected". It is believed that the
3126 * issue is the spurious dependency on the destination register.
3127 * Provide a hint to the register rename logic that the destination
3128 * value is overwritten, by clearing it, as suggested in the
3129 * optimization manual. It should be cheap for unaffected processors
3132 * Reference numbers for erratas are
3133 * 4th Gen Core: HSD146
3134 * 5th Gen Core: BDM85
3135 * 6th Gen Core: SKL029
3138 popcnt_pc_map_pq(uint64_t *map)
3142 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3143 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3144 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3145 : "=&r" (result), "=&r" (tmp)
3146 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3151 * Ensure that the number of spare PV entries in the specified pmap meets or
3152 * exceeds the given count, "needed".
3154 * The given PV list lock may be released.
3157 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3159 struct pch new_tail;
3160 struct pv_chunk *pc;
3164 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3165 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3168 * Newly allocated PV chunks must be stored in a private list until
3169 * the required number of PV chunks have been allocated. Otherwise,
3170 * reclaim_pv_chunk() could recycle one of these chunks. In
3171 * contrast, these chunks must be added to the pmap upon allocation.
3173 TAILQ_INIT(&new_tail);
3176 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3178 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3179 bit_count((bitstr_t *)pc->pc_map, 0,
3180 sizeof(pc->pc_map) * NBBY, &free);
3183 free = popcnt_pc_map_pq(pc->pc_map);
3187 if (avail >= needed)
3190 for (; avail < needed; avail += _NPCPV) {
3191 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3194 m = reclaim_pv_chunk(pmap, lockp);
3198 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3199 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3200 dump_add_page(m->phys_addr);
3201 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3203 pc->pc_map[0] = PC_FREE0;
3204 pc->pc_map[1] = PC_FREE1;
3205 pc->pc_map[2] = PC_FREE2;
3206 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3207 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3208 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3210 if (!TAILQ_EMPTY(&new_tail)) {
3211 mtx_lock(&pv_chunks_mutex);
3212 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3213 mtx_unlock(&pv_chunks_mutex);
3218 * First find and then remove the pv entry for the specified pmap and virtual
3219 * address from the specified pv list. Returns the pv entry if found and NULL
3220 * otherwise. This operation can be performed on pv lists for either 4KB or
3221 * 2MB page mappings.
3223 static __inline pv_entry_t
3224 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3228 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3229 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3230 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3239 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3240 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3241 * entries for each of the 4KB page mappings.
3244 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3245 struct rwlock **lockp)
3247 struct md_page *pvh;
3248 struct pv_chunk *pc;
3250 vm_offset_t va_last;
3254 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3255 KASSERT((pa & PDRMASK) == 0,
3256 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3257 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3260 * Transfer the 2mpage's pv entry for this mapping to the first
3261 * page's pv list. Once this transfer begins, the pv list lock
3262 * must not be released until the last pv entry is reinstantiated.
3264 pvh = pa_to_pvh(pa);
3265 va = trunc_2mpage(va);
3266 pv = pmap_pvh_remove(pvh, pmap, va);
3267 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3268 m = PHYS_TO_VM_PAGE(pa);
3269 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3271 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3272 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3273 va_last = va + NBPDR - PAGE_SIZE;
3275 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3276 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3277 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3278 for (field = 0; field < _NPCM; field++) {
3279 while (pc->pc_map[field]) {
3280 bit = bsfq(pc->pc_map[field]);
3281 pc->pc_map[field] &= ~(1ul << bit);
3282 pv = &pc->pc_pventry[field * 64 + bit];
3286 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3287 ("pmap_pv_demote_pde: page %p is not managed", m));
3288 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3294 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3295 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3298 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3299 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3300 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3302 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3303 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3307 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3308 * replace the many pv entries for the 4KB page mappings by a single pv entry
3309 * for the 2MB page mapping.
3312 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3313 struct rwlock **lockp)
3315 struct md_page *pvh;
3317 vm_offset_t va_last;
3320 KASSERT((pa & PDRMASK) == 0,
3321 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3322 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3325 * Transfer the first page's pv entry for this mapping to the 2mpage's
3326 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3327 * a transfer avoids the possibility that get_pv_entry() calls
3328 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3329 * mappings that is being promoted.
3331 m = PHYS_TO_VM_PAGE(pa);
3332 va = trunc_2mpage(va);
3333 pv = pmap_pvh_remove(&m->md, pmap, va);
3334 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3335 pvh = pa_to_pvh(pa);
3336 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3338 /* Free the remaining NPTEPG - 1 pv entries. */
3339 va_last = va + NBPDR - PAGE_SIZE;
3343 pmap_pvh_free(&m->md, pmap, va);
3344 } while (va < va_last);
3348 * First find and then destroy the pv entry for the specified pmap and virtual
3349 * address. This operation can be performed on pv lists for either 4KB or 2MB
3353 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3357 pv = pmap_pvh_remove(pvh, pmap, va);
3358 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3359 free_pv_entry(pmap, pv);
3363 * Conditionally create the PV entry for a 4KB page mapping if the required
3364 * memory can be allocated without resorting to reclamation.
3367 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3368 struct rwlock **lockp)
3372 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3373 /* Pass NULL instead of the lock pointer to disable reclamation. */
3374 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3376 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3377 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3385 * Conditionally create the PV entry for a 2MB page mapping if the required
3386 * memory can be allocated without resorting to reclamation.
3389 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3390 struct rwlock **lockp)
3392 struct md_page *pvh;
3395 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3396 /* Pass NULL instead of the lock pointer to disable reclamation. */
3397 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3399 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3400 pvh = pa_to_pvh(pa);
3401 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3409 * Fills a page table page with mappings to consecutive physical pages.
3412 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3416 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3418 newpte += PAGE_SIZE;
3423 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3424 * mapping is invalidated.
3427 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3429 struct rwlock *lock;
3433 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3440 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3441 struct rwlock **lockp)
3443 pd_entry_t newpde, oldpde;
3444 pt_entry_t *firstpte, newpte;
3445 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3448 struct spglist free;
3452 PG_G = pmap_global_bit(pmap);
3453 PG_A = pmap_accessed_bit(pmap);
3454 PG_M = pmap_modified_bit(pmap);
3455 PG_RW = pmap_rw_bit(pmap);
3456 PG_V = pmap_valid_bit(pmap);
3457 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3459 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3461 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3462 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3463 if ((oldpde & PG_A) != 0 && (mpte = pmap_lookup_pt_page(pmap, va)) !=
3465 pmap_remove_pt_page(pmap, mpte);
3467 KASSERT((oldpde & PG_W) == 0,
3468 ("pmap_demote_pde: page table page for a wired mapping"
3472 * Invalidate the 2MB page mapping and return "failure" if the
3473 * mapping was never accessed or the allocation of the new
3474 * page table page fails. If the 2MB page mapping belongs to
3475 * the direct map region of the kernel's address space, then
3476 * the page allocation request specifies the highest possible
3477 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3478 * normal. Page table pages are preallocated for every other
3479 * part of the kernel address space, so the direct map region
3480 * is the only part of the kernel address space that must be
3483 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3484 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3485 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3486 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3488 sva = trunc_2mpage(va);
3489 pmap_remove_pde(pmap, pde, sva, &free, lockp);
3490 pmap_invalidate_range(pmap, sva, sva + NBPDR - 1);
3491 pmap_free_zero_pages(&free);
3492 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3493 " in pmap %p", va, pmap);
3496 if (va < VM_MAXUSER_ADDRESS)
3497 pmap_resident_count_inc(pmap, 1);
3499 mptepa = VM_PAGE_TO_PHYS(mpte);
3500 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3501 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3502 KASSERT((oldpde & PG_A) != 0,
3503 ("pmap_demote_pde: oldpde is missing PG_A"));
3504 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3505 ("pmap_demote_pde: oldpde is missing PG_M"));
3506 newpte = oldpde & ~PG_PS;
3507 newpte = pmap_swap_pat(pmap, newpte);
3510 * If the page table page is new, initialize it.
3512 if (mpte->wire_count == 1) {
3513 mpte->wire_count = NPTEPG;
3514 pmap_fill_ptp(firstpte, newpte);
3516 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3517 ("pmap_demote_pde: firstpte and newpte map different physical"
3521 * If the mapping has changed attributes, update the page table
3524 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3525 pmap_fill_ptp(firstpte, newpte);
3528 * The spare PV entries must be reserved prior to demoting the
3529 * mapping, that is, prior to changing the PDE. Otherwise, the state
3530 * of the PDE and the PV lists will be inconsistent, which can result
3531 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3532 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3533 * PV entry for the 2MB page mapping that is being demoted.
3535 if ((oldpde & PG_MANAGED) != 0)
3536 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3539 * Demote the mapping. This pmap is locked. The old PDE has
3540 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3541 * set. Thus, there is no danger of a race with another
3542 * processor changing the setting of PG_A and/or PG_M between
3543 * the read above and the store below.
3545 if (workaround_erratum383)
3546 pmap_update_pde(pmap, va, pde, newpde);
3548 pde_store(pde, newpde);
3551 * Invalidate a stale recursive mapping of the page table page.
3553 if (va >= VM_MAXUSER_ADDRESS)
3554 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3557 * Demote the PV entry.
3559 if ((oldpde & PG_MANAGED) != 0)
3560 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3562 atomic_add_long(&pmap_pde_demotions, 1);
3563 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3564 " in pmap %p", va, pmap);
3569 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3572 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3578 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3579 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3580 mpte = pmap_lookup_pt_page(pmap, va);
3582 panic("pmap_remove_kernel_pde: Missing pt page.");
3584 pmap_remove_pt_page(pmap, mpte);
3585 mptepa = VM_PAGE_TO_PHYS(mpte);
3586 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3589 * Initialize the page table page.
3591 pagezero((void *)PHYS_TO_DMAP(mptepa));
3594 * Demote the mapping.
3596 if (workaround_erratum383)
3597 pmap_update_pde(pmap, va, pde, newpde);
3599 pde_store(pde, newpde);
3602 * Invalidate a stale recursive mapping of the page table page.
3604 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3608 * pmap_remove_pde: do the things to unmap a superpage in a process
3611 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
3612 struct spglist *free, struct rwlock **lockp)
3614 struct md_page *pvh;
3616 vm_offset_t eva, va;
3618 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3620 PG_G = pmap_global_bit(pmap);
3621 PG_A = pmap_accessed_bit(pmap);
3622 PG_M = pmap_modified_bit(pmap);
3623 PG_RW = pmap_rw_bit(pmap);
3625 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3626 KASSERT((sva & PDRMASK) == 0,
3627 ("pmap_remove_pde: sva is not 2mpage aligned"));
3628 oldpde = pte_load_clear(pdq);
3630 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
3633 * When workaround_erratum383 is false, a promotion to a 2M
3634 * page mapping does not invalidate the 512 4K page mappings
3635 * from the TLB. Consequently, at this point, the TLB may
3636 * hold both 4K and 2M page mappings. Therefore, the entire
3637 * range of addresses must be invalidated here. In contrast,
3638 * when workaround_erratum383 is true, a promotion does
3639 * invalidate the 512 4K page mappings, and so a single INVLPG
3640 * suffices to invalidate the 2M page mapping.
3642 if ((oldpde & PG_G) != 0) {
3643 if (workaround_erratum383)
3644 pmap_invalidate_page(kernel_pmap, sva);
3646 pmap_invalidate_range(kernel_pmap, sva,
3650 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
3651 if (oldpde & PG_MANAGED) {
3652 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
3653 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
3654 pmap_pvh_free(pvh, pmap, sva);
3656 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3657 va < eva; va += PAGE_SIZE, m++) {
3658 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3661 vm_page_aflag_set(m, PGA_REFERENCED);
3662 if (TAILQ_EMPTY(&m->md.pv_list) &&
3663 TAILQ_EMPTY(&pvh->pv_list))
3664 vm_page_aflag_clear(m, PGA_WRITEABLE);
3665 pmap_delayed_invl_page(m);
3668 if (pmap == kernel_pmap) {
3669 pmap_remove_kernel_pde(pmap, pdq, sva);
3671 mpte = pmap_lookup_pt_page(pmap, sva);
3673 pmap_remove_pt_page(pmap, mpte);
3674 pmap_resident_count_dec(pmap, 1);
3675 KASSERT(mpte->wire_count == NPTEPG,
3676 ("pmap_remove_pde: pte page wire count error"));
3677 mpte->wire_count = 0;
3678 pmap_add_delayed_free_list(mpte, free, FALSE);
3679 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3682 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
3686 * pmap_remove_pte: do the things to unmap a page in a process
3689 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
3690 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
3692 struct md_page *pvh;
3693 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
3696 PG_A = pmap_accessed_bit(pmap);
3697 PG_M = pmap_modified_bit(pmap);
3698 PG_RW = pmap_rw_bit(pmap);
3700 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3701 oldpte = pte_load_clear(ptq);
3703 pmap->pm_stats.wired_count -= 1;
3704 pmap_resident_count_dec(pmap, 1);
3705 if (oldpte & PG_MANAGED) {
3706 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
3707 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3710 vm_page_aflag_set(m, PGA_REFERENCED);
3711 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3712 pmap_pvh_free(&m->md, pmap, va);
3713 if (TAILQ_EMPTY(&m->md.pv_list) &&
3714 (m->flags & PG_FICTITIOUS) == 0) {
3715 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3716 if (TAILQ_EMPTY(&pvh->pv_list))
3717 vm_page_aflag_clear(m, PGA_WRITEABLE);
3719 pmap_delayed_invl_page(m);
3721 return (pmap_unuse_pt(pmap, va, ptepde, free));
3725 * Remove a single page from a process address space
3728 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
3729 struct spglist *free)
3731 struct rwlock *lock;
3732 pt_entry_t *pte, PG_V;
3734 PG_V = pmap_valid_bit(pmap);
3735 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3736 if ((*pde & PG_V) == 0)
3738 pte = pmap_pde_to_pte(pde, va);
3739 if ((*pte & PG_V) == 0)
3742 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
3745 pmap_invalidate_page(pmap, va);
3749 * Remove the given range of addresses from the specified map.
3751 * It is assumed that the start and end are properly
3752 * rounded to the page size.
3755 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3757 struct rwlock *lock;
3758 vm_offset_t va, va_next;
3759 pml4_entry_t *pml4e;
3761 pd_entry_t ptpaddr, *pde;
3762 pt_entry_t *pte, PG_G, PG_V;
3763 struct spglist free;
3766 PG_G = pmap_global_bit(pmap);
3767 PG_V = pmap_valid_bit(pmap);
3770 * Perform an unsynchronized read. This is, however, safe.
3772 if (pmap->pm_stats.resident_count == 0)
3778 pmap_delayed_invl_started();
3782 * special handling of removing one page. a very
3783 * common operation and easy to short circuit some
3786 if (sva + PAGE_SIZE == eva) {
3787 pde = pmap_pde(pmap, sva);
3788 if (pde && (*pde & PG_PS) == 0) {
3789 pmap_remove_page(pmap, sva, pde, &free);
3795 for (; sva < eva; sva = va_next) {
3797 if (pmap->pm_stats.resident_count == 0)
3800 pml4e = pmap_pml4e(pmap, sva);
3801 if ((*pml4e & PG_V) == 0) {
3802 va_next = (sva + NBPML4) & ~PML4MASK;
3808 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
3809 if ((*pdpe & PG_V) == 0) {
3810 va_next = (sva + NBPDP) & ~PDPMASK;
3817 * Calculate index for next page table.
3819 va_next = (sva + NBPDR) & ~PDRMASK;
3823 pde = pmap_pdpe_to_pde(pdpe, sva);
3827 * Weed out invalid mappings.
3833 * Check for large page.
3835 if ((ptpaddr & PG_PS) != 0) {
3837 * Are we removing the entire large page? If not,
3838 * demote the mapping and fall through.
3840 if (sva + NBPDR == va_next && eva >= va_next) {
3842 * The TLB entry for a PG_G mapping is
3843 * invalidated by pmap_remove_pde().
3845 if ((ptpaddr & PG_G) == 0)
3847 pmap_remove_pde(pmap, pde, sva, &free, &lock);
3849 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
3851 /* The large page mapping was destroyed. */
3858 * Limit our scan to either the end of the va represented
3859 * by the current page table page, or to the end of the
3860 * range being removed.
3866 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
3869 if (va != va_next) {
3870 pmap_invalidate_range(pmap, va, sva);
3875 if ((*pte & PG_G) == 0)
3877 else if (va == va_next)
3879 if (pmap_remove_pte(pmap, pte, sva, ptpaddr, &free,
3886 pmap_invalidate_range(pmap, va, sva);
3892 pmap_invalidate_all(pmap);
3894 pmap_delayed_invl_finished();
3895 pmap_free_zero_pages(&free);
3899 * Routine: pmap_remove_all
3901 * Removes this physical page from
3902 * all physical maps in which it resides.
3903 * Reflects back modify bits to the pager.
3906 * Original versions of this routine were very
3907 * inefficient because they iteratively called
3908 * pmap_remove (slow...)
3912 pmap_remove_all(vm_page_t m)
3914 struct md_page *pvh;
3917 struct rwlock *lock;
3918 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
3921 struct spglist free;
3922 int pvh_gen, md_gen;
3924 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3925 ("pmap_remove_all: page %p is not managed", m));
3927 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3928 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
3929 pa_to_pvh(VM_PAGE_TO_PHYS(m));
3932 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
3934 if (!PMAP_TRYLOCK(pmap)) {
3935 pvh_gen = pvh->pv_gen;
3939 if (pvh_gen != pvh->pv_gen) {
3946 pde = pmap_pde(pmap, va);
3947 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
3950 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3952 if (!PMAP_TRYLOCK(pmap)) {
3953 pvh_gen = pvh->pv_gen;
3954 md_gen = m->md.pv_gen;
3958 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
3964 PG_A = pmap_accessed_bit(pmap);
3965 PG_M = pmap_modified_bit(pmap);
3966 PG_RW = pmap_rw_bit(pmap);
3967 pmap_resident_count_dec(pmap, 1);
3968 pde = pmap_pde(pmap, pv->pv_va);
3969 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
3970 " a 2mpage in page %p's pv list", m));
3971 pte = pmap_pde_to_pte(pde, pv->pv_va);
3972 tpte = pte_load_clear(pte);
3974 pmap->pm_stats.wired_count--;
3976 vm_page_aflag_set(m, PGA_REFERENCED);
3979 * Update the vm_page_t clean and reference bits.
3981 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3983 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
3984 pmap_invalidate_page(pmap, pv->pv_va);
3985 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3987 free_pv_entry(pmap, pv);
3990 vm_page_aflag_clear(m, PGA_WRITEABLE);
3992 pmap_delayed_invl_wait(m);
3993 pmap_free_zero_pages(&free);
3997 * pmap_protect_pde: do the things to protect a 2mpage in a process
4000 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
4002 pd_entry_t newpde, oldpde;
4003 vm_offset_t eva, va;
4005 boolean_t anychanged;
4006 pt_entry_t PG_G, PG_M, PG_RW;
4008 PG_G = pmap_global_bit(pmap);
4009 PG_M = pmap_modified_bit(pmap);
4010 PG_RW = pmap_rw_bit(pmap);
4012 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4013 KASSERT((sva & PDRMASK) == 0,
4014 ("pmap_protect_pde: sva is not 2mpage aligned"));
4017 oldpde = newpde = *pde;
4018 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4019 (PG_MANAGED | PG_M | PG_RW)) {
4021 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4022 va < eva; va += PAGE_SIZE, m++)
4025 if ((prot & VM_PROT_WRITE) == 0)
4026 newpde &= ~(PG_RW | PG_M);
4027 if ((prot & VM_PROT_EXECUTE) == 0)
4029 if (newpde != oldpde) {
4030 if (!atomic_cmpset_long(pde, oldpde, newpde))
4032 if (oldpde & PG_G) {
4033 /* See pmap_remove_pde() for explanation. */
4034 if (workaround_erratum383)
4035 pmap_invalidate_page(kernel_pmap, sva);
4037 pmap_invalidate_range(kernel_pmap, sva,
4042 return (anychanged);
4046 * Set the physical protection on the
4047 * specified range of this map as requested.
4050 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4052 vm_offset_t va_next;
4053 pml4_entry_t *pml4e;
4055 pd_entry_t ptpaddr, *pde;
4056 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4057 boolean_t anychanged;
4059 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4060 if (prot == VM_PROT_NONE) {
4061 pmap_remove(pmap, sva, eva);
4065 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4066 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4069 PG_G = pmap_global_bit(pmap);
4070 PG_M = pmap_modified_bit(pmap);
4071 PG_V = pmap_valid_bit(pmap);
4072 PG_RW = pmap_rw_bit(pmap);
4076 for (; sva < eva; sva = va_next) {
4078 pml4e = pmap_pml4e(pmap, sva);
4079 if ((*pml4e & PG_V) == 0) {
4080 va_next = (sva + NBPML4) & ~PML4MASK;
4086 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4087 if ((*pdpe & PG_V) == 0) {
4088 va_next = (sva + NBPDP) & ~PDPMASK;
4094 va_next = (sva + NBPDR) & ~PDRMASK;
4098 pde = pmap_pdpe_to_pde(pdpe, sva);
4102 * Weed out invalid mappings.
4108 * Check for large page.
4110 if ((ptpaddr & PG_PS) != 0) {
4112 * Are we protecting the entire large page? If not,
4113 * demote the mapping and fall through.
4115 if (sva + NBPDR == va_next && eva >= va_next) {
4117 * The TLB entry for a PG_G mapping is
4118 * invalidated by pmap_protect_pde().
4120 if (pmap_protect_pde(pmap, pde, sva, prot))
4123 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4125 * The large page mapping was destroyed.
4134 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4136 pt_entry_t obits, pbits;
4140 obits = pbits = *pte;
4141 if ((pbits & PG_V) == 0)
4144 if ((prot & VM_PROT_WRITE) == 0) {
4145 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4146 (PG_MANAGED | PG_M | PG_RW)) {
4147 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4150 pbits &= ~(PG_RW | PG_M);
4152 if ((prot & VM_PROT_EXECUTE) == 0)
4155 if (pbits != obits) {
4156 if (!atomic_cmpset_long(pte, obits, pbits))
4159 pmap_invalidate_page(pmap, sva);
4166 pmap_invalidate_all(pmap);
4171 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4172 * single page table page (PTP) to a single 2MB page mapping. For promotion
4173 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4174 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4175 * identical characteristics.
4178 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4179 struct rwlock **lockp)
4182 pt_entry_t *firstpte, oldpte, pa, *pte;
4183 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4187 PG_A = pmap_accessed_bit(pmap);
4188 PG_G = pmap_global_bit(pmap);
4189 PG_M = pmap_modified_bit(pmap);
4190 PG_V = pmap_valid_bit(pmap);
4191 PG_RW = pmap_rw_bit(pmap);
4192 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4194 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4197 * Examine the first PTE in the specified PTP. Abort if this PTE is
4198 * either invalid, unused, or does not map the first 4KB physical page
4199 * within a 2MB page.
4201 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4204 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4205 atomic_add_long(&pmap_pde_p_failures, 1);
4206 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4207 " in pmap %p", va, pmap);
4210 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4212 * When PG_M is already clear, PG_RW can be cleared without
4213 * a TLB invalidation.
4215 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4221 * Examine each of the other PTEs in the specified PTP. Abort if this
4222 * PTE maps an unexpected 4KB physical page or does not have identical
4223 * characteristics to the first PTE.
4225 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4226 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4229 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4230 atomic_add_long(&pmap_pde_p_failures, 1);
4231 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4232 " in pmap %p", va, pmap);
4235 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4237 * When PG_M is already clear, PG_RW can be cleared
4238 * without a TLB invalidation.
4240 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4243 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4244 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4245 (va & ~PDRMASK), pmap);
4247 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4248 atomic_add_long(&pmap_pde_p_failures, 1);
4249 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4250 " in pmap %p", va, pmap);
4257 * Save the page table page in its current state until the PDE
4258 * mapping the superpage is demoted by pmap_demote_pde() or
4259 * destroyed by pmap_remove_pde().
4261 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4262 KASSERT(mpte >= vm_page_array &&
4263 mpte < &vm_page_array[vm_page_array_size],
4264 ("pmap_promote_pde: page table page is out of range"));
4265 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4266 ("pmap_promote_pde: page table page's pindex is wrong"));
4267 if (pmap_insert_pt_page(pmap, mpte)) {
4268 atomic_add_long(&pmap_pde_p_failures, 1);
4270 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4276 * Promote the pv entries.
4278 if ((newpde & PG_MANAGED) != 0)
4279 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4282 * Propagate the PAT index to its proper position.
4284 newpde = pmap_swap_pat(pmap, newpde);
4287 * Map the superpage.
4289 if (workaround_erratum383)
4290 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4292 pde_store(pde, PG_PS | newpde);
4294 atomic_add_long(&pmap_pde_promotions, 1);
4295 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4296 " in pmap %p", va, pmap);
4300 * Insert the given physical page (p) at
4301 * the specified virtual address (v) in the
4302 * target physical map with the protection requested.
4304 * If specified, the page will be wired down, meaning
4305 * that the related pte can not be reclaimed.
4307 * NB: This is the only routine which MAY NOT lazy-evaluate
4308 * or lose information. That is, this routine must actually
4309 * insert this page into the given map NOW.
4311 * When destroying both a page table and PV entry, this function
4312 * performs the TLB invalidation before releasing the PV list
4313 * lock, so we do not need pmap_delayed_invl_page() calls here.
4316 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4317 u_int flags, int8_t psind __unused)
4319 struct rwlock *lock;
4321 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4322 pt_entry_t newpte, origpte;
4328 PG_A = pmap_accessed_bit(pmap);
4329 PG_G = pmap_global_bit(pmap);
4330 PG_M = pmap_modified_bit(pmap);
4331 PG_V = pmap_valid_bit(pmap);
4332 PG_RW = pmap_rw_bit(pmap);
4334 va = trunc_page(va);
4335 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4336 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4337 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4339 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4340 va >= kmi.clean_eva,
4341 ("pmap_enter: managed mapping within the clean submap"));
4342 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4343 VM_OBJECT_ASSERT_LOCKED(m->object);
4344 pa = VM_PAGE_TO_PHYS(m);
4345 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4346 if ((flags & VM_PROT_WRITE) != 0)
4348 if ((prot & VM_PROT_WRITE) != 0)
4350 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4351 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4352 if ((prot & VM_PROT_EXECUTE) == 0)
4354 if ((flags & PMAP_ENTER_WIRED) != 0)
4356 if (va < VM_MAXUSER_ADDRESS)
4358 if (pmap == kernel_pmap)
4360 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, 0);
4363 * Set modified bit gratuitously for writeable mappings if
4364 * the page is unmanaged. We do not want to take a fault
4365 * to do the dirty bit accounting for these mappings.
4367 if ((m->oflags & VPO_UNMANAGED) != 0) {
4368 if ((newpte & PG_RW) != 0)
4378 * In the case that a page table page is not
4379 * resident, we are creating it here.
4382 pde = pmap_pde(pmap, va);
4383 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4384 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4385 pte = pmap_pde_to_pte(pde, va);
4386 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4387 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4390 } else if (va < VM_MAXUSER_ADDRESS) {
4392 * Here if the pte page isn't mapped, or if it has been
4395 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4396 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4397 nosleep ? NULL : &lock);
4398 if (mpte == NULL && nosleep) {
4402 return (KERN_RESOURCE_SHORTAGE);
4406 panic("pmap_enter: invalid page directory va=%#lx", va);
4411 * Is the specified virtual address already mapped?
4413 if ((origpte & PG_V) != 0) {
4415 * Wiring change, just update stats. We don't worry about
4416 * wiring PT pages as they remain resident as long as there
4417 * are valid mappings in them. Hence, if a user page is wired,
4418 * the PT page will be also.
4420 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4421 pmap->pm_stats.wired_count++;
4422 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4423 pmap->pm_stats.wired_count--;
4426 * Remove the extra PT page reference.
4430 KASSERT(mpte->wire_count > 0,
4431 ("pmap_enter: missing reference to page table page,"
4436 * Has the physical page changed?
4438 opa = origpte & PG_FRAME;
4441 * No, might be a protection or wiring change.
4443 if ((origpte & PG_MANAGED) != 0) {
4444 newpte |= PG_MANAGED;
4445 if ((newpte & PG_RW) != 0)
4446 vm_page_aflag_set(m, PGA_WRITEABLE);
4448 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4454 * Increment the counters.
4456 if ((newpte & PG_W) != 0)
4457 pmap->pm_stats.wired_count++;
4458 pmap_resident_count_inc(pmap, 1);
4462 * Enter on the PV list if part of our managed memory.
4464 if ((m->oflags & VPO_UNMANAGED) == 0) {
4465 newpte |= PG_MANAGED;
4466 pv = get_pv_entry(pmap, &lock);
4468 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4469 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4471 if ((newpte & PG_RW) != 0)
4472 vm_page_aflag_set(m, PGA_WRITEABLE);
4478 if ((origpte & PG_V) != 0) {
4480 origpte = pte_load_store(pte, newpte);
4481 opa = origpte & PG_FRAME;
4483 if ((origpte & PG_MANAGED) != 0) {
4484 om = PHYS_TO_VM_PAGE(opa);
4485 if ((origpte & (PG_M | PG_RW)) == (PG_M |
4488 if ((origpte & PG_A) != 0)
4489 vm_page_aflag_set(om, PGA_REFERENCED);
4490 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4491 pmap_pvh_free(&om->md, pmap, va);
4492 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4493 TAILQ_EMPTY(&om->md.pv_list) &&
4494 ((om->flags & PG_FICTITIOUS) != 0 ||
4495 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4496 vm_page_aflag_clear(om, PGA_WRITEABLE);
4498 } else if ((newpte & PG_M) == 0 && (origpte & (PG_M |
4499 PG_RW)) == (PG_M | PG_RW)) {
4500 if ((origpte & PG_MANAGED) != 0)
4504 * Although the PTE may still have PG_RW set, TLB
4505 * invalidation may nonetheless be required because
4506 * the PTE no longer has PG_M set.
4508 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4510 * This PTE change does not require TLB invalidation.
4514 if ((origpte & PG_A) != 0)
4515 pmap_invalidate_page(pmap, va);
4517 pte_store(pte, newpte);
4522 * If both the page table page and the reservation are fully
4523 * populated, then attempt promotion.
4525 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4526 pmap_ps_enabled(pmap) &&
4527 (m->flags & PG_FICTITIOUS) == 0 &&
4528 vm_reserv_level_iffullpop(m) == 0)
4529 pmap_promote_pde(pmap, pde, va, &lock);
4534 return (KERN_SUCCESS);
4538 * Tries to create a 2MB page mapping. Returns TRUE if successful and FALSE
4539 * otherwise. Fails if (1) a page table page cannot be allocated without
4540 * blocking, (2) a mapping already exists at the specified virtual address, or
4541 * (3) a pv entry cannot be allocated without reclaiming another pv entry.
4544 pmap_enter_pde(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4545 struct rwlock **lockp)
4547 pd_entry_t *pde, newpde;
4550 struct spglist free;
4552 PG_V = pmap_valid_bit(pmap);
4553 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4555 if ((mpde = pmap_allocpde(pmap, va, NULL)) == NULL) {
4556 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4557 " in pmap %p", va, pmap);
4560 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpde));
4561 pde = &pde[pmap_pde_index(va)];
4562 if ((*pde & PG_V) != 0) {
4563 KASSERT(mpde->wire_count > 1,
4564 ("pmap_enter_pde: mpde's wire count is too low"));
4566 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4567 " in pmap %p", va, pmap);
4570 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
4572 if ((m->oflags & VPO_UNMANAGED) == 0) {
4573 newpde |= PG_MANAGED;
4576 * Abort this mapping if its PV entry could not be created.
4578 if (!pmap_pv_insert_pde(pmap, va, VM_PAGE_TO_PHYS(m),
4581 if (pmap_unwire_ptp(pmap, va, mpde, &free)) {
4583 * Although "va" is not mapped, paging-
4584 * structure caches could nonetheless have
4585 * entries that refer to the freed page table
4586 * pages. Invalidate those entries.
4588 pmap_invalidate_page(pmap, va);
4589 pmap_free_zero_pages(&free);
4591 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4592 " in pmap %p", va, pmap);
4596 if ((prot & VM_PROT_EXECUTE) == 0)
4598 if (va < VM_MAXUSER_ADDRESS)
4602 * Increment counters.
4604 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
4607 * Map the superpage.
4609 pde_store(pde, newpde);
4611 atomic_add_long(&pmap_pde_mappings, 1);
4612 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
4613 " in pmap %p", va, pmap);
4618 * Maps a sequence of resident pages belonging to the same object.
4619 * The sequence begins with the given page m_start. This page is
4620 * mapped at the given virtual address start. Each subsequent page is
4621 * mapped at a virtual address that is offset from start by the same
4622 * amount as the page is offset from m_start within the object. The
4623 * last page in the sequence is the page with the largest offset from
4624 * m_start that can be mapped at a virtual address less than the given
4625 * virtual address end. Not every virtual page between start and end
4626 * is mapped; only those for which a resident page exists with the
4627 * corresponding offset from m_start are mapped.
4630 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
4631 vm_page_t m_start, vm_prot_t prot)
4633 struct rwlock *lock;
4636 vm_pindex_t diff, psize;
4638 VM_OBJECT_ASSERT_LOCKED(m_start->object);
4640 psize = atop(end - start);
4645 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
4646 va = start + ptoa(diff);
4647 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
4648 m->psind == 1 && pmap_ps_enabled(pmap) &&
4649 pmap_enter_pde(pmap, va, m, prot, &lock))
4650 m = &m[NBPDR / PAGE_SIZE - 1];
4652 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
4654 m = TAILQ_NEXT(m, listq);
4662 * this code makes some *MAJOR* assumptions:
4663 * 1. Current pmap & pmap exists.
4666 * 4. No page table pages.
4667 * but is *MUCH* faster than pmap_enter...
4671 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
4673 struct rwlock *lock;
4677 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
4684 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
4685 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
4687 struct spglist free;
4688 pt_entry_t *pte, PG_V;
4691 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
4692 (m->oflags & VPO_UNMANAGED) != 0,
4693 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
4694 PG_V = pmap_valid_bit(pmap);
4695 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4698 * In the case that a page table page is not
4699 * resident, we are creating it here.
4701 if (va < VM_MAXUSER_ADDRESS) {
4702 vm_pindex_t ptepindex;
4706 * Calculate pagetable page index
4708 ptepindex = pmap_pde_pindex(va);
4709 if (mpte && (mpte->pindex == ptepindex)) {
4713 * Get the page directory entry
4715 ptepa = pmap_pde(pmap, va);
4718 * If the page table page is mapped, we just increment
4719 * the hold count, and activate it. Otherwise, we
4720 * attempt to allocate a page table page. If this
4721 * attempt fails, we don't retry. Instead, we give up.
4723 if (ptepa && (*ptepa & PG_V) != 0) {
4726 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
4730 * Pass NULL instead of the PV list lock
4731 * pointer, because we don't intend to sleep.
4733 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
4738 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
4739 pte = &pte[pmap_pte_index(va)];
4753 * Enter on the PV list if part of our managed memory.
4755 if ((m->oflags & VPO_UNMANAGED) == 0 &&
4756 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
4759 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
4761 * Although "va" is not mapped, paging-
4762 * structure caches could nonetheless have
4763 * entries that refer to the freed page table
4764 * pages. Invalidate those entries.
4766 pmap_invalidate_page(pmap, va);
4767 pmap_free_zero_pages(&free);
4775 * Increment counters
4777 pmap_resident_count_inc(pmap, 1);
4779 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
4780 if ((prot & VM_PROT_EXECUTE) == 0)
4784 * Now validate mapping with RO protection
4786 if ((m->oflags & VPO_UNMANAGED) != 0)
4787 pte_store(pte, pa | PG_V | PG_U);
4789 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
4794 * Make a temporary mapping for a physical address. This is only intended
4795 * to be used for panic dumps.
4798 pmap_kenter_temporary(vm_paddr_t pa, int i)
4802 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
4803 pmap_kenter(va, pa);
4805 return ((void *)crashdumpmap);
4809 * This code maps large physical mmap regions into the
4810 * processor address space. Note that some shortcuts
4811 * are taken, but the code works.
4814 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
4815 vm_pindex_t pindex, vm_size_t size)
4818 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
4819 vm_paddr_t pa, ptepa;
4823 PG_A = pmap_accessed_bit(pmap);
4824 PG_M = pmap_modified_bit(pmap);
4825 PG_V = pmap_valid_bit(pmap);
4826 PG_RW = pmap_rw_bit(pmap);
4828 VM_OBJECT_ASSERT_WLOCKED(object);
4829 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
4830 ("pmap_object_init_pt: non-device object"));
4831 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
4832 if (!pmap_ps_enabled(pmap))
4834 if (!vm_object_populate(object, pindex, pindex + atop(size)))
4836 p = vm_page_lookup(object, pindex);
4837 KASSERT(p->valid == VM_PAGE_BITS_ALL,
4838 ("pmap_object_init_pt: invalid page %p", p));
4839 pat_mode = p->md.pat_mode;
4842 * Abort the mapping if the first page is not physically
4843 * aligned to a 2MB page boundary.
4845 ptepa = VM_PAGE_TO_PHYS(p);
4846 if (ptepa & (NBPDR - 1))
4850 * Skip the first page. Abort the mapping if the rest of
4851 * the pages are not physically contiguous or have differing
4852 * memory attributes.
4854 p = TAILQ_NEXT(p, listq);
4855 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
4857 KASSERT(p->valid == VM_PAGE_BITS_ALL,
4858 ("pmap_object_init_pt: invalid page %p", p));
4859 if (pa != VM_PAGE_TO_PHYS(p) ||
4860 pat_mode != p->md.pat_mode)
4862 p = TAILQ_NEXT(p, listq);
4866 * Map using 2MB pages. Since "ptepa" is 2M aligned and
4867 * "size" is a multiple of 2M, adding the PAT setting to "pa"
4868 * will not affect the termination of this loop.
4871 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
4872 pa < ptepa + size; pa += NBPDR) {
4873 pdpg = pmap_allocpde(pmap, addr, NULL);
4876 * The creation of mappings below is only an
4877 * optimization. If a page directory page
4878 * cannot be allocated without blocking,
4879 * continue on to the next mapping rather than
4885 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4886 pde = &pde[pmap_pde_index(addr)];
4887 if ((*pde & PG_V) == 0) {
4888 pde_store(pde, pa | PG_PS | PG_M | PG_A |
4889 PG_U | PG_RW | PG_V);
4890 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
4891 atomic_add_long(&pmap_pde_mappings, 1);
4893 /* Continue on if the PDE is already valid. */
4895 KASSERT(pdpg->wire_count > 0,
4896 ("pmap_object_init_pt: missing reference "
4897 "to page directory page, va: 0x%lx", addr));
4906 * Clear the wired attribute from the mappings for the specified range of
4907 * addresses in the given pmap. Every valid mapping within that range
4908 * must have the wired attribute set. In contrast, invalid mappings
4909 * cannot have the wired attribute set, so they are ignored.
4911 * The wired attribute of the page table entry is not a hardware
4912 * feature, so there is no need to invalidate any TLB entries.
4913 * Since pmap_demote_pde() for the wired entry must never fail,
4914 * pmap_delayed_invl_started()/finished() calls around the
4915 * function are not needed.
4918 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4920 vm_offset_t va_next;
4921 pml4_entry_t *pml4e;
4924 pt_entry_t *pte, PG_V;
4926 PG_V = pmap_valid_bit(pmap);
4928 for (; sva < eva; sva = va_next) {
4929 pml4e = pmap_pml4e(pmap, sva);
4930 if ((*pml4e & PG_V) == 0) {
4931 va_next = (sva + NBPML4) & ~PML4MASK;
4936 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4937 if ((*pdpe & PG_V) == 0) {
4938 va_next = (sva + NBPDP) & ~PDPMASK;
4943 va_next = (sva + NBPDR) & ~PDRMASK;
4946 pde = pmap_pdpe_to_pde(pdpe, sva);
4947 if ((*pde & PG_V) == 0)
4949 if ((*pde & PG_PS) != 0) {
4950 if ((*pde & PG_W) == 0)
4951 panic("pmap_unwire: pde %#jx is missing PG_W",
4955 * Are we unwiring the entire large page? If not,
4956 * demote the mapping and fall through.
4958 if (sva + NBPDR == va_next && eva >= va_next) {
4959 atomic_clear_long(pde, PG_W);
4960 pmap->pm_stats.wired_count -= NBPDR /
4963 } else if (!pmap_demote_pde(pmap, pde, sva))
4964 panic("pmap_unwire: demotion failed");
4968 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4970 if ((*pte & PG_V) == 0)
4972 if ((*pte & PG_W) == 0)
4973 panic("pmap_unwire: pte %#jx is missing PG_W",
4977 * PG_W must be cleared atomically. Although the pmap
4978 * lock synchronizes access to PG_W, another processor
4979 * could be setting PG_M and/or PG_A concurrently.
4981 atomic_clear_long(pte, PG_W);
4982 pmap->pm_stats.wired_count--;
4989 * Copy the range specified by src_addr/len
4990 * from the source map to the range dst_addr/len
4991 * in the destination map.
4993 * This routine is only advisory and need not do anything.
4997 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
4998 vm_offset_t src_addr)
5000 struct rwlock *lock;
5001 struct spglist free;
5003 vm_offset_t end_addr = src_addr + len;
5004 vm_offset_t va_next;
5005 pt_entry_t PG_A, PG_M, PG_V;
5007 if (dst_addr != src_addr)
5010 if (dst_pmap->pm_type != src_pmap->pm_type)
5014 * EPT page table entries that require emulation of A/D bits are
5015 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5016 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5017 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5018 * implementations flag an EPT misconfiguration for exec-only
5019 * mappings we skip this function entirely for emulated pmaps.
5021 if (pmap_emulate_ad_bits(dst_pmap))
5025 if (dst_pmap < src_pmap) {
5026 PMAP_LOCK(dst_pmap);
5027 PMAP_LOCK(src_pmap);
5029 PMAP_LOCK(src_pmap);
5030 PMAP_LOCK(dst_pmap);
5033 PG_A = pmap_accessed_bit(dst_pmap);
5034 PG_M = pmap_modified_bit(dst_pmap);
5035 PG_V = pmap_valid_bit(dst_pmap);
5037 for (addr = src_addr; addr < end_addr; addr = va_next) {
5038 pt_entry_t *src_pte, *dst_pte;
5039 vm_page_t dstmpde, dstmpte, srcmpte;
5040 pml4_entry_t *pml4e;
5042 pd_entry_t srcptepaddr, *pde;
5044 KASSERT(addr < UPT_MIN_ADDRESS,
5045 ("pmap_copy: invalid to pmap_copy page tables"));
5047 pml4e = pmap_pml4e(src_pmap, addr);
5048 if ((*pml4e & PG_V) == 0) {
5049 va_next = (addr + NBPML4) & ~PML4MASK;
5055 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5056 if ((*pdpe & PG_V) == 0) {
5057 va_next = (addr + NBPDP) & ~PDPMASK;
5063 va_next = (addr + NBPDR) & ~PDRMASK;
5067 pde = pmap_pdpe_to_pde(pdpe, addr);
5069 if (srcptepaddr == 0)
5072 if (srcptepaddr & PG_PS) {
5073 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5075 dstmpde = pmap_allocpde(dst_pmap, addr, NULL);
5076 if (dstmpde == NULL)
5078 pde = (pd_entry_t *)
5079 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpde));
5080 pde = &pde[pmap_pde_index(addr)];
5081 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5082 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr &
5083 PG_PS_FRAME, &lock))) {
5084 *pde = srcptepaddr & ~PG_W;
5085 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5086 atomic_add_long(&pmap_pde_mappings, 1);
5088 dstmpde->wire_count--;
5092 srcptepaddr &= PG_FRAME;
5093 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5094 KASSERT(srcmpte->wire_count > 0,
5095 ("pmap_copy: source page table page is unused"));
5097 if (va_next > end_addr)
5100 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5101 src_pte = &src_pte[pmap_pte_index(addr)];
5103 while (addr < va_next) {
5107 * we only virtual copy managed pages
5109 if ((ptetemp & PG_MANAGED) != 0) {
5110 if (dstmpte != NULL &&
5111 dstmpte->pindex == pmap_pde_pindex(addr))
5112 dstmpte->wire_count++;
5113 else if ((dstmpte = pmap_allocpte(dst_pmap,
5114 addr, NULL)) == NULL)
5116 dst_pte = (pt_entry_t *)
5117 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5118 dst_pte = &dst_pte[pmap_pte_index(addr)];
5119 if (*dst_pte == 0 &&
5120 pmap_try_insert_pv_entry(dst_pmap, addr,
5121 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5124 * Clear the wired, modified, and
5125 * accessed (referenced) bits
5128 *dst_pte = ptetemp & ~(PG_W | PG_M |
5130 pmap_resident_count_inc(dst_pmap, 1);
5133 if (pmap_unwire_ptp(dst_pmap, addr,
5136 * Although "addr" is not
5137 * mapped, paging-structure
5138 * caches could nonetheless
5139 * have entries that refer to
5140 * the freed page table pages.
5141 * Invalidate those entries.
5143 pmap_invalidate_page(dst_pmap,
5145 pmap_free_zero_pages(&free);
5149 if (dstmpte->wire_count >= srcmpte->wire_count)
5159 PMAP_UNLOCK(src_pmap);
5160 PMAP_UNLOCK(dst_pmap);
5164 * pmap_zero_page zeros the specified hardware page by mapping
5165 * the page into KVM and using bzero to clear its contents.
5168 pmap_zero_page(vm_page_t m)
5170 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5172 pagezero((void *)va);
5176 * pmap_zero_page_area zeros the specified hardware page by mapping
5177 * the page into KVM and using bzero to clear its contents.
5179 * off and size may not cover an area beyond a single hardware page.
5182 pmap_zero_page_area(vm_page_t m, int off, int size)
5184 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5186 if (off == 0 && size == PAGE_SIZE)
5187 pagezero((void *)va);
5189 bzero((char *)va + off, size);
5193 * pmap_zero_page_idle zeros the specified hardware page by mapping
5194 * the page into KVM and using bzero to clear its contents. This
5195 * is intended to be called from the vm_pagezero process only and
5199 pmap_zero_page_idle(vm_page_t m)
5201 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5203 pagezero((void *)va);
5207 * pmap_copy_page copies the specified (machine independent)
5208 * page by mapping the page into virtual memory and using
5209 * bcopy to copy the page, one machine dependent page at a
5213 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5215 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5216 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5218 pagecopy((void *)src, (void *)dst);
5221 int unmapped_buf_allowed = 1;
5224 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5225 vm_offset_t b_offset, int xfersize)
5229 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5233 while (xfersize > 0) {
5234 a_pg_offset = a_offset & PAGE_MASK;
5235 pages[0] = ma[a_offset >> PAGE_SHIFT];
5236 b_pg_offset = b_offset & PAGE_MASK;
5237 pages[1] = mb[b_offset >> PAGE_SHIFT];
5238 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5239 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5240 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5241 a_cp = (char *)vaddr[0] + a_pg_offset;
5242 b_cp = (char *)vaddr[1] + b_pg_offset;
5243 bcopy(a_cp, b_cp, cnt);
5244 if (__predict_false(mapped))
5245 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5253 * Returns true if the pmap's pv is one of the first
5254 * 16 pvs linked to from this page. This count may
5255 * be changed upwards or downwards in the future; it
5256 * is only necessary that true be returned for a small
5257 * subset of pmaps for proper page aging.
5260 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5262 struct md_page *pvh;
5263 struct rwlock *lock;
5268 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5269 ("pmap_page_exists_quick: page %p is not managed", m));
5271 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5273 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5274 if (PV_PMAP(pv) == pmap) {
5282 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5283 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5284 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5285 if (PV_PMAP(pv) == pmap) {
5299 * pmap_page_wired_mappings:
5301 * Return the number of managed mappings to the given physical page
5305 pmap_page_wired_mappings(vm_page_t m)
5307 struct rwlock *lock;
5308 struct md_page *pvh;
5312 int count, md_gen, pvh_gen;
5314 if ((m->oflags & VPO_UNMANAGED) != 0)
5316 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5320 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5322 if (!PMAP_TRYLOCK(pmap)) {
5323 md_gen = m->md.pv_gen;
5327 if (md_gen != m->md.pv_gen) {
5332 pte = pmap_pte(pmap, pv->pv_va);
5333 if ((*pte & PG_W) != 0)
5337 if ((m->flags & PG_FICTITIOUS) == 0) {
5338 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5339 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5341 if (!PMAP_TRYLOCK(pmap)) {
5342 md_gen = m->md.pv_gen;
5343 pvh_gen = pvh->pv_gen;
5347 if (md_gen != m->md.pv_gen ||
5348 pvh_gen != pvh->pv_gen) {
5353 pte = pmap_pde(pmap, pv->pv_va);
5354 if ((*pte & PG_W) != 0)
5364 * Returns TRUE if the given page is mapped individually or as part of
5365 * a 2mpage. Otherwise, returns FALSE.
5368 pmap_page_is_mapped(vm_page_t m)
5370 struct rwlock *lock;
5373 if ((m->oflags & VPO_UNMANAGED) != 0)
5375 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5377 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5378 ((m->flags & PG_FICTITIOUS) == 0 &&
5379 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5385 * Destroy all managed, non-wired mappings in the given user-space
5386 * pmap. This pmap cannot be active on any processor besides the
5389 * This function cannot be applied to the kernel pmap. Moreover, it
5390 * is not intended for general use. It is only to be used during
5391 * process termination. Consequently, it can be implemented in ways
5392 * that make it faster than pmap_remove(). First, it can more quickly
5393 * destroy mappings by iterating over the pmap's collection of PV
5394 * entries, rather than searching the page table. Second, it doesn't
5395 * have to test and clear the page table entries atomically, because
5396 * no processor is currently accessing the user address space. In
5397 * particular, a page table entry's dirty bit won't change state once
5398 * this function starts.
5401 pmap_remove_pages(pmap_t pmap)
5404 pt_entry_t *pte, tpte;
5405 pt_entry_t PG_M, PG_RW, PG_V;
5406 struct spglist free;
5407 vm_page_t m, mpte, mt;
5409 struct md_page *pvh;
5410 struct pv_chunk *pc, *npc;
5411 struct rwlock *lock;
5413 uint64_t inuse, bitmask;
5414 int allfree, field, freed, idx;
5415 boolean_t superpage;
5419 * Assert that the given pmap is only active on the current
5420 * CPU. Unfortunately, we cannot block another CPU from
5421 * activating the pmap while this function is executing.
5423 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5426 cpuset_t other_cpus;
5428 other_cpus = all_cpus;
5430 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5431 CPU_AND(&other_cpus, &pmap->pm_active);
5433 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5438 PG_M = pmap_modified_bit(pmap);
5439 PG_V = pmap_valid_bit(pmap);
5440 PG_RW = pmap_rw_bit(pmap);
5444 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5447 for (field = 0; field < _NPCM; field++) {
5448 inuse = ~pc->pc_map[field] & pc_freemask[field];
5449 while (inuse != 0) {
5451 bitmask = 1UL << bit;
5452 idx = field * 64 + bit;
5453 pv = &pc->pc_pventry[idx];
5456 pte = pmap_pdpe(pmap, pv->pv_va);
5458 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5460 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5463 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5465 pte = &pte[pmap_pte_index(pv->pv_va)];
5469 * Keep track whether 'tpte' is a
5470 * superpage explicitly instead of
5471 * relying on PG_PS being set.
5473 * This is because PG_PS is numerically
5474 * identical to PG_PTE_PAT and thus a
5475 * regular page could be mistaken for
5481 if ((tpte & PG_V) == 0) {
5482 panic("bad pte va %lx pte %lx",
5487 * We cannot remove wired pages from a process' mapping at this time
5495 pa = tpte & PG_PS_FRAME;
5497 pa = tpte & PG_FRAME;
5499 m = PHYS_TO_VM_PAGE(pa);
5500 KASSERT(m->phys_addr == pa,
5501 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5502 m, (uintmax_t)m->phys_addr,
5505 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5506 m < &vm_page_array[vm_page_array_size],
5507 ("pmap_remove_pages: bad tpte %#jx",
5513 * Update the vm_page_t clean/reference bits.
5515 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5517 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5523 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5526 pc->pc_map[field] |= bitmask;
5528 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
5529 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
5530 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5532 if (TAILQ_EMPTY(&pvh->pv_list)) {
5533 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5534 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
5535 TAILQ_EMPTY(&mt->md.pv_list))
5536 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5538 mpte = pmap_lookup_pt_page(pmap, pv->pv_va);
5540 pmap_remove_pt_page(pmap, mpte);
5541 pmap_resident_count_dec(pmap, 1);
5542 KASSERT(mpte->wire_count == NPTEPG,
5543 ("pmap_remove_pages: pte page wire count error"));
5544 mpte->wire_count = 0;
5545 pmap_add_delayed_free_list(mpte, &free, FALSE);
5546 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
5549 pmap_resident_count_dec(pmap, 1);
5550 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5552 if ((m->aflags & PGA_WRITEABLE) != 0 &&
5553 TAILQ_EMPTY(&m->md.pv_list) &&
5554 (m->flags & PG_FICTITIOUS) == 0) {
5555 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5556 if (TAILQ_EMPTY(&pvh->pv_list))
5557 vm_page_aflag_clear(m, PGA_WRITEABLE);
5560 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
5564 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5565 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5566 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5568 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5574 pmap_invalidate_all(pmap);
5576 pmap_free_zero_pages(&free);
5580 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
5582 struct rwlock *lock;
5584 struct md_page *pvh;
5585 pt_entry_t *pte, mask;
5586 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5588 int md_gen, pvh_gen;
5592 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5595 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5597 if (!PMAP_TRYLOCK(pmap)) {
5598 md_gen = m->md.pv_gen;
5602 if (md_gen != m->md.pv_gen) {
5607 pte = pmap_pte(pmap, pv->pv_va);
5610 PG_M = pmap_modified_bit(pmap);
5611 PG_RW = pmap_rw_bit(pmap);
5612 mask |= PG_RW | PG_M;
5615 PG_A = pmap_accessed_bit(pmap);
5616 PG_V = pmap_valid_bit(pmap);
5617 mask |= PG_V | PG_A;
5619 rv = (*pte & mask) == mask;
5624 if ((m->flags & PG_FICTITIOUS) == 0) {
5625 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5626 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5628 if (!PMAP_TRYLOCK(pmap)) {
5629 md_gen = m->md.pv_gen;
5630 pvh_gen = pvh->pv_gen;
5634 if (md_gen != m->md.pv_gen ||
5635 pvh_gen != pvh->pv_gen) {
5640 pte = pmap_pde(pmap, pv->pv_va);
5643 PG_M = pmap_modified_bit(pmap);
5644 PG_RW = pmap_rw_bit(pmap);
5645 mask |= PG_RW | PG_M;
5648 PG_A = pmap_accessed_bit(pmap);
5649 PG_V = pmap_valid_bit(pmap);
5650 mask |= PG_V | PG_A;
5652 rv = (*pte & mask) == mask;
5666 * Return whether or not the specified physical page was modified
5667 * in any physical maps.
5670 pmap_is_modified(vm_page_t m)
5673 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5674 ("pmap_is_modified: page %p is not managed", m));
5677 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5678 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
5679 * is clear, no PTEs can have PG_M set.
5681 VM_OBJECT_ASSERT_WLOCKED(m->object);
5682 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
5684 return (pmap_page_test_mappings(m, FALSE, TRUE));
5688 * pmap_is_prefaultable:
5690 * Return whether or not the specified virtual address is eligible
5694 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
5697 pt_entry_t *pte, PG_V;
5700 PG_V = pmap_valid_bit(pmap);
5703 pde = pmap_pde(pmap, addr);
5704 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
5705 pte = pmap_pde_to_pte(pde, addr);
5706 rv = (*pte & PG_V) == 0;
5713 * pmap_is_referenced:
5715 * Return whether or not the specified physical page was referenced
5716 * in any physical maps.
5719 pmap_is_referenced(vm_page_t m)
5722 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5723 ("pmap_is_referenced: page %p is not managed", m));
5724 return (pmap_page_test_mappings(m, TRUE, FALSE));
5728 * Clear the write and modified bits in each of the given page's mappings.
5731 pmap_remove_write(vm_page_t m)
5733 struct md_page *pvh;
5735 struct rwlock *lock;
5736 pv_entry_t next_pv, pv;
5738 pt_entry_t oldpte, *pte, PG_M, PG_RW;
5740 int pvh_gen, md_gen;
5742 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5743 ("pmap_remove_write: page %p is not managed", m));
5746 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5747 * set by another thread while the object is locked. Thus,
5748 * if PGA_WRITEABLE is clear, no page table entries need updating.
5750 VM_OBJECT_ASSERT_WLOCKED(m->object);
5751 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
5753 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5754 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
5755 pa_to_pvh(VM_PAGE_TO_PHYS(m));
5758 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
5760 if (!PMAP_TRYLOCK(pmap)) {
5761 pvh_gen = pvh->pv_gen;
5765 if (pvh_gen != pvh->pv_gen) {
5771 PG_RW = pmap_rw_bit(pmap);
5773 pde = pmap_pde(pmap, va);
5774 if ((*pde & PG_RW) != 0)
5775 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
5776 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
5777 ("inconsistent pv lock %p %p for page %p",
5778 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
5781 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5783 if (!PMAP_TRYLOCK(pmap)) {
5784 pvh_gen = pvh->pv_gen;
5785 md_gen = m->md.pv_gen;
5789 if (pvh_gen != pvh->pv_gen ||
5790 md_gen != m->md.pv_gen) {
5796 PG_M = pmap_modified_bit(pmap);
5797 PG_RW = pmap_rw_bit(pmap);
5798 pde = pmap_pde(pmap, pv->pv_va);
5799 KASSERT((*pde & PG_PS) == 0,
5800 ("pmap_remove_write: found a 2mpage in page %p's pv list",
5802 pte = pmap_pde_to_pte(pde, pv->pv_va);
5805 if (oldpte & PG_RW) {
5806 if (!atomic_cmpset_long(pte, oldpte, oldpte &
5809 if ((oldpte & PG_M) != 0)
5811 pmap_invalidate_page(pmap, pv->pv_va);
5816 vm_page_aflag_clear(m, PGA_WRITEABLE);
5817 pmap_delayed_invl_wait(m);
5820 static __inline boolean_t
5821 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
5824 if (!pmap_emulate_ad_bits(pmap))
5827 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
5830 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
5831 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
5832 * if the EPT_PG_WRITE bit is set.
5834 if ((pte & EPT_PG_WRITE) != 0)
5838 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
5840 if ((pte & EPT_PG_EXECUTE) == 0 ||
5841 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
5847 #define PMAP_TS_REFERENCED_MAX 5
5850 * pmap_ts_referenced:
5852 * Return a count of reference bits for a page, clearing those bits.
5853 * It is not necessary for every reference bit to be cleared, but it
5854 * is necessary that 0 only be returned when there are truly no
5855 * reference bits set.
5857 * XXX: The exact number of bits to check and clear is a matter that
5858 * should be tested and standardized at some point in the future for
5859 * optimal aging of shared pages.
5861 * As an optimization, update the page's dirty field if a modified bit is
5862 * found while counting reference bits. This opportunistic update can be
5863 * performed at low cost and can eliminate the need for some future calls
5864 * to pmap_is_modified(). However, since this function stops after
5865 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
5866 * dirty pages. Those dirty pages will only be detected by a future call
5867 * to pmap_is_modified().
5869 * A DI block is not needed within this function, because
5870 * invalidations are performed before the PV list lock is
5874 pmap_ts_referenced(vm_page_t m)
5876 struct md_page *pvh;
5879 struct rwlock *lock;
5880 pd_entry_t oldpde, *pde;
5881 pt_entry_t *pte, PG_A, PG_M, PG_RW;
5884 int cleared, md_gen, not_cleared, pvh_gen;
5885 struct spglist free;
5888 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5889 ("pmap_ts_referenced: page %p is not managed", m));
5892 pa = VM_PAGE_TO_PHYS(m);
5893 lock = PHYS_TO_PV_LIST_LOCK(pa);
5894 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
5898 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
5899 goto small_mappings;
5905 if (!PMAP_TRYLOCK(pmap)) {
5906 pvh_gen = pvh->pv_gen;
5910 if (pvh_gen != pvh->pv_gen) {
5915 PG_A = pmap_accessed_bit(pmap);
5916 PG_M = pmap_modified_bit(pmap);
5917 PG_RW = pmap_rw_bit(pmap);
5919 pde = pmap_pde(pmap, pv->pv_va);
5921 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5923 * Although "oldpde" is mapping a 2MB page, because
5924 * this function is called at a 4KB page granularity,
5925 * we only update the 4KB page under test.
5929 if ((*pde & PG_A) != 0) {
5931 * Since this reference bit is shared by 512 4KB
5932 * pages, it should not be cleared every time it is
5933 * tested. Apply a simple "hash" function on the
5934 * physical page number, the virtual superpage number,
5935 * and the pmap address to select one 4KB page out of
5936 * the 512 on which testing the reference bit will
5937 * result in clearing that reference bit. This
5938 * function is designed to avoid the selection of the
5939 * same 4KB page for every 2MB page mapping.
5941 * On demotion, a mapping that hasn't been referenced
5942 * is simply destroyed. To avoid the possibility of a
5943 * subsequent page fault on a demoted wired mapping,
5944 * always leave its reference bit set. Moreover,
5945 * since the superpage is wired, the current state of
5946 * its reference bit won't affect page replacement.
5948 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
5949 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
5950 (*pde & PG_W) == 0) {
5951 if (safe_to_clear_referenced(pmap, oldpde)) {
5952 atomic_clear_long(pde, PG_A);
5953 pmap_invalidate_page(pmap, pv->pv_va);
5955 } else if (pmap_demote_pde_locked(pmap, pde,
5956 pv->pv_va, &lock)) {
5958 * Remove the mapping to a single page
5959 * so that a subsequent access may
5960 * repromote. Since the underlying
5961 * page table page is fully populated,
5962 * this removal never frees a page
5966 va += VM_PAGE_TO_PHYS(m) - (oldpde &
5968 pte = pmap_pde_to_pte(pde, va);
5969 pmap_remove_pte(pmap, pte, va, *pde,
5971 pmap_invalidate_page(pmap, va);
5977 * The superpage mapping was removed
5978 * entirely and therefore 'pv' is no
5986 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
5987 ("inconsistent pv lock %p %p for page %p",
5988 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
5993 /* Rotate the PV list if it has more than one entry. */
5994 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
5995 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5996 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5999 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6001 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6003 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6010 if (!PMAP_TRYLOCK(pmap)) {
6011 pvh_gen = pvh->pv_gen;
6012 md_gen = m->md.pv_gen;
6016 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6021 PG_A = pmap_accessed_bit(pmap);
6022 PG_M = pmap_modified_bit(pmap);
6023 PG_RW = pmap_rw_bit(pmap);
6024 pde = pmap_pde(pmap, pv->pv_va);
6025 KASSERT((*pde & PG_PS) == 0,
6026 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6028 pte = pmap_pde_to_pte(pde, pv->pv_va);
6029 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6031 if ((*pte & PG_A) != 0) {
6032 if (safe_to_clear_referenced(pmap, *pte)) {
6033 atomic_clear_long(pte, PG_A);
6034 pmap_invalidate_page(pmap, pv->pv_va);
6036 } else if ((*pte & PG_W) == 0) {
6038 * Wired pages cannot be paged out so
6039 * doing accessed bit emulation for
6040 * them is wasted effort. We do the
6041 * hard work for unwired pages only.
6043 pmap_remove_pte(pmap, pte, pv->pv_va,
6044 *pde, &free, &lock);
6045 pmap_invalidate_page(pmap, pv->pv_va);
6050 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6051 ("inconsistent pv lock %p %p for page %p",
6052 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6057 /* Rotate the PV list if it has more than one entry. */
6058 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6059 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6060 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6063 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6064 not_cleared < PMAP_TS_REFERENCED_MAX);
6067 pmap_free_zero_pages(&free);
6068 return (cleared + not_cleared);
6072 * Apply the given advice to the specified range of addresses within the
6073 * given pmap. Depending on the advice, clear the referenced and/or
6074 * modified flags in each mapping and set the mapped page's dirty field.
6077 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6079 struct rwlock *lock;
6080 pml4_entry_t *pml4e;
6082 pd_entry_t oldpde, *pde;
6083 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6084 vm_offset_t va, va_next;
6086 boolean_t anychanged;
6088 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6092 * A/D bit emulation requires an alternate code path when clearing
6093 * the modified and accessed bits below. Since this function is
6094 * advisory in nature we skip it entirely for pmaps that require
6095 * A/D bit emulation.
6097 if (pmap_emulate_ad_bits(pmap))
6100 PG_A = pmap_accessed_bit(pmap);
6101 PG_G = pmap_global_bit(pmap);
6102 PG_M = pmap_modified_bit(pmap);
6103 PG_V = pmap_valid_bit(pmap);
6104 PG_RW = pmap_rw_bit(pmap);
6106 pmap_delayed_invl_started();
6108 for (; sva < eva; sva = va_next) {
6109 pml4e = pmap_pml4e(pmap, sva);
6110 if ((*pml4e & PG_V) == 0) {
6111 va_next = (sva + NBPML4) & ~PML4MASK;
6116 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6117 if ((*pdpe & PG_V) == 0) {
6118 va_next = (sva + NBPDP) & ~PDPMASK;
6123 va_next = (sva + NBPDR) & ~PDRMASK;
6126 pde = pmap_pdpe_to_pde(pdpe, sva);
6128 if ((oldpde & PG_V) == 0)
6130 else if ((oldpde & PG_PS) != 0) {
6131 if ((oldpde & PG_MANAGED) == 0)
6134 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6139 * The large page mapping was destroyed.
6145 * Unless the page mappings are wired, remove the
6146 * mapping to a single page so that a subsequent
6147 * access may repromote. Since the underlying page
6148 * table page is fully populated, this removal never
6149 * frees a page table page.
6151 if ((oldpde & PG_W) == 0) {
6152 pte = pmap_pde_to_pte(pde, sva);
6153 KASSERT((*pte & PG_V) != 0,
6154 ("pmap_advise: invalid PTE"));
6155 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6165 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6167 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6169 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6170 if (advice == MADV_DONTNEED) {
6172 * Future calls to pmap_is_modified()
6173 * can be avoided by making the page
6176 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6179 atomic_clear_long(pte, PG_M | PG_A);
6180 } else if ((*pte & PG_A) != 0)
6181 atomic_clear_long(pte, PG_A);
6185 if ((*pte & PG_G) != 0) {
6192 if (va != va_next) {
6193 pmap_invalidate_range(pmap, va, sva);
6198 pmap_invalidate_range(pmap, va, sva);
6201 pmap_invalidate_all(pmap);
6203 pmap_delayed_invl_finished();
6207 * Clear the modify bits on the specified physical page.
6210 pmap_clear_modify(vm_page_t m)
6212 struct md_page *pvh;
6214 pv_entry_t next_pv, pv;
6215 pd_entry_t oldpde, *pde;
6216 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6217 struct rwlock *lock;
6219 int md_gen, pvh_gen;
6221 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6222 ("pmap_clear_modify: page %p is not managed", m));
6223 VM_OBJECT_ASSERT_WLOCKED(m->object);
6224 KASSERT(!vm_page_xbusied(m),
6225 ("pmap_clear_modify: page %p is exclusive busied", m));
6228 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6229 * If the object containing the page is locked and the page is not
6230 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6232 if ((m->aflags & PGA_WRITEABLE) == 0)
6234 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6235 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6236 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6239 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6241 if (!PMAP_TRYLOCK(pmap)) {
6242 pvh_gen = pvh->pv_gen;
6246 if (pvh_gen != pvh->pv_gen) {
6251 PG_M = pmap_modified_bit(pmap);
6252 PG_V = pmap_valid_bit(pmap);
6253 PG_RW = pmap_rw_bit(pmap);
6255 pde = pmap_pde(pmap, va);
6257 if ((oldpde & PG_RW) != 0) {
6258 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6259 if ((oldpde & PG_W) == 0) {
6261 * Write protect the mapping to a
6262 * single page so that a subsequent
6263 * write access may repromote.
6265 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6267 pte = pmap_pde_to_pte(pde, va);
6269 if ((oldpte & PG_V) != 0) {
6270 while (!atomic_cmpset_long(pte,
6272 oldpte & ~(PG_M | PG_RW)))
6275 pmap_invalidate_page(pmap, va);
6282 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6284 if (!PMAP_TRYLOCK(pmap)) {
6285 md_gen = m->md.pv_gen;
6286 pvh_gen = pvh->pv_gen;
6290 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6295 PG_M = pmap_modified_bit(pmap);
6296 PG_RW = pmap_rw_bit(pmap);
6297 pde = pmap_pde(pmap, pv->pv_va);
6298 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6299 " a 2mpage in page %p's pv list", m));
6300 pte = pmap_pde_to_pte(pde, pv->pv_va);
6301 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6302 atomic_clear_long(pte, PG_M);
6303 pmap_invalidate_page(pmap, pv->pv_va);
6311 * Miscellaneous support routines follow
6314 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6315 static __inline void
6316 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6321 * The cache mode bits are all in the low 32-bits of the
6322 * PTE, so we can just spin on updating the low 32-bits.
6325 opte = *(u_int *)pte;
6326 npte = opte & ~mask;
6328 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6331 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6332 static __inline void
6333 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6338 * The cache mode bits are all in the low 32-bits of the
6339 * PDE, so we can just spin on updating the low 32-bits.
6342 opde = *(u_int *)pde;
6343 npde = opde & ~mask;
6345 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6349 * Map a set of physical memory pages into the kernel virtual
6350 * address space. Return a pointer to where it is mapped. This
6351 * routine is intended to be used for mapping device memory,
6355 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6357 struct pmap_preinit_mapping *ppim;
6358 vm_offset_t va, offset;
6362 offset = pa & PAGE_MASK;
6363 size = round_page(offset + size);
6364 pa = trunc_page(pa);
6366 if (!pmap_initialized) {
6368 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6369 ppim = pmap_preinit_mapping + i;
6370 if (ppim->va == 0) {
6374 ppim->va = virtual_avail;
6375 virtual_avail += size;
6381 panic("%s: too many preinit mappings", __func__);
6384 * If we have a preinit mapping, re-use it.
6386 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6387 ppim = pmap_preinit_mapping + i;
6388 if (ppim->pa == pa && ppim->sz == size &&
6390 return ((void *)(ppim->va + offset));
6393 * If the specified range of physical addresses fits within
6394 * the direct map window, use the direct map.
6396 if (pa < dmaplimit && pa + size < dmaplimit) {
6397 va = PHYS_TO_DMAP(pa);
6398 if (!pmap_change_attr(va, size, mode))
6399 return ((void *)(va + offset));
6401 va = kva_alloc(size);
6403 panic("%s: Couldn't allocate KVA", __func__);
6405 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6406 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6407 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6408 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6409 return ((void *)(va + offset));
6413 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6416 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6420 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6423 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6427 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6429 struct pmap_preinit_mapping *ppim;
6433 /* If we gave a direct map region in pmap_mapdev, do nothing */
6434 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6436 offset = va & PAGE_MASK;
6437 size = round_page(offset + size);
6438 va = trunc_page(va);
6439 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6440 ppim = pmap_preinit_mapping + i;
6441 if (ppim->va == va && ppim->sz == size) {
6442 if (pmap_initialized)
6448 if (va + size == virtual_avail)
6453 if (pmap_initialized)
6458 * Tries to demote a 1GB page mapping.
6461 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6463 pdp_entry_t newpdpe, oldpdpe;
6464 pd_entry_t *firstpde, newpde, *pde;
6465 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6469 PG_A = pmap_accessed_bit(pmap);
6470 PG_M = pmap_modified_bit(pmap);
6471 PG_V = pmap_valid_bit(pmap);
6472 PG_RW = pmap_rw_bit(pmap);
6474 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6476 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6477 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6478 if ((mpde = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6479 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6480 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6481 " in pmap %p", va, pmap);
6484 mpdepa = VM_PAGE_TO_PHYS(mpde);
6485 firstpde = (pd_entry_t *)PHYS_TO_DMAP(mpdepa);
6486 newpdpe = mpdepa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6487 KASSERT((oldpdpe & PG_A) != 0,
6488 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6489 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6490 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
6494 * Initialize the page directory page.
6496 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
6502 * Demote the mapping.
6507 * Invalidate a stale recursive mapping of the page directory page.
6509 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
6511 pmap_pdpe_demotions++;
6512 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
6513 " in pmap %p", va, pmap);
6518 * Sets the memory attribute for the specified page.
6521 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6524 m->md.pat_mode = ma;
6527 * If "m" is a normal page, update its direct mapping. This update
6528 * can be relied upon to perform any cache operations that are
6529 * required for data coherence.
6531 if ((m->flags & PG_FICTITIOUS) == 0 &&
6532 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6534 panic("memory attribute change on the direct map failed");
6538 * Changes the specified virtual address range's memory type to that given by
6539 * the parameter "mode". The specified virtual address range must be
6540 * completely contained within either the direct map or the kernel map. If
6541 * the virtual address range is contained within the kernel map, then the
6542 * memory type for each of the corresponding ranges of the direct map is also
6543 * changed. (The corresponding ranges of the direct map are those ranges that
6544 * map the same physical pages as the specified virtual address range.) These
6545 * changes to the direct map are necessary because Intel describes the
6546 * behavior of their processors as "undefined" if two or more mappings to the
6547 * same physical page have different memory types.
6549 * Returns zero if the change completed successfully, and either EINVAL or
6550 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6551 * of the virtual address range was not mapped, and ENOMEM is returned if
6552 * there was insufficient memory available to complete the change. In the
6553 * latter case, the memory type may have been changed on some part of the
6554 * virtual address range or the direct map.
6557 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6561 PMAP_LOCK(kernel_pmap);
6562 error = pmap_change_attr_locked(va, size, mode);
6563 PMAP_UNLOCK(kernel_pmap);
6568 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
6570 vm_offset_t base, offset, tmpva;
6571 vm_paddr_t pa_start, pa_end, pa_end1;
6575 int cache_bits_pte, cache_bits_pde, error;
6578 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6579 base = trunc_page(va);
6580 offset = va & PAGE_MASK;
6581 size = round_page(offset + size);
6584 * Only supported on kernel virtual addresses, including the direct
6585 * map but excluding the recursive map.
6587 if (base < DMAP_MIN_ADDRESS)
6590 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
6591 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
6595 * Pages that aren't mapped aren't supported. Also break down 2MB pages
6596 * into 4KB pages if required.
6598 for (tmpva = base; tmpva < base + size; ) {
6599 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6600 if (pdpe == NULL || *pdpe == 0)
6602 if (*pdpe & PG_PS) {
6604 * If the current 1GB page already has the required
6605 * memory type, then we need not demote this page. Just
6606 * increment tmpva to the next 1GB page frame.
6608 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
6609 tmpva = trunc_1gpage(tmpva) + NBPDP;
6614 * If the current offset aligns with a 1GB page frame
6615 * and there is at least 1GB left within the range, then
6616 * we need not break down this page into 2MB pages.
6618 if ((tmpva & PDPMASK) == 0 &&
6619 tmpva + PDPMASK < base + size) {
6623 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
6626 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6631 * If the current 2MB page already has the required
6632 * memory type, then we need not demote this page. Just
6633 * increment tmpva to the next 2MB page frame.
6635 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
6636 tmpva = trunc_2mpage(tmpva) + NBPDR;
6641 * If the current offset aligns with a 2MB page frame
6642 * and there is at least 2MB left within the range, then
6643 * we need not break down this page into 4KB pages.
6645 if ((tmpva & PDRMASK) == 0 &&
6646 tmpva + PDRMASK < base + size) {
6650 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
6653 pte = pmap_pde_to_pte(pde, tmpva);
6661 * Ok, all the pages exist, so run through them updating their
6662 * cache mode if required.
6664 pa_start = pa_end = 0;
6665 for (tmpva = base; tmpva < base + size; ) {
6666 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6667 if (*pdpe & PG_PS) {
6668 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
6669 pmap_pde_attr(pdpe, cache_bits_pde,
6673 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6674 (*pdpe & PG_PS_FRAME) < dmaplimit) {
6675 if (pa_start == pa_end) {
6676 /* Start physical address run. */
6677 pa_start = *pdpe & PG_PS_FRAME;
6678 pa_end = pa_start + NBPDP;
6679 } else if (pa_end == (*pdpe & PG_PS_FRAME))
6682 /* Run ended, update direct map. */
6683 error = pmap_change_attr_locked(
6684 PHYS_TO_DMAP(pa_start),
6685 pa_end - pa_start, mode);
6688 /* Start physical address run. */
6689 pa_start = *pdpe & PG_PS_FRAME;
6690 pa_end = pa_start + NBPDP;
6693 tmpva = trunc_1gpage(tmpva) + NBPDP;
6696 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6698 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
6699 pmap_pde_attr(pde, cache_bits_pde,
6703 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6704 (*pde & PG_PS_FRAME) < dmaplimit) {
6705 if (pa_start == pa_end) {
6706 /* Start physical address run. */
6707 pa_start = *pde & PG_PS_FRAME;
6708 pa_end = pa_start + NBPDR;
6709 } else if (pa_end == (*pde & PG_PS_FRAME))
6712 /* Run ended, update direct map. */
6713 error = pmap_change_attr_locked(
6714 PHYS_TO_DMAP(pa_start),
6715 pa_end - pa_start, mode);
6718 /* Start physical address run. */
6719 pa_start = *pde & PG_PS_FRAME;
6720 pa_end = pa_start + NBPDR;
6723 tmpva = trunc_2mpage(tmpva) + NBPDR;
6725 pte = pmap_pde_to_pte(pde, tmpva);
6726 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
6727 pmap_pte_attr(pte, cache_bits_pte,
6731 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6732 (*pte & PG_PS_FRAME) < dmaplimit) {
6733 if (pa_start == pa_end) {
6734 /* Start physical address run. */
6735 pa_start = *pte & PG_FRAME;
6736 pa_end = pa_start + PAGE_SIZE;
6737 } else if (pa_end == (*pte & PG_FRAME))
6738 pa_end += PAGE_SIZE;
6740 /* Run ended, update direct map. */
6741 error = pmap_change_attr_locked(
6742 PHYS_TO_DMAP(pa_start),
6743 pa_end - pa_start, mode);
6746 /* Start physical address run. */
6747 pa_start = *pte & PG_FRAME;
6748 pa_end = pa_start + PAGE_SIZE;
6754 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
6755 pa_end1 = MIN(pa_end, dmaplimit);
6756 if (pa_start != pa_end1)
6757 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
6758 pa_end1 - pa_start, mode);
6762 * Flush CPU caches if required to make sure any data isn't cached that
6763 * shouldn't be, etc.
6766 pmap_invalidate_range(kernel_pmap, base, tmpva);
6767 pmap_invalidate_cache_range(base, tmpva, FALSE);
6773 * Demotes any mapping within the direct map region that covers more than the
6774 * specified range of physical addresses. This range's size must be a power
6775 * of two and its starting address must be a multiple of its size. Since the
6776 * demotion does not change any attributes of the mapping, a TLB invalidation
6777 * is not mandatory. The caller may, however, request a TLB invalidation.
6780 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
6789 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
6790 KASSERT((base & (len - 1)) == 0,
6791 ("pmap_demote_DMAP: base is not a multiple of len"));
6792 if (len < NBPDP && base < dmaplimit) {
6793 va = PHYS_TO_DMAP(base);
6795 PMAP_LOCK(kernel_pmap);
6796 pdpe = pmap_pdpe(kernel_pmap, va);
6797 if ((*pdpe & X86_PG_V) == 0)
6798 panic("pmap_demote_DMAP: invalid PDPE");
6799 if ((*pdpe & PG_PS) != 0) {
6800 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
6801 panic("pmap_demote_DMAP: PDPE failed");
6805 pde = pmap_pdpe_to_pde(pdpe, va);
6806 if ((*pde & X86_PG_V) == 0)
6807 panic("pmap_demote_DMAP: invalid PDE");
6808 if ((*pde & PG_PS) != 0) {
6809 if (!pmap_demote_pde(kernel_pmap, pde, va))
6810 panic("pmap_demote_DMAP: PDE failed");
6814 if (changed && invalidate)
6815 pmap_invalidate_page(kernel_pmap, va);
6816 PMAP_UNLOCK(kernel_pmap);
6821 * perform the pmap work for mincore
6824 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
6827 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
6831 PG_A = pmap_accessed_bit(pmap);
6832 PG_M = pmap_modified_bit(pmap);
6833 PG_V = pmap_valid_bit(pmap);
6834 PG_RW = pmap_rw_bit(pmap);
6838 pdep = pmap_pde(pmap, addr);
6839 if (pdep != NULL && (*pdep & PG_V)) {
6840 if (*pdep & PG_PS) {
6842 /* Compute the physical address of the 4KB page. */
6843 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
6845 val = MINCORE_SUPER;
6847 pte = *pmap_pde_to_pte(pdep, addr);
6848 pa = pte & PG_FRAME;
6856 if ((pte & PG_V) != 0) {
6857 val |= MINCORE_INCORE;
6858 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6859 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
6860 if ((pte & PG_A) != 0)
6861 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
6863 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
6864 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
6865 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
6866 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
6867 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
6870 PA_UNLOCK_COND(*locked_pa);
6876 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
6878 uint32_t gen, new_gen, pcid_next;
6880 CRITICAL_ASSERT(curthread);
6881 gen = PCPU_GET(pcid_gen);
6882 if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN ||
6883 pmap->pm_pcids[cpuid].pm_gen == gen)
6884 return (CR3_PCID_SAVE);
6885 pcid_next = PCPU_GET(pcid_next);
6886 KASSERT(pcid_next <= PMAP_PCID_OVERMAX, ("cpu %d pcid_next %#x",
6888 if (pcid_next == PMAP_PCID_OVERMAX) {
6892 PCPU_SET(pcid_gen, new_gen);
6893 pcid_next = PMAP_PCID_KERN + 1;
6897 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
6898 pmap->pm_pcids[cpuid].pm_gen = new_gen;
6899 PCPU_SET(pcid_next, pcid_next + 1);
6904 pmap_activate_sw(struct thread *td)
6906 pmap_t oldpmap, pmap;
6907 uint64_t cached, cr3;
6911 oldpmap = PCPU_GET(curpmap);
6912 pmap = vmspace_pmap(td->td_proc->p_vmspace);
6913 if (oldpmap == pmap)
6915 cpuid = PCPU_GET(cpuid);
6917 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
6919 CPU_SET(cpuid, &pmap->pm_active);
6922 if (pmap_pcid_enabled) {
6923 cached = pmap_pcid_alloc(pmap, cpuid);
6924 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
6925 pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
6926 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
6927 pmap->pm_pcids[cpuid].pm_pcid));
6928 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
6929 pmap == kernel_pmap,
6930 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
6931 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
6934 * If the INVPCID instruction is not available,
6935 * invltlb_pcid_handler() is used for handle
6936 * invalidate_all IPI, which checks for curpmap ==
6937 * smp_tlb_pmap. Below operations sequence has a
6938 * window where %CR3 is loaded with the new pmap's
6939 * PML4 address, but curpmap value is not yet updated.
6940 * This causes invltlb IPI handler, called between the
6941 * updates, to execute as NOP, which leaves stale TLB
6944 * Note that the most typical use of
6945 * pmap_activate_sw(), from the context switch, is
6946 * immune to this race, because interrupts are
6947 * disabled (while the thread lock is owned), and IPI
6948 * happends after curpmap is updated. Protect other
6949 * callers in a similar way, by disabling interrupts
6950 * around the %cr3 register reload and curpmap
6954 rflags = intr_disable();
6956 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
6957 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
6960 PCPU_INC(pm_save_cnt);
6962 PCPU_SET(curpmap, pmap);
6964 intr_restore(rflags);
6965 } else if (cr3 != pmap->pm_cr3) {
6966 load_cr3(pmap->pm_cr3);
6967 PCPU_SET(curpmap, pmap);
6970 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
6972 CPU_CLR(cpuid, &oldpmap->pm_active);
6977 pmap_activate(struct thread *td)
6981 pmap_activate_sw(td);
6986 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
6991 * Increase the starting virtual address of the given mapping if a
6992 * different alignment might result in more superpage mappings.
6995 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
6996 vm_offset_t *addr, vm_size_t size)
6998 vm_offset_t superpage_offset;
7002 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7003 offset += ptoa(object->pg_color);
7004 superpage_offset = offset & PDRMASK;
7005 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
7006 (*addr & PDRMASK) == superpage_offset)
7008 if ((*addr & PDRMASK) < superpage_offset)
7009 *addr = (*addr & ~PDRMASK) + superpage_offset;
7011 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
7015 static unsigned long num_dirty_emulations;
7016 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
7017 &num_dirty_emulations, 0, NULL);
7019 static unsigned long num_accessed_emulations;
7020 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
7021 &num_accessed_emulations, 0, NULL);
7023 static unsigned long num_superpage_accessed_emulations;
7024 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7025 &num_superpage_accessed_emulations, 0, NULL);
7027 static unsigned long ad_emulation_superpage_promotions;
7028 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7029 &ad_emulation_superpage_promotions, 0, NULL);
7030 #endif /* INVARIANTS */
7033 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7036 struct rwlock *lock;
7039 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7041 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7042 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7044 if (!pmap_emulate_ad_bits(pmap))
7047 PG_A = pmap_accessed_bit(pmap);
7048 PG_M = pmap_modified_bit(pmap);
7049 PG_V = pmap_valid_bit(pmap);
7050 PG_RW = pmap_rw_bit(pmap);
7056 pde = pmap_pde(pmap, va);
7057 if (pde == NULL || (*pde & PG_V) == 0)
7060 if ((*pde & PG_PS) != 0) {
7061 if (ftype == VM_PROT_READ) {
7063 atomic_add_long(&num_superpage_accessed_emulations, 1);
7071 pte = pmap_pde_to_pte(pde, va);
7072 if ((*pte & PG_V) == 0)
7075 if (ftype == VM_PROT_WRITE) {
7076 if ((*pte & PG_RW) == 0)
7079 * Set the modified and accessed bits simultaneously.
7081 * Intel EPT PTEs that do software emulation of A/D bits map
7082 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7083 * An EPT misconfiguration is triggered if the PTE is writable
7084 * but not readable (WR=10). This is avoided by setting PG_A
7085 * and PG_M simultaneously.
7087 *pte |= PG_M | PG_A;
7092 /* try to promote the mapping */
7093 if (va < VM_MAXUSER_ADDRESS)
7094 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7098 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7100 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7101 pmap_ps_enabled(pmap) &&
7102 (m->flags & PG_FICTITIOUS) == 0 &&
7103 vm_reserv_level_iffullpop(m) == 0) {
7104 pmap_promote_pde(pmap, pde, va, &lock);
7106 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7110 if (ftype == VM_PROT_WRITE)
7111 atomic_add_long(&num_dirty_emulations, 1);
7113 atomic_add_long(&num_accessed_emulations, 1);
7115 rv = 0; /* success */
7124 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7129 pt_entry_t *pte, PG_V;
7133 PG_V = pmap_valid_bit(pmap);
7136 pml4 = pmap_pml4e(pmap, va);
7138 if ((*pml4 & PG_V) == 0)
7141 pdp = pmap_pml4e_to_pdpe(pml4, va);
7143 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7146 pde = pmap_pdpe_to_pde(pdp, va);
7148 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7151 pte = pmap_pde_to_pte(pde, va);
7160 * Get the kernel virtual address of a set of physical pages. If there are
7161 * physical addresses not covered by the DMAP perform a transient mapping
7162 * that will be removed when calling pmap_unmap_io_transient.
7164 * \param page The pages the caller wishes to obtain the virtual
7165 * address on the kernel memory map.
7166 * \param vaddr On return contains the kernel virtual memory address
7167 * of the pages passed in the page parameter.
7168 * \param count Number of pages passed in.
7169 * \param can_fault TRUE if the thread using the mapped pages can take
7170 * page faults, FALSE otherwise.
7172 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7173 * finished or FALSE otherwise.
7177 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7178 boolean_t can_fault)
7181 boolean_t needs_mapping;
7183 int cache_bits, error, i;
7186 * Allocate any KVA space that we need, this is done in a separate
7187 * loop to prevent calling vmem_alloc while pinned.
7189 needs_mapping = FALSE;
7190 for (i = 0; i < count; i++) {
7191 paddr = VM_PAGE_TO_PHYS(page[i]);
7192 if (__predict_false(paddr >= dmaplimit)) {
7193 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7194 M_BESTFIT | M_WAITOK, &vaddr[i]);
7195 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7196 needs_mapping = TRUE;
7198 vaddr[i] = PHYS_TO_DMAP(paddr);
7202 /* Exit early if everything is covered by the DMAP */
7207 * NB: The sequence of updating a page table followed by accesses
7208 * to the corresponding pages used in the !DMAP case is subject to
7209 * the situation described in the "AMD64 Architecture Programmer's
7210 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7211 * Coherency Considerations". Therefore, issuing the INVLPG right
7212 * after modifying the PTE bits is crucial.
7216 for (i = 0; i < count; i++) {
7217 paddr = VM_PAGE_TO_PHYS(page[i]);
7218 if (paddr >= dmaplimit) {
7221 * Slow path, since we can get page faults
7222 * while mappings are active don't pin the
7223 * thread to the CPU and instead add a global
7224 * mapping visible to all CPUs.
7226 pmap_qenter(vaddr[i], &page[i], 1);
7228 pte = vtopte(vaddr[i]);
7229 cache_bits = pmap_cache_bits(kernel_pmap,
7230 page[i]->md.pat_mode, 0);
7231 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7238 return (needs_mapping);
7242 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7243 boolean_t can_fault)
7250 for (i = 0; i < count; i++) {
7251 paddr = VM_PAGE_TO_PHYS(page[i]);
7252 if (paddr >= dmaplimit) {
7254 pmap_qremove(vaddr[i], 1);
7255 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7261 pmap_quick_enter_page(vm_page_t m)
7265 paddr = VM_PAGE_TO_PHYS(m);
7266 if (paddr < dmaplimit)
7267 return (PHYS_TO_DMAP(paddr));
7268 mtx_lock_spin(&qframe_mtx);
7269 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7270 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7271 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7276 pmap_quick_remove_page(vm_offset_t addr)
7281 pte_store(vtopte(qframe), 0);
7283 mtx_unlock_spin(&qframe_mtx);
7286 #include "opt_ddb.h"
7288 #include <ddb/ddb.h>
7290 DB_SHOW_COMMAND(pte, pmap_print_pte)
7296 pt_entry_t *pte, PG_V;
7300 va = (vm_offset_t)addr;
7301 pmap = PCPU_GET(curpmap); /* XXX */
7303 db_printf("show pte addr\n");
7306 PG_V = pmap_valid_bit(pmap);
7307 pml4 = pmap_pml4e(pmap, va);
7308 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
7309 if ((*pml4 & PG_V) == 0) {
7313 pdp = pmap_pml4e_to_pdpe(pml4, va);
7314 db_printf(" pdpe %#016lx", *pdp);
7315 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
7319 pde = pmap_pdpe_to_pde(pdp, va);
7320 db_printf(" pde %#016lx", *pde);
7321 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
7325 pte = pmap_pde_to_pte(pde, va);
7326 db_printf(" pte %#016lx\n", *pte);
7329 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
7334 a = (vm_paddr_t)addr;
7335 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
7337 db_printf("show phys2dmap addr\n");