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 void pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask);
618 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
619 struct rwlock **lockp);
620 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
622 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
623 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
624 struct spglist *free, struct rwlock **lockp);
625 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
626 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
627 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
628 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
629 struct spglist *free);
630 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
631 vm_page_t m, struct rwlock **lockp);
632 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
634 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
636 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
637 struct rwlock **lockp);
638 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
639 struct rwlock **lockp);
640 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
641 struct rwlock **lockp);
643 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
644 struct spglist *free);
645 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
646 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
649 * Move the kernel virtual free pointer to the next
650 * 2MB. This is used to help improve performance
651 * by using a large (2MB) page for much of the kernel
652 * (.text, .data, .bss)
655 pmap_kmem_choose(vm_offset_t addr)
657 vm_offset_t newaddr = addr;
659 newaddr = roundup2(addr, NBPDR);
663 /********************/
664 /* Inline functions */
665 /********************/
667 /* Return a non-clipped PD index for a given VA */
668 static __inline vm_pindex_t
669 pmap_pde_pindex(vm_offset_t va)
671 return (va >> PDRSHIFT);
675 /* Return a pointer to the PML4 slot that corresponds to a VA */
676 static __inline pml4_entry_t *
677 pmap_pml4e(pmap_t pmap, vm_offset_t va)
680 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
683 /* Return a pointer to the PDP slot that corresponds to a VA */
684 static __inline pdp_entry_t *
685 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
689 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
690 return (&pdpe[pmap_pdpe_index(va)]);
693 /* Return a pointer to the PDP slot that corresponds to a VA */
694 static __inline pdp_entry_t *
695 pmap_pdpe(pmap_t pmap, vm_offset_t va)
700 PG_V = pmap_valid_bit(pmap);
701 pml4e = pmap_pml4e(pmap, va);
702 if ((*pml4e & PG_V) == 0)
704 return (pmap_pml4e_to_pdpe(pml4e, va));
707 /* Return a pointer to the PD slot that corresponds to a VA */
708 static __inline pd_entry_t *
709 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
713 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
714 return (&pde[pmap_pde_index(va)]);
717 /* Return a pointer to the PD slot that corresponds to a VA */
718 static __inline pd_entry_t *
719 pmap_pde(pmap_t pmap, vm_offset_t va)
724 PG_V = pmap_valid_bit(pmap);
725 pdpe = pmap_pdpe(pmap, va);
726 if (pdpe == NULL || (*pdpe & PG_V) == 0)
728 return (pmap_pdpe_to_pde(pdpe, va));
731 /* Return a pointer to the PT slot that corresponds to a VA */
732 static __inline pt_entry_t *
733 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
737 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
738 return (&pte[pmap_pte_index(va)]);
741 /* Return a pointer to the PT slot that corresponds to a VA */
742 static __inline pt_entry_t *
743 pmap_pte(pmap_t pmap, vm_offset_t va)
748 PG_V = pmap_valid_bit(pmap);
749 pde = pmap_pde(pmap, va);
750 if (pde == NULL || (*pde & PG_V) == 0)
752 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
753 return ((pt_entry_t *)pde);
754 return (pmap_pde_to_pte(pde, va));
758 pmap_resident_count_inc(pmap_t pmap, int count)
761 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
762 pmap->pm_stats.resident_count += count;
766 pmap_resident_count_dec(pmap_t pmap, int count)
769 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
770 KASSERT(pmap->pm_stats.resident_count >= count,
771 ("pmap %p resident count underflow %ld %d", pmap,
772 pmap->pm_stats.resident_count, count));
773 pmap->pm_stats.resident_count -= count;
776 PMAP_INLINE pt_entry_t *
777 vtopte(vm_offset_t va)
779 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
781 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
783 return (PTmap + ((va >> PAGE_SHIFT) & mask));
786 static __inline pd_entry_t *
787 vtopde(vm_offset_t va)
789 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
791 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
793 return (PDmap + ((va >> PDRSHIFT) & mask));
797 allocpages(vm_paddr_t *firstaddr, int n)
802 bzero((void *)ret, n * PAGE_SIZE);
803 *firstaddr += n * PAGE_SIZE;
807 CTASSERT(powerof2(NDMPML4E));
809 /* number of kernel PDP slots */
810 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
813 nkpt_init(vm_paddr_t addr)
820 pt_pages = howmany(addr, 1 << PDRSHIFT);
821 pt_pages += NKPDPE(pt_pages);
824 * Add some slop beyond the bare minimum required for bootstrapping
827 * This is quite important when allocating KVA for kernel modules.
828 * The modules are required to be linked in the negative 2GB of
829 * the address space. If we run out of KVA in this region then
830 * pmap_growkernel() will need to allocate page table pages to map
831 * the entire 512GB of KVA space which is an unnecessary tax on
834 * Secondly, device memory mapped as part of setting up the low-
835 * level console(s) is taken from KVA, starting at virtual_avail.
836 * This is because cninit() is called after pmap_bootstrap() but
837 * before vm_init() and pmap_init(). 20MB for a frame buffer is
840 pt_pages += 32; /* 64MB additional slop. */
846 create_pagetables(vm_paddr_t *firstaddr)
848 int i, j, ndm1g, nkpdpe;
854 /* Allocate page table pages for the direct map */
855 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
856 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
858 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
859 if (ndmpdpphys > NDMPML4E) {
861 * Each NDMPML4E allows 512 GB, so limit to that,
862 * and then readjust ndmpdp and ndmpdpphys.
864 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
865 Maxmem = atop(NDMPML4E * NBPML4);
866 ndmpdpphys = NDMPML4E;
867 ndmpdp = NDMPML4E * NPDEPG;
869 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
871 if ((amd_feature & AMDID_PAGE1GB) != 0)
872 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
874 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
875 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
878 KPML4phys = allocpages(firstaddr, 1);
879 KPDPphys = allocpages(firstaddr, NKPML4E);
882 * Allocate the initial number of kernel page table pages required to
883 * bootstrap. We defer this until after all memory-size dependent
884 * allocations are done (e.g. direct map), so that we don't have to
885 * build in too much slop in our estimate.
887 * Note that when NKPML4E > 1, we have an empty page underneath
888 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
889 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
891 nkpt_init(*firstaddr);
892 nkpdpe = NKPDPE(nkpt);
894 KPTphys = allocpages(firstaddr, nkpt);
895 KPDphys = allocpages(firstaddr, nkpdpe);
897 /* Fill in the underlying page table pages */
898 /* Nominally read-only (but really R/W) from zero to physfree */
899 /* XXX not fully used, underneath 2M pages */
900 pt_p = (pt_entry_t *)KPTphys;
901 for (i = 0; ptoa(i) < *firstaddr; i++)
902 pt_p[i] = ptoa(i) | X86_PG_RW | X86_PG_V | X86_PG_G;
904 /* Now map the page tables at their location within PTmap */
905 pd_p = (pd_entry_t *)KPDphys;
906 for (i = 0; i < nkpt; i++)
907 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
909 /* Map from zero to end of allocations under 2M pages */
910 /* This replaces some of the KPTphys entries above */
911 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
912 pd_p[i] = (i << PDRSHIFT) | X86_PG_RW | X86_PG_V | PG_PS |
915 /* And connect up the PD to the PDP (leaving room for L4 pages) */
916 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
917 for (i = 0; i < nkpdpe; i++)
918 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
922 * Now, set up the direct map region using 2MB and/or 1GB pages. If
923 * the end of physical memory is not aligned to a 1GB page boundary,
924 * then the residual physical memory is mapped with 2MB pages. Later,
925 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
926 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
927 * that are partially used.
929 pd_p = (pd_entry_t *)DMPDphys;
930 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
931 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
932 /* Preset PG_M and PG_A because demotion expects it. */
933 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | X86_PG_G |
936 pdp_p = (pdp_entry_t *)DMPDPphys;
937 for (i = 0; i < ndm1g; i++) {
938 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
939 /* Preset PG_M and PG_A because demotion expects it. */
940 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | X86_PG_G |
943 for (j = 0; i < ndmpdp; i++, j++) {
944 pdp_p[i] = DMPDphys + ptoa(j);
945 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_U;
948 /* And recursively map PML4 to itself in order to get PTmap */
949 p4_p = (pml4_entry_t *)KPML4phys;
950 p4_p[PML4PML4I] = KPML4phys;
951 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | PG_U;
953 /* Connect the Direct Map slot(s) up to the PML4. */
954 for (i = 0; i < ndmpdpphys; i++) {
955 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
956 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | PG_U;
959 /* Connect the KVA slots up to the PML4 */
960 for (i = 0; i < NKPML4E; i++) {
961 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
962 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V | PG_U;
967 * Bootstrap the system enough to run with virtual memory.
969 * On amd64 this is called after mapping has already been enabled
970 * and just syncs the pmap module with what has already been done.
971 * [We can't call it easily with mapping off since the kernel is not
972 * mapped with PA == VA, hence we would have to relocate every address
973 * from the linked base (virtual) address "KERNBASE" to the actual
974 * (physical) address starting relative to 0]
977 pmap_bootstrap(vm_paddr_t *firstaddr)
984 * Create an initial set of page tables to run the kernel in.
986 create_pagetables(firstaddr);
989 * Add a physical memory segment (vm_phys_seg) corresponding to the
990 * preallocated kernel page table pages so that vm_page structures
991 * representing these pages will be created. The vm_page structures
992 * are required for promotion of the corresponding kernel virtual
993 * addresses to superpage mappings.
995 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
997 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
998 virtual_avail = pmap_kmem_choose(virtual_avail);
1000 virtual_end = VM_MAX_KERNEL_ADDRESS;
1003 /* XXX do %cr0 as well */
1004 load_cr4(rcr4() | CR4_PGE);
1005 load_cr3(KPML4phys);
1006 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1007 load_cr4(rcr4() | CR4_SMEP);
1010 * Initialize the kernel pmap (which is statically allocated).
1012 PMAP_LOCK_INIT(kernel_pmap);
1013 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1014 kernel_pmap->pm_cr3 = KPML4phys;
1015 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1016 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1017 kernel_pmap->pm_flags = pmap_flags;
1020 * Initialize the TLB invalidations generation number lock.
1022 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1025 * Reserve some special page table entries/VA space for temporary
1028 #define SYSMAP(c, p, v, n) \
1029 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1035 * Crashdump maps. The first page is reused as CMAP1 for the
1038 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1039 CADDR1 = crashdumpmap;
1044 * Initialize the PAT MSR.
1045 * pmap_init_pat() clears and sets CR4_PGE, which, as a
1046 * side-effect, invalidates stale PG_G TLB entries that might
1047 * have been created in our pre-boot environment.
1051 /* Initialize TLB Context Id. */
1052 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1053 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1054 /* Check for INVPCID support */
1055 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1057 for (i = 0; i < MAXCPU; i++) {
1058 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1059 kernel_pmap->pm_pcids[i].pm_gen = 1;
1061 __pcpu[0].pc_pcid_next = PMAP_PCID_KERN + 1;
1062 __pcpu[0].pc_pcid_gen = 1;
1064 * pcpu area for APs is zeroed during AP startup.
1065 * pc_pcid_next and pc_pcid_gen are initialized by AP
1066 * during pcpu setup.
1068 load_cr4(rcr4() | CR4_PCIDE);
1070 pmap_pcid_enabled = 0;
1075 * Setup the PAT MSR.
1080 int pat_table[PAT_INDEX_SIZE];
1085 /* Bail if this CPU doesn't implement PAT. */
1086 if ((cpu_feature & CPUID_PAT) == 0)
1089 /* Set default PAT index table. */
1090 for (i = 0; i < PAT_INDEX_SIZE; i++)
1092 pat_table[PAT_WRITE_BACK] = 0;
1093 pat_table[PAT_WRITE_THROUGH] = 1;
1094 pat_table[PAT_UNCACHEABLE] = 3;
1095 pat_table[PAT_WRITE_COMBINING] = 3;
1096 pat_table[PAT_WRITE_PROTECTED] = 3;
1097 pat_table[PAT_UNCACHED] = 3;
1099 /* Initialize default PAT entries. */
1100 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1101 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1102 PAT_VALUE(2, PAT_UNCACHED) |
1103 PAT_VALUE(3, PAT_UNCACHEABLE) |
1104 PAT_VALUE(4, PAT_WRITE_BACK) |
1105 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1106 PAT_VALUE(6, PAT_UNCACHED) |
1107 PAT_VALUE(7, PAT_UNCACHEABLE);
1111 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1112 * Program 5 and 6 as WP and WC.
1113 * Leave 4 and 7 as WB and UC.
1115 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1116 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1117 PAT_VALUE(6, PAT_WRITE_COMBINING);
1118 pat_table[PAT_UNCACHED] = 2;
1119 pat_table[PAT_WRITE_PROTECTED] = 5;
1120 pat_table[PAT_WRITE_COMBINING] = 6;
1123 * Just replace PAT Index 2 with WC instead of UC-.
1125 pat_msr &= ~PAT_MASK(2);
1126 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1127 pat_table[PAT_WRITE_COMBINING] = 2;
1132 load_cr4(cr4 & ~CR4_PGE);
1134 /* Disable caches (CD = 1, NW = 0). */
1136 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1138 /* Flushes caches and TLBs. */
1142 /* Update PAT and index table. */
1143 wrmsr(MSR_PAT, pat_msr);
1144 for (i = 0; i < PAT_INDEX_SIZE; i++)
1145 pat_index[i] = pat_table[i];
1147 /* Flush caches and TLBs again. */
1151 /* Restore caches and PGE. */
1157 * Initialize a vm_page's machine-dependent fields.
1160 pmap_page_init(vm_page_t m)
1163 TAILQ_INIT(&m->md.pv_list);
1164 m->md.pat_mode = PAT_WRITE_BACK;
1168 * Initialize the pmap module.
1169 * Called by vm_init, to initialize any structures that the pmap
1170 * system needs to map virtual memory.
1175 struct pmap_preinit_mapping *ppim;
1178 int error, i, pv_npg;
1181 * Initialize the vm page array entries for the kernel pmap's
1184 for (i = 0; i < nkpt; i++) {
1185 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1186 KASSERT(mpte >= vm_page_array &&
1187 mpte < &vm_page_array[vm_page_array_size],
1188 ("pmap_init: page table page is out of range"));
1189 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1190 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1194 * If the kernel is running on a virtual machine, then it must assume
1195 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1196 * be prepared for the hypervisor changing the vendor and family that
1197 * are reported by CPUID. Consequently, the workaround for AMD Family
1198 * 10h Erratum 383 is enabled if the processor's feature set does not
1199 * include at least one feature that is only supported by older Intel
1200 * or newer AMD processors.
1202 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1203 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1204 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1206 workaround_erratum383 = 1;
1209 * Are large page mappings enabled?
1211 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1212 if (pg_ps_enabled) {
1213 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1214 ("pmap_init: can't assign to pagesizes[1]"));
1215 pagesizes[1] = NBPDR;
1219 * Initialize the pv chunk list mutex.
1221 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1224 * Initialize the pool of pv list locks.
1226 for (i = 0; i < NPV_LIST_LOCKS; i++)
1227 rw_init(&pv_list_locks[i], "pmap pv list");
1230 * Calculate the size of the pv head table for superpages.
1232 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1235 * Allocate memory for the pv head table for superpages.
1237 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1239 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1241 for (i = 0; i < pv_npg; i++)
1242 TAILQ_INIT(&pv_table[i].pv_list);
1243 TAILQ_INIT(&pv_dummy.pv_list);
1245 pmap_initialized = 1;
1246 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1247 ppim = pmap_preinit_mapping + i;
1250 /* Make the direct map consistent */
1251 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1252 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1253 ppim->sz, ppim->mode);
1257 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1258 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1261 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1262 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1263 (vmem_addr_t *)&qframe);
1265 panic("qframe allocation failed");
1268 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1269 "2MB page mapping counters");
1271 static u_long pmap_pde_demotions;
1272 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1273 &pmap_pde_demotions, 0, "2MB page demotions");
1275 static u_long pmap_pde_mappings;
1276 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1277 &pmap_pde_mappings, 0, "2MB page mappings");
1279 static u_long pmap_pde_p_failures;
1280 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1281 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1283 static u_long pmap_pde_promotions;
1284 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1285 &pmap_pde_promotions, 0, "2MB page promotions");
1287 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1288 "1GB page mapping counters");
1290 static u_long pmap_pdpe_demotions;
1291 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1292 &pmap_pdpe_demotions, 0, "1GB page demotions");
1294 /***************************************************
1295 * Low level helper routines.....
1296 ***************************************************/
1299 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1301 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1303 switch (pmap->pm_type) {
1306 /* Verify that both PAT bits are not set at the same time */
1307 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1308 ("Invalid PAT bits in entry %#lx", entry));
1310 /* Swap the PAT bits if one of them is set */
1311 if ((entry & x86_pat_bits) != 0)
1312 entry ^= x86_pat_bits;
1316 * Nothing to do - the memory attributes are represented
1317 * the same way for regular pages and superpages.
1321 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1328 * Determine the appropriate bits to set in a PTE or PDE for a specified
1332 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1334 int cache_bits, pat_flag, pat_idx;
1336 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1337 panic("Unknown caching mode %d\n", mode);
1339 switch (pmap->pm_type) {
1342 /* The PAT bit is different for PTE's and PDE's. */
1343 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1345 /* Map the caching mode to a PAT index. */
1346 pat_idx = pat_index[mode];
1348 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1351 cache_bits |= pat_flag;
1353 cache_bits |= PG_NC_PCD;
1355 cache_bits |= PG_NC_PWT;
1359 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1363 panic("unsupported pmap type %d", pmap->pm_type);
1366 return (cache_bits);
1370 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1374 switch (pmap->pm_type) {
1377 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1380 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1383 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1389 static __inline boolean_t
1390 pmap_ps_enabled(pmap_t pmap)
1393 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1397 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1400 switch (pmap->pm_type) {
1407 * This is a little bogus since the generation number is
1408 * supposed to be bumped up when a region of the address
1409 * space is invalidated in the page tables.
1411 * In this case the old PDE entry is valid but yet we want
1412 * to make sure that any mappings using the old entry are
1413 * invalidated in the TLB.
1415 * The reason this works as expected is because we rendezvous
1416 * "all" host cpus and force any vcpu context to exit as a
1419 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1422 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1424 pde_store(pde, newpde);
1428 * After changing the page size for the specified virtual address in the page
1429 * table, flush the corresponding entries from the processor's TLB. Only the
1430 * calling processor's TLB is affected.
1432 * The calling thread must be pinned to a processor.
1435 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1439 if (pmap_type_guest(pmap))
1442 KASSERT(pmap->pm_type == PT_X86,
1443 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1445 PG_G = pmap_global_bit(pmap);
1447 if ((newpde & PG_PS) == 0)
1448 /* Demotion: flush a specific 2MB page mapping. */
1450 else if ((newpde & PG_G) == 0)
1452 * Promotion: flush every 4KB page mapping from the TLB
1453 * because there are too many to flush individually.
1458 * Promotion: flush every 4KB page mapping from the TLB,
1459 * including any global (PG_G) mappings.
1467 * For SMP, these functions have to use the IPI mechanism for coherence.
1469 * N.B.: Before calling any of the following TLB invalidation functions,
1470 * the calling processor must ensure that all stores updating a non-
1471 * kernel page table are globally performed. Otherwise, another
1472 * processor could cache an old, pre-update entry without being
1473 * invalidated. This can happen one of two ways: (1) The pmap becomes
1474 * active on another processor after its pm_active field is checked by
1475 * one of the following functions but before a store updating the page
1476 * table is globally performed. (2) The pmap becomes active on another
1477 * processor before its pm_active field is checked but due to
1478 * speculative loads one of the following functions stills reads the
1479 * pmap as inactive on the other processor.
1481 * The kernel page table is exempt because its pm_active field is
1482 * immutable. The kernel page table is always active on every
1487 * Interrupt the cpus that are executing in the guest context.
1488 * This will force the vcpu to exit and the cached EPT mappings
1489 * will be invalidated by the host before the next vmresume.
1491 static __inline void
1492 pmap_invalidate_ept(pmap_t pmap)
1497 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1498 ("pmap_invalidate_ept: absurd pm_active"));
1501 * The TLB mappings associated with a vcpu context are not
1502 * flushed each time a different vcpu is chosen to execute.
1504 * This is in contrast with a process's vtop mappings that
1505 * are flushed from the TLB on each context switch.
1507 * Therefore we need to do more than just a TLB shootdown on
1508 * the active cpus in 'pmap->pm_active'. To do this we keep
1509 * track of the number of invalidations performed on this pmap.
1511 * Each vcpu keeps a cache of this counter and compares it
1512 * just before a vmresume. If the counter is out-of-date an
1513 * invept will be done to flush stale mappings from the TLB.
1515 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1518 * Force the vcpu to exit and trap back into the hypervisor.
1520 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1521 ipi_selected(pmap->pm_active, ipinum);
1526 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1531 if (pmap_type_guest(pmap)) {
1532 pmap_invalidate_ept(pmap);
1536 KASSERT(pmap->pm_type == PT_X86,
1537 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1540 if (pmap == kernel_pmap) {
1544 cpuid = PCPU_GET(cpuid);
1545 if (pmap == PCPU_GET(curpmap))
1547 else if (pmap_pcid_enabled)
1548 pmap->pm_pcids[cpuid].pm_gen = 0;
1549 if (pmap_pcid_enabled) {
1552 pmap->pm_pcids[i].pm_gen = 0;
1555 mask = &pmap->pm_active;
1557 smp_masked_invlpg(*mask, va);
1561 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1562 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1565 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1571 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1572 pmap_invalidate_all(pmap);
1576 if (pmap_type_guest(pmap)) {
1577 pmap_invalidate_ept(pmap);
1581 KASSERT(pmap->pm_type == PT_X86,
1582 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1585 cpuid = PCPU_GET(cpuid);
1586 if (pmap == kernel_pmap) {
1587 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1591 if (pmap == PCPU_GET(curpmap)) {
1592 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1594 } else if (pmap_pcid_enabled) {
1595 pmap->pm_pcids[cpuid].pm_gen = 0;
1597 if (pmap_pcid_enabled) {
1600 pmap->pm_pcids[i].pm_gen = 0;
1603 mask = &pmap->pm_active;
1605 smp_masked_invlpg_range(*mask, sva, eva);
1610 pmap_invalidate_all(pmap_t pmap)
1613 struct invpcid_descr d;
1616 if (pmap_type_guest(pmap)) {
1617 pmap_invalidate_ept(pmap);
1621 KASSERT(pmap->pm_type == PT_X86,
1622 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1625 if (pmap == kernel_pmap) {
1626 if (pmap_pcid_enabled && invpcid_works) {
1627 bzero(&d, sizeof(d));
1628 invpcid(&d, INVPCID_CTXGLOB);
1634 cpuid = PCPU_GET(cpuid);
1635 if (pmap == PCPU_GET(curpmap)) {
1636 if (pmap_pcid_enabled) {
1637 if (invpcid_works) {
1638 d.pcid = pmap->pm_pcids[cpuid].pm_pcid;
1641 invpcid(&d, INVPCID_CTX);
1643 load_cr3(pmap->pm_cr3 | pmap->pm_pcids
1644 [PCPU_GET(cpuid)].pm_pcid);
1649 } else if (pmap_pcid_enabled) {
1650 pmap->pm_pcids[cpuid].pm_gen = 0;
1652 if (pmap_pcid_enabled) {
1655 pmap->pm_pcids[i].pm_gen = 0;
1658 mask = &pmap->pm_active;
1660 smp_masked_invltlb(*mask, pmap);
1665 pmap_invalidate_cache(void)
1675 cpuset_t invalidate; /* processors that invalidate their TLB */
1680 u_int store; /* processor that updates the PDE */
1684 pmap_update_pde_action(void *arg)
1686 struct pde_action *act = arg;
1688 if (act->store == PCPU_GET(cpuid))
1689 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1693 pmap_update_pde_teardown(void *arg)
1695 struct pde_action *act = arg;
1697 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1698 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1702 * Change the page size for the specified virtual address in a way that
1703 * prevents any possibility of the TLB ever having two entries that map the
1704 * same virtual address using different page sizes. This is the recommended
1705 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1706 * machine check exception for a TLB state that is improperly diagnosed as a
1710 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1712 struct pde_action act;
1713 cpuset_t active, other_cpus;
1717 cpuid = PCPU_GET(cpuid);
1718 other_cpus = all_cpus;
1719 CPU_CLR(cpuid, &other_cpus);
1720 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1723 active = pmap->pm_active;
1725 if (CPU_OVERLAP(&active, &other_cpus)) {
1727 act.invalidate = active;
1731 act.newpde = newpde;
1732 CPU_SET(cpuid, &active);
1733 smp_rendezvous_cpus(active,
1734 smp_no_rendevous_barrier, pmap_update_pde_action,
1735 pmap_update_pde_teardown, &act);
1737 pmap_update_pde_store(pmap, pde, newpde);
1738 if (CPU_ISSET(cpuid, &active))
1739 pmap_update_pde_invalidate(pmap, va, newpde);
1745 * Normal, non-SMP, invalidation functions.
1748 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1751 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1755 KASSERT(pmap->pm_type == PT_X86,
1756 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1758 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1760 else if (pmap_pcid_enabled)
1761 pmap->pm_pcids[0].pm_gen = 0;
1765 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1769 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1773 KASSERT(pmap->pm_type == PT_X86,
1774 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1776 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1777 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1779 } else if (pmap_pcid_enabled) {
1780 pmap->pm_pcids[0].pm_gen = 0;
1785 pmap_invalidate_all(pmap_t pmap)
1787 struct invpcid_descr d;
1789 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1793 KASSERT(pmap->pm_type == PT_X86,
1794 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
1796 if (pmap == kernel_pmap) {
1797 if (pmap_pcid_enabled && invpcid_works) {
1798 bzero(&d, sizeof(d));
1799 invpcid(&d, INVPCID_CTXGLOB);
1803 } else if (pmap == PCPU_GET(curpmap)) {
1804 if (pmap_pcid_enabled) {
1805 if (invpcid_works) {
1806 d.pcid = pmap->pm_pcids[0].pm_pcid;
1809 invpcid(&d, INVPCID_CTX);
1811 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[0].
1817 } else if (pmap_pcid_enabled) {
1818 pmap->pm_pcids[0].pm_gen = 0;
1823 pmap_invalidate_cache(void)
1830 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1833 pmap_update_pde_store(pmap, pde, newpde);
1834 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1835 pmap_update_pde_invalidate(pmap, va, newpde);
1837 pmap->pm_pcids[0].pm_gen = 0;
1841 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
1844 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
1848 sva &= ~(vm_offset_t)cpu_clflush_line_size;
1850 KASSERT((sva & PAGE_MASK) == 0,
1851 ("pmap_invalidate_cache_range: sva not page-aligned"));
1852 KASSERT((eva & PAGE_MASK) == 0,
1853 ("pmap_invalidate_cache_range: eva not page-aligned"));
1856 if ((cpu_feature & CPUID_SS) != 0 && !force)
1857 ; /* If "Self Snoop" is supported and allowed, do nothing. */
1858 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
1859 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1861 * XXX: Some CPUs fault, hang, or trash the local APIC
1862 * registers if we use CLFLUSH on the local APIC
1863 * range. The local APIC is always uncached, so we
1864 * don't need to flush for that range anyway.
1866 if (pmap_kextract(sva) == lapic_paddr)
1870 * Otherwise, do per-cache line flush. Use the sfence
1871 * instruction to insure that previous stores are
1872 * included in the write-back. The processor
1873 * propagates flush to other processors in the cache
1877 for (; sva < eva; sva += cpu_clflush_line_size)
1880 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
1881 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1882 if (pmap_kextract(sva) == lapic_paddr)
1885 * Writes are ordered by CLFLUSH on Intel CPUs.
1887 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1889 for (; sva < eva; sva += cpu_clflush_line_size)
1891 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1896 * No targeted cache flush methods are supported by CPU,
1897 * or the supplied range is bigger than 2MB.
1898 * Globally invalidate cache.
1900 pmap_invalidate_cache();
1905 * Remove the specified set of pages from the data and instruction caches.
1907 * In contrast to pmap_invalidate_cache_range(), this function does not
1908 * rely on the CPU's self-snoop feature, because it is intended for use
1909 * when moving pages into a different cache domain.
1912 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1914 vm_offset_t daddr, eva;
1918 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
1919 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1920 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
1921 pmap_invalidate_cache();
1925 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
1927 for (i = 0; i < count; i++) {
1928 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
1929 eva = daddr + PAGE_SIZE;
1930 for (; daddr < eva; daddr += cpu_clflush_line_size) {
1939 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
1945 * Routine: pmap_extract
1947 * Extract the physical page address associated
1948 * with the given map/virtual_address pair.
1951 pmap_extract(pmap_t pmap, vm_offset_t va)
1955 pt_entry_t *pte, PG_V;
1959 PG_V = pmap_valid_bit(pmap);
1961 pdpe = pmap_pdpe(pmap, va);
1962 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
1963 if ((*pdpe & PG_PS) != 0)
1964 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
1966 pde = pmap_pdpe_to_pde(pdpe, va);
1967 if ((*pde & PG_V) != 0) {
1968 if ((*pde & PG_PS) != 0) {
1969 pa = (*pde & PG_PS_FRAME) |
1972 pte = pmap_pde_to_pte(pde, va);
1973 pa = (*pte & PG_FRAME) |
1984 * Routine: pmap_extract_and_hold
1986 * Atomically extract and hold the physical page
1987 * with the given pmap and virtual address pair
1988 * if that mapping permits the given protection.
1991 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1993 pd_entry_t pde, *pdep;
1994 pt_entry_t pte, PG_RW, PG_V;
2000 PG_RW = pmap_rw_bit(pmap);
2001 PG_V = pmap_valid_bit(pmap);
2004 pdep = pmap_pde(pmap, va);
2005 if (pdep != NULL && (pde = *pdep)) {
2007 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2008 if (vm_page_pa_tryrelock(pmap, (pde &
2009 PG_PS_FRAME) | (va & PDRMASK), &pa))
2011 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
2016 pte = *pmap_pde_to_pte(pdep, va);
2018 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2019 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2022 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
2033 pmap_kextract(vm_offset_t va)
2038 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2039 pa = DMAP_TO_PHYS(va);
2043 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2046 * Beware of a concurrent promotion that changes the
2047 * PDE at this point! For example, vtopte() must not
2048 * be used to access the PTE because it would use the
2049 * new PDE. It is, however, safe to use the old PDE
2050 * because the page table page is preserved by the
2053 pa = *pmap_pde_to_pte(&pde, va);
2054 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2060 /***************************************************
2061 * Low level mapping routines.....
2062 ***************************************************/
2065 * Add a wired page to the kva.
2066 * Note: not SMP coherent.
2069 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2074 pte_store(pte, pa | X86_PG_RW | X86_PG_V | X86_PG_G);
2077 static __inline void
2078 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2084 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2085 pte_store(pte, pa | X86_PG_RW | X86_PG_V | X86_PG_G | cache_bits);
2089 * Remove a page from the kernel pagetables.
2090 * Note: not SMP coherent.
2093 pmap_kremove(vm_offset_t va)
2102 * Used to map a range of physical addresses into kernel
2103 * virtual address space.
2105 * The value passed in '*virt' is a suggested virtual address for
2106 * the mapping. Architectures which can support a direct-mapped
2107 * physical to virtual region can return the appropriate address
2108 * within that region, leaving '*virt' unchanged. Other
2109 * architectures should map the pages starting at '*virt' and
2110 * update '*virt' with the first usable address after the mapped
2114 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2116 return PHYS_TO_DMAP(start);
2121 * Add a list of wired pages to the kva
2122 * this routine is only used for temporary
2123 * kernel mappings that do not need to have
2124 * page modification or references recorded.
2125 * Note that old mappings are simply written
2126 * over. The page *must* be wired.
2127 * Note: SMP coherent. Uses a ranged shootdown IPI.
2130 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2132 pt_entry_t *endpte, oldpte, pa, *pte;
2138 endpte = pte + count;
2139 while (pte < endpte) {
2141 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2142 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2143 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2145 pte_store(pte, pa | X86_PG_G | X86_PG_RW | X86_PG_V);
2149 if (__predict_false((oldpte & X86_PG_V) != 0))
2150 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2155 * This routine tears out page mappings from the
2156 * kernel -- it is meant only for temporary mappings.
2157 * Note: SMP coherent. Uses a ranged shootdown IPI.
2160 pmap_qremove(vm_offset_t sva, int count)
2165 while (count-- > 0) {
2166 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2170 pmap_invalidate_range(kernel_pmap, sva, va);
2173 /***************************************************
2174 * Page table page management routines.....
2175 ***************************************************/
2176 static __inline void
2177 pmap_free_zero_pages(struct spglist *free)
2181 while ((m = SLIST_FIRST(free)) != NULL) {
2182 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2183 /* Preserve the page's PG_ZERO setting. */
2184 vm_page_free_toq(m);
2189 * Schedule the specified unused page table page to be freed. Specifically,
2190 * add the page to the specified list of pages that will be released to the
2191 * physical memory manager after the TLB has been updated.
2193 static __inline void
2194 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2195 boolean_t set_PG_ZERO)
2199 m->flags |= PG_ZERO;
2201 m->flags &= ~PG_ZERO;
2202 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2206 * Inserts the specified page table page into the specified pmap's collection
2207 * of idle page table pages. Each of a pmap's page table pages is responsible
2208 * for mapping a distinct range of virtual addresses. The pmap's collection is
2209 * ordered by this virtual address range.
2212 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2215 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2216 return (vm_radix_insert(&pmap->pm_root, mpte));
2220 * Removes the page table page mapping the specified virtual address from the
2221 * specified pmap's collection of idle page table pages, and returns it.
2222 * Otherwise, returns NULL if there is no page table page corresponding to the
2223 * specified virtual address.
2225 static __inline vm_page_t
2226 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
2229 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2230 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
2234 * Decrements a page table page's wire count, which is used to record the
2235 * number of valid page table entries within the page. If the wire count
2236 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2237 * page table page was unmapped and FALSE otherwise.
2239 static inline boolean_t
2240 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2244 if (m->wire_count == 0) {
2245 _pmap_unwire_ptp(pmap, va, m, free);
2252 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2255 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2257 * unmap the page table page
2259 if (m->pindex >= (NUPDE + NUPDPE)) {
2262 pml4 = pmap_pml4e(pmap, va);
2264 } else if (m->pindex >= NUPDE) {
2267 pdp = pmap_pdpe(pmap, va);
2272 pd = pmap_pde(pmap, va);
2275 pmap_resident_count_dec(pmap, 1);
2276 if (m->pindex < NUPDE) {
2277 /* We just released a PT, unhold the matching PD */
2280 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2281 pmap_unwire_ptp(pmap, va, pdpg, free);
2283 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2284 /* We just released a PD, unhold the matching PDP */
2287 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2288 pmap_unwire_ptp(pmap, va, pdppg, free);
2292 * This is a release store so that the ordinary store unmapping
2293 * the page table page is globally performed before TLB shoot-
2296 atomic_subtract_rel_int(&vm_cnt.v_wire_count, 1);
2299 * Put page on a list so that it is released after
2300 * *ALL* TLB shootdown is done
2302 pmap_add_delayed_free_list(m, free, TRUE);
2306 * After removing a page table entry, this routine is used to
2307 * conditionally free the page, and manage the hold/wire counts.
2310 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2311 struct spglist *free)
2315 if (va >= VM_MAXUSER_ADDRESS)
2317 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2318 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2319 return (pmap_unwire_ptp(pmap, va, mpte, free));
2323 pmap_pinit0(pmap_t pmap)
2327 PMAP_LOCK_INIT(pmap);
2328 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2329 pmap->pm_cr3 = KPML4phys;
2330 pmap->pm_root.rt_root = 0;
2331 CPU_ZERO(&pmap->pm_active);
2332 TAILQ_INIT(&pmap->pm_pvchunk);
2333 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2334 pmap->pm_flags = pmap_flags;
2336 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2337 pmap->pm_pcids[i].pm_gen = 0;
2339 PCPU_SET(curpmap, kernel_pmap);
2340 pmap_activate(curthread);
2341 CPU_FILL(&kernel_pmap->pm_active);
2345 pmap_pinit_pml4(vm_page_t pml4pg)
2347 pml4_entry_t *pm_pml4;
2350 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2352 /* Wire in kernel global address entries. */
2353 for (i = 0; i < NKPML4E; i++) {
2354 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2357 for (i = 0; i < ndmpdpphys; i++) {
2358 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2362 /* install self-referential address mapping entry(s) */
2363 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2364 X86_PG_A | X86_PG_M;
2368 * Initialize a preallocated and zeroed pmap structure,
2369 * such as one in a vmspace structure.
2372 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2375 vm_paddr_t pml4phys;
2379 * allocate the page directory page
2381 while ((pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2382 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL)
2385 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2386 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2388 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2389 pmap->pm_pcids[i].pm_gen = 0;
2391 pmap->pm_cr3 = ~0; /* initialize to an invalid value */
2393 if ((pml4pg->flags & PG_ZERO) == 0)
2394 pagezero(pmap->pm_pml4);
2397 * Do not install the host kernel mappings in the nested page
2398 * tables. These mappings are meaningless in the guest physical
2401 if ((pmap->pm_type = pm_type) == PT_X86) {
2402 pmap->pm_cr3 = pml4phys;
2403 pmap_pinit_pml4(pml4pg);
2406 pmap->pm_root.rt_root = 0;
2407 CPU_ZERO(&pmap->pm_active);
2408 TAILQ_INIT(&pmap->pm_pvchunk);
2409 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2410 pmap->pm_flags = flags;
2411 pmap->pm_eptgen = 0;
2417 pmap_pinit(pmap_t pmap)
2420 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2424 * This routine is called if the desired page table page does not exist.
2426 * If page table page allocation fails, this routine may sleep before
2427 * returning NULL. It sleeps only if a lock pointer was given.
2429 * Note: If a page allocation fails at page table level two or three,
2430 * one or two pages may be held during the wait, only to be released
2431 * afterwards. This conservative approach is easily argued to avoid
2435 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2437 vm_page_t m, pdppg, pdpg;
2438 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2440 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2442 PG_A = pmap_accessed_bit(pmap);
2443 PG_M = pmap_modified_bit(pmap);
2444 PG_V = pmap_valid_bit(pmap);
2445 PG_RW = pmap_rw_bit(pmap);
2448 * Allocate a page table page.
2450 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2451 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2452 if (lockp != NULL) {
2453 RELEASE_PV_LIST_LOCK(lockp);
2455 PMAP_ASSERT_NOT_IN_DI();
2461 * Indicate the need to retry. While waiting, the page table
2462 * page may have been allocated.
2466 if ((m->flags & PG_ZERO) == 0)
2470 * Map the pagetable page into the process address space, if
2471 * it isn't already there.
2474 if (ptepindex >= (NUPDE + NUPDPE)) {
2476 vm_pindex_t pml4index;
2478 /* Wire up a new PDPE page */
2479 pml4index = ptepindex - (NUPDE + NUPDPE);
2480 pml4 = &pmap->pm_pml4[pml4index];
2481 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2483 } else if (ptepindex >= NUPDE) {
2484 vm_pindex_t pml4index;
2485 vm_pindex_t pdpindex;
2489 /* Wire up a new PDE page */
2490 pdpindex = ptepindex - NUPDE;
2491 pml4index = pdpindex >> NPML4EPGSHIFT;
2493 pml4 = &pmap->pm_pml4[pml4index];
2494 if ((*pml4 & PG_V) == 0) {
2495 /* Have to allocate a new pdp, recurse */
2496 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2499 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2500 vm_page_free_zero(m);
2504 /* Add reference to pdp page */
2505 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2506 pdppg->wire_count++;
2508 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2510 /* Now find the pdp page */
2511 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2512 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2515 vm_pindex_t pml4index;
2516 vm_pindex_t pdpindex;
2521 /* Wire up a new PTE page */
2522 pdpindex = ptepindex >> NPDPEPGSHIFT;
2523 pml4index = pdpindex >> NPML4EPGSHIFT;
2525 /* First, find the pdp and check that its valid. */
2526 pml4 = &pmap->pm_pml4[pml4index];
2527 if ((*pml4 & PG_V) == 0) {
2528 /* Have to allocate a new pd, recurse */
2529 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2532 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2533 vm_page_free_zero(m);
2536 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2537 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2539 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2540 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2541 if ((*pdp & PG_V) == 0) {
2542 /* Have to allocate a new pd, recurse */
2543 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2546 atomic_subtract_int(&vm_cnt.v_wire_count,
2548 vm_page_free_zero(m);
2552 /* Add reference to the pd page */
2553 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2557 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2559 /* Now we know where the page directory page is */
2560 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2561 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2564 pmap_resident_count_inc(pmap, 1);
2570 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2572 vm_pindex_t pdpindex, ptepindex;
2573 pdp_entry_t *pdpe, PG_V;
2576 PG_V = pmap_valid_bit(pmap);
2579 pdpe = pmap_pdpe(pmap, va);
2580 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2581 /* Add a reference to the pd page. */
2582 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2585 /* Allocate a pd page. */
2586 ptepindex = pmap_pde_pindex(va);
2587 pdpindex = ptepindex >> NPDPEPGSHIFT;
2588 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2589 if (pdpg == NULL && lockp != NULL)
2596 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2598 vm_pindex_t ptepindex;
2599 pd_entry_t *pd, PG_V;
2602 PG_V = pmap_valid_bit(pmap);
2605 * Calculate pagetable page index
2607 ptepindex = pmap_pde_pindex(va);
2610 * Get the page directory entry
2612 pd = pmap_pde(pmap, va);
2615 * This supports switching from a 2MB page to a
2618 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2619 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2621 * Invalidation of the 2MB page mapping may have caused
2622 * the deallocation of the underlying PD page.
2629 * If the page table page is mapped, we just increment the
2630 * hold count, and activate it.
2632 if (pd != NULL && (*pd & PG_V) != 0) {
2633 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2637 * Here if the pte page isn't mapped, or if it has been
2640 m = _pmap_allocpte(pmap, ptepindex, lockp);
2641 if (m == NULL && lockp != NULL)
2648 /***************************************************
2649 * Pmap allocation/deallocation routines.
2650 ***************************************************/
2653 * Release any resources held by the given physical map.
2654 * Called when a pmap initialized by pmap_pinit is being released.
2655 * Should only be called if the map contains no valid mappings.
2658 pmap_release(pmap_t pmap)
2663 KASSERT(pmap->pm_stats.resident_count == 0,
2664 ("pmap_release: pmap resident count %ld != 0",
2665 pmap->pm_stats.resident_count));
2666 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2667 ("pmap_release: pmap has reserved page table page(s)"));
2668 KASSERT(CPU_EMPTY(&pmap->pm_active),
2669 ("releasing active pmap %p", pmap));
2671 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2673 for (i = 0; i < NKPML4E; i++) /* KVA */
2674 pmap->pm_pml4[KPML4BASE + i] = 0;
2675 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
2676 pmap->pm_pml4[DMPML4I + i] = 0;
2677 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
2680 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2681 vm_page_free_zero(m);
2685 kvm_size(SYSCTL_HANDLER_ARGS)
2687 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2689 return sysctl_handle_long(oidp, &ksize, 0, req);
2691 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2692 0, 0, kvm_size, "LU", "Size of KVM");
2695 kvm_free(SYSCTL_HANDLER_ARGS)
2697 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2699 return sysctl_handle_long(oidp, &kfree, 0, req);
2701 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2702 0, 0, kvm_free, "LU", "Amount of KVM free");
2705 * grow the number of kernel page table entries, if needed
2708 pmap_growkernel(vm_offset_t addr)
2712 pd_entry_t *pde, newpdir;
2715 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2718 * Return if "addr" is within the range of kernel page table pages
2719 * that were preallocated during pmap bootstrap. Moreover, leave
2720 * "kernel_vm_end" and the kernel page table as they were.
2722 * The correctness of this action is based on the following
2723 * argument: vm_map_insert() allocates contiguous ranges of the
2724 * kernel virtual address space. It calls this function if a range
2725 * ends after "kernel_vm_end". If the kernel is mapped between
2726 * "kernel_vm_end" and "addr", then the range cannot begin at
2727 * "kernel_vm_end". In fact, its beginning address cannot be less
2728 * than the kernel. Thus, there is no immediate need to allocate
2729 * any new kernel page table pages between "kernel_vm_end" and
2732 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
2735 addr = roundup2(addr, NBPDR);
2736 if (addr - 1 >= kernel_map->max_offset)
2737 addr = kernel_map->max_offset;
2738 while (kernel_vm_end < addr) {
2739 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
2740 if ((*pdpe & X86_PG_V) == 0) {
2741 /* We need a new PDP entry */
2742 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
2743 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
2744 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2746 panic("pmap_growkernel: no memory to grow kernel");
2747 if ((nkpg->flags & PG_ZERO) == 0)
2748 pmap_zero_page(nkpg);
2749 paddr = VM_PAGE_TO_PHYS(nkpg);
2750 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
2751 X86_PG_A | X86_PG_M);
2752 continue; /* try again */
2754 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
2755 if ((*pde & X86_PG_V) != 0) {
2756 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2757 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2758 kernel_vm_end = kernel_map->max_offset;
2764 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
2765 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
2768 panic("pmap_growkernel: no memory to grow kernel");
2769 if ((nkpg->flags & PG_ZERO) == 0)
2770 pmap_zero_page(nkpg);
2771 paddr = VM_PAGE_TO_PHYS(nkpg);
2772 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
2773 pde_store(pde, newpdir);
2775 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2776 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2777 kernel_vm_end = kernel_map->max_offset;
2784 /***************************************************
2785 * page management routines.
2786 ***************************************************/
2788 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
2789 CTASSERT(_NPCM == 3);
2790 CTASSERT(_NPCPV == 168);
2792 static __inline struct pv_chunk *
2793 pv_to_chunk(pv_entry_t pv)
2796 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
2799 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
2801 #define PC_FREE0 0xfffffffffffffffful
2802 #define PC_FREE1 0xfffffffffffffffful
2803 #define PC_FREE2 0x000000fffffffffful
2805 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
2808 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2810 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2811 "Current number of pv entry chunks");
2812 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2813 "Current number of pv entry chunks allocated");
2814 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2815 "Current number of pv entry chunks frees");
2816 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
2817 "Number of times tried to get a chunk page but failed.");
2819 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
2820 static int pv_entry_spare;
2822 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2823 "Current number of pv entry frees");
2824 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
2825 "Current number of pv entry allocs");
2826 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2827 "Current number of pv entries");
2828 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2829 "Current number of spare pv entries");
2833 * We are in a serious low memory condition. Resort to
2834 * drastic measures to free some pages so we can allocate
2835 * another pv entry chunk.
2837 * Returns NULL if PV entries were reclaimed from the specified pmap.
2839 * We do not, however, unmap 2mpages because subsequent accesses will
2840 * allocate per-page pv entries until repromotion occurs, thereby
2841 * exacerbating the shortage of free pv entries.
2844 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
2846 struct pch new_tail;
2847 struct pv_chunk *pc;
2848 struct md_page *pvh;
2851 pt_entry_t *pte, tpte;
2852 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
2856 struct spglist free;
2858 int bit, field, freed;
2860 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2861 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
2864 PG_G = PG_A = PG_M = PG_RW = 0;
2866 TAILQ_INIT(&new_tail);
2867 pmap_delayed_invl_started();
2868 mtx_lock(&pv_chunks_mutex);
2869 while ((pc = TAILQ_FIRST(&pv_chunks)) != NULL && SLIST_EMPTY(&free)) {
2870 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2871 mtx_unlock(&pv_chunks_mutex);
2872 if (pmap != pc->pc_pmap) {
2874 pmap_invalidate_all(pmap);
2875 if (pmap != locked_pmap)
2878 pmap_delayed_invl_finished();
2879 pmap_delayed_invl_started();
2881 /* Avoid deadlock and lock recursion. */
2882 if (pmap > locked_pmap) {
2883 RELEASE_PV_LIST_LOCK(lockp);
2885 } else if (pmap != locked_pmap &&
2886 !PMAP_TRYLOCK(pmap)) {
2888 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2889 mtx_lock(&pv_chunks_mutex);
2892 PG_G = pmap_global_bit(pmap);
2893 PG_A = pmap_accessed_bit(pmap);
2894 PG_M = pmap_modified_bit(pmap);
2895 PG_RW = pmap_rw_bit(pmap);
2899 * Destroy every non-wired, 4 KB page mapping in the chunk.
2902 for (field = 0; field < _NPCM; field++) {
2903 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2904 inuse != 0; inuse &= ~(1UL << bit)) {
2906 pv = &pc->pc_pventry[field * 64 + bit];
2908 pde = pmap_pde(pmap, va);
2909 if ((*pde & PG_PS) != 0)
2911 pte = pmap_pde_to_pte(pde, va);
2912 if ((*pte & PG_W) != 0)
2914 tpte = pte_load_clear(pte);
2915 if ((tpte & PG_G) != 0)
2916 pmap_invalidate_page(pmap, va);
2917 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
2918 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
2920 if ((tpte & PG_A) != 0)
2921 vm_page_aflag_set(m, PGA_REFERENCED);
2922 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
2923 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
2925 if (TAILQ_EMPTY(&m->md.pv_list) &&
2926 (m->flags & PG_FICTITIOUS) == 0) {
2927 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
2928 if (TAILQ_EMPTY(&pvh->pv_list)) {
2929 vm_page_aflag_clear(m,
2933 pmap_delayed_invl_page(m);
2934 pc->pc_map[field] |= 1UL << bit;
2935 pmap_unuse_pt(pmap, va, *pde, &free);
2940 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2941 mtx_lock(&pv_chunks_mutex);
2944 /* Every freed mapping is for a 4 KB page. */
2945 pmap_resident_count_dec(pmap, freed);
2946 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
2947 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
2948 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
2949 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2950 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
2951 pc->pc_map[2] == PC_FREE2) {
2952 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
2953 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
2954 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
2955 /* Entire chunk is free; return it. */
2956 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
2957 dump_drop_page(m_pc->phys_addr);
2958 mtx_lock(&pv_chunks_mutex);
2961 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2962 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2963 mtx_lock(&pv_chunks_mutex);
2964 /* One freed pv entry in locked_pmap is sufficient. */
2965 if (pmap == locked_pmap)
2968 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
2969 mtx_unlock(&pv_chunks_mutex);
2971 pmap_invalidate_all(pmap);
2972 if (pmap != locked_pmap)
2975 pmap_delayed_invl_finished();
2976 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
2977 m_pc = SLIST_FIRST(&free);
2978 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2979 /* Recycle a freed page table page. */
2980 m_pc->wire_count = 1;
2981 atomic_add_int(&vm_cnt.v_wire_count, 1);
2983 pmap_free_zero_pages(&free);
2988 * free the pv_entry back to the free list
2991 free_pv_entry(pmap_t pmap, pv_entry_t pv)
2993 struct pv_chunk *pc;
2994 int idx, field, bit;
2996 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2997 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
2998 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
2999 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3000 pc = pv_to_chunk(pv);
3001 idx = pv - &pc->pc_pventry[0];
3004 pc->pc_map[field] |= 1ul << bit;
3005 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3006 pc->pc_map[2] != PC_FREE2) {
3007 /* 98% of the time, pc is already at the head of the list. */
3008 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3009 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3010 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3014 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3019 free_pv_chunk(struct pv_chunk *pc)
3023 mtx_lock(&pv_chunks_mutex);
3024 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3025 mtx_unlock(&pv_chunks_mutex);
3026 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3027 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3028 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3029 /* entire chunk is free, return it */
3030 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3031 dump_drop_page(m->phys_addr);
3032 vm_page_unwire(m, PQ_NONE);
3037 * Returns a new PV entry, allocating a new PV chunk from the system when
3038 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3039 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3042 * The given PV list lock may be released.
3045 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3049 struct pv_chunk *pc;
3052 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3053 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3055 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3057 for (field = 0; field < _NPCM; field++) {
3058 if (pc->pc_map[field]) {
3059 bit = bsfq(pc->pc_map[field]);
3063 if (field < _NPCM) {
3064 pv = &pc->pc_pventry[field * 64 + bit];
3065 pc->pc_map[field] &= ~(1ul << bit);
3066 /* If this was the last item, move it to tail */
3067 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3068 pc->pc_map[2] == 0) {
3069 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3070 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3073 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3074 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3078 /* No free items, allocate another chunk */
3079 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3082 if (lockp == NULL) {
3083 PV_STAT(pc_chunk_tryfail++);
3086 m = reclaim_pv_chunk(pmap, lockp);
3090 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3091 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3092 dump_add_page(m->phys_addr);
3093 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3095 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3096 pc->pc_map[1] = PC_FREE1;
3097 pc->pc_map[2] = PC_FREE2;
3098 mtx_lock(&pv_chunks_mutex);
3099 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3100 mtx_unlock(&pv_chunks_mutex);
3101 pv = &pc->pc_pventry[0];
3102 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3103 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3104 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3109 * Returns the number of one bits within the given PV chunk map.
3111 * The erratas for Intel processors state that "POPCNT Instruction May
3112 * Take Longer to Execute Than Expected". It is believed that the
3113 * issue is the spurious dependency on the destination register.
3114 * Provide a hint to the register rename logic that the destination
3115 * value is overwritten, by clearing it, as suggested in the
3116 * optimization manual. It should be cheap for unaffected processors
3119 * Reference numbers for erratas are
3120 * 4th Gen Core: HSD146
3121 * 5th Gen Core: BDM85
3122 * 6th Gen Core: SKL029
3125 popcnt_pc_map_pq(uint64_t *map)
3129 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3130 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3131 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3132 : "=&r" (result), "=&r" (tmp)
3133 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3138 * Ensure that the number of spare PV entries in the specified pmap meets or
3139 * exceeds the given count, "needed".
3141 * The given PV list lock may be released.
3144 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3146 struct pch new_tail;
3147 struct pv_chunk *pc;
3151 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3152 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3155 * Newly allocated PV chunks must be stored in a private list until
3156 * the required number of PV chunks have been allocated. Otherwise,
3157 * reclaim_pv_chunk() could recycle one of these chunks. In
3158 * contrast, these chunks must be added to the pmap upon allocation.
3160 TAILQ_INIT(&new_tail);
3163 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3165 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3166 bit_count((bitstr_t *)pc->pc_map, 0,
3167 sizeof(pc->pc_map) * NBBY, &free);
3170 free = popcnt_pc_map_pq(pc->pc_map);
3174 if (avail >= needed)
3177 for (; avail < needed; avail += _NPCPV) {
3178 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3181 m = reclaim_pv_chunk(pmap, lockp);
3185 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3186 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3187 dump_add_page(m->phys_addr);
3188 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3190 pc->pc_map[0] = PC_FREE0;
3191 pc->pc_map[1] = PC_FREE1;
3192 pc->pc_map[2] = PC_FREE2;
3193 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3194 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3195 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3197 if (!TAILQ_EMPTY(&new_tail)) {
3198 mtx_lock(&pv_chunks_mutex);
3199 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3200 mtx_unlock(&pv_chunks_mutex);
3205 * First find and then remove the pv entry for the specified pmap and virtual
3206 * address from the specified pv list. Returns the pv entry if found and NULL
3207 * otherwise. This operation can be performed on pv lists for either 4KB or
3208 * 2MB page mappings.
3210 static __inline pv_entry_t
3211 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3215 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3216 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3217 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3226 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3227 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3228 * entries for each of the 4KB page mappings.
3231 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3232 struct rwlock **lockp)
3234 struct md_page *pvh;
3235 struct pv_chunk *pc;
3237 vm_offset_t va_last;
3241 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3242 KASSERT((pa & PDRMASK) == 0,
3243 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3244 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3247 * Transfer the 2mpage's pv entry for this mapping to the first
3248 * page's pv list. Once this transfer begins, the pv list lock
3249 * must not be released until the last pv entry is reinstantiated.
3251 pvh = pa_to_pvh(pa);
3252 va = trunc_2mpage(va);
3253 pv = pmap_pvh_remove(pvh, pmap, va);
3254 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3255 m = PHYS_TO_VM_PAGE(pa);
3256 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3258 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3259 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3260 va_last = va + NBPDR - PAGE_SIZE;
3262 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3263 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3264 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3265 for (field = 0; field < _NPCM; field++) {
3266 while (pc->pc_map[field]) {
3267 bit = bsfq(pc->pc_map[field]);
3268 pc->pc_map[field] &= ~(1ul << bit);
3269 pv = &pc->pc_pventry[field * 64 + bit];
3273 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3274 ("pmap_pv_demote_pde: page %p is not managed", m));
3275 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3281 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3282 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3285 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3286 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3287 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3289 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3290 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3294 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3295 * replace the many pv entries for the 4KB page mappings by a single pv entry
3296 * for the 2MB page mapping.
3299 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3300 struct rwlock **lockp)
3302 struct md_page *pvh;
3304 vm_offset_t va_last;
3307 KASSERT((pa & PDRMASK) == 0,
3308 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3309 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3312 * Transfer the first page's pv entry for this mapping to the 2mpage's
3313 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3314 * a transfer avoids the possibility that get_pv_entry() calls
3315 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3316 * mappings that is being promoted.
3318 m = PHYS_TO_VM_PAGE(pa);
3319 va = trunc_2mpage(va);
3320 pv = pmap_pvh_remove(&m->md, pmap, va);
3321 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3322 pvh = pa_to_pvh(pa);
3323 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3325 /* Free the remaining NPTEPG - 1 pv entries. */
3326 va_last = va + NBPDR - PAGE_SIZE;
3330 pmap_pvh_free(&m->md, pmap, va);
3331 } while (va < va_last);
3335 * First find and then destroy the pv entry for the specified pmap and virtual
3336 * address. This operation can be performed on pv lists for either 4KB or 2MB
3340 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3344 pv = pmap_pvh_remove(pvh, pmap, va);
3345 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3346 free_pv_entry(pmap, pv);
3350 * Conditionally create the PV entry for a 4KB page mapping if the required
3351 * memory can be allocated without resorting to reclamation.
3354 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3355 struct rwlock **lockp)
3359 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3360 /* Pass NULL instead of the lock pointer to disable reclamation. */
3361 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3363 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3364 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3372 * Conditionally create the PV entry for a 2MB page mapping if the required
3373 * memory can be allocated without resorting to reclamation.
3376 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3377 struct rwlock **lockp)
3379 struct md_page *pvh;
3382 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3383 /* Pass NULL instead of the lock pointer to disable reclamation. */
3384 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3386 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3387 pvh = pa_to_pvh(pa);
3388 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3396 * Fills a page table page with mappings to consecutive physical pages.
3399 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3403 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3405 newpte += PAGE_SIZE;
3410 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3411 * mapping is invalidated.
3414 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3416 struct rwlock *lock;
3420 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3427 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3428 struct rwlock **lockp)
3430 pd_entry_t newpde, oldpde;
3431 pt_entry_t *firstpte, newpte;
3432 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3435 struct spglist free;
3439 PG_G = pmap_global_bit(pmap);
3440 PG_A = pmap_accessed_bit(pmap);
3441 PG_M = pmap_modified_bit(pmap);
3442 PG_RW = pmap_rw_bit(pmap);
3443 PG_V = pmap_valid_bit(pmap);
3444 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3446 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3448 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3449 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3450 if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
3452 KASSERT((oldpde & PG_W) == 0,
3453 ("pmap_demote_pde: page table page for a wired mapping"
3457 * Invalidate the 2MB page mapping and return "failure" if the
3458 * mapping was never accessed or the allocation of the new
3459 * page table page fails. If the 2MB page mapping belongs to
3460 * the direct map region of the kernel's address space, then
3461 * the page allocation request specifies the highest possible
3462 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3463 * normal. Page table pages are preallocated for every other
3464 * part of the kernel address space, so the direct map region
3465 * is the only part of the kernel address space that must be
3468 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3469 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3470 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3471 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3473 sva = trunc_2mpage(va);
3474 pmap_remove_pde(pmap, pde, sva, &free, lockp);
3475 pmap_invalidate_range(pmap, sva, sva + NBPDR - 1);
3476 pmap_free_zero_pages(&free);
3477 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3478 " in pmap %p", va, pmap);
3481 if (va < VM_MAXUSER_ADDRESS)
3482 pmap_resident_count_inc(pmap, 1);
3484 mptepa = VM_PAGE_TO_PHYS(mpte);
3485 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3486 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3487 KASSERT((oldpde & PG_A) != 0,
3488 ("pmap_demote_pde: oldpde is missing PG_A"));
3489 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3490 ("pmap_demote_pde: oldpde is missing PG_M"));
3491 newpte = oldpde & ~PG_PS;
3492 newpte = pmap_swap_pat(pmap, newpte);
3495 * If the page table page is new, initialize it.
3497 if (mpte->wire_count == 1) {
3498 mpte->wire_count = NPTEPG;
3499 pmap_fill_ptp(firstpte, newpte);
3501 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3502 ("pmap_demote_pde: firstpte and newpte map different physical"
3506 * If the mapping has changed attributes, update the page table
3509 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3510 pmap_fill_ptp(firstpte, newpte);
3513 * The spare PV entries must be reserved prior to demoting the
3514 * mapping, that is, prior to changing the PDE. Otherwise, the state
3515 * of the PDE and the PV lists will be inconsistent, which can result
3516 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3517 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3518 * PV entry for the 2MB page mapping that is being demoted.
3520 if ((oldpde & PG_MANAGED) != 0)
3521 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3524 * Demote the mapping. This pmap is locked. The old PDE has
3525 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3526 * set. Thus, there is no danger of a race with another
3527 * processor changing the setting of PG_A and/or PG_M between
3528 * the read above and the store below.
3530 if (workaround_erratum383)
3531 pmap_update_pde(pmap, va, pde, newpde);
3533 pde_store(pde, newpde);
3536 * Invalidate a stale recursive mapping of the page table page.
3538 if (va >= VM_MAXUSER_ADDRESS)
3539 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3542 * Demote the PV entry.
3544 if ((oldpde & PG_MANAGED) != 0)
3545 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3547 atomic_add_long(&pmap_pde_demotions, 1);
3548 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3549 " in pmap %p", va, pmap);
3554 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3557 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3563 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3564 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3565 mpte = pmap_remove_pt_page(pmap, va);
3567 panic("pmap_remove_kernel_pde: Missing pt page.");
3569 mptepa = VM_PAGE_TO_PHYS(mpte);
3570 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3573 * Initialize the page table page.
3575 pagezero((void *)PHYS_TO_DMAP(mptepa));
3578 * Demote the mapping.
3580 if (workaround_erratum383)
3581 pmap_update_pde(pmap, va, pde, newpde);
3583 pde_store(pde, newpde);
3586 * Invalidate a stale recursive mapping of the page table page.
3588 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3592 * pmap_remove_pde: do the things to unmap a superpage in a process
3595 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
3596 struct spglist *free, struct rwlock **lockp)
3598 struct md_page *pvh;
3600 vm_offset_t eva, va;
3602 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3604 PG_G = pmap_global_bit(pmap);
3605 PG_A = pmap_accessed_bit(pmap);
3606 PG_M = pmap_modified_bit(pmap);
3607 PG_RW = pmap_rw_bit(pmap);
3609 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3610 KASSERT((sva & PDRMASK) == 0,
3611 ("pmap_remove_pde: sva is not 2mpage aligned"));
3612 oldpde = pte_load_clear(pdq);
3614 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
3617 * When workaround_erratum383 is false, a promotion to a 2M
3618 * page mapping does not invalidate the 512 4K page mappings
3619 * from the TLB. Consequently, at this point, the TLB may
3620 * hold both 4K and 2M page mappings. Therefore, the entire
3621 * range of addresses must be invalidated here. In contrast,
3622 * when workaround_erratum383 is true, a promotion does
3623 * invalidate the 512 4K page mappings, and so a single INVLPG
3624 * suffices to invalidate the 2M page mapping.
3626 if ((oldpde & PG_G) != 0) {
3627 if (workaround_erratum383)
3628 pmap_invalidate_page(kernel_pmap, sva);
3630 pmap_invalidate_range(kernel_pmap, sva,
3634 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
3635 if (oldpde & PG_MANAGED) {
3636 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
3637 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
3638 pmap_pvh_free(pvh, pmap, sva);
3640 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3641 va < eva; va += PAGE_SIZE, m++) {
3642 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3645 vm_page_aflag_set(m, PGA_REFERENCED);
3646 if (TAILQ_EMPTY(&m->md.pv_list) &&
3647 TAILQ_EMPTY(&pvh->pv_list))
3648 vm_page_aflag_clear(m, PGA_WRITEABLE);
3649 pmap_delayed_invl_page(m);
3652 if (pmap == kernel_pmap) {
3653 pmap_remove_kernel_pde(pmap, pdq, sva);
3655 mpte = pmap_remove_pt_page(pmap, sva);
3657 pmap_resident_count_dec(pmap, 1);
3658 KASSERT(mpte->wire_count == NPTEPG,
3659 ("pmap_remove_pde: pte page wire count error"));
3660 mpte->wire_count = 0;
3661 pmap_add_delayed_free_list(mpte, free, FALSE);
3662 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3665 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
3669 * pmap_remove_pte: do the things to unmap a page in a process
3672 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
3673 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
3675 struct md_page *pvh;
3676 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
3679 PG_A = pmap_accessed_bit(pmap);
3680 PG_M = pmap_modified_bit(pmap);
3681 PG_RW = pmap_rw_bit(pmap);
3683 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3684 oldpte = pte_load_clear(ptq);
3686 pmap->pm_stats.wired_count -= 1;
3687 pmap_resident_count_dec(pmap, 1);
3688 if (oldpte & PG_MANAGED) {
3689 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
3690 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3693 vm_page_aflag_set(m, PGA_REFERENCED);
3694 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3695 pmap_pvh_free(&m->md, pmap, va);
3696 if (TAILQ_EMPTY(&m->md.pv_list) &&
3697 (m->flags & PG_FICTITIOUS) == 0) {
3698 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3699 if (TAILQ_EMPTY(&pvh->pv_list))
3700 vm_page_aflag_clear(m, PGA_WRITEABLE);
3702 pmap_delayed_invl_page(m);
3704 return (pmap_unuse_pt(pmap, va, ptepde, free));
3708 * Remove a single page from a process address space
3711 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
3712 struct spglist *free)
3714 struct rwlock *lock;
3715 pt_entry_t *pte, PG_V;
3717 PG_V = pmap_valid_bit(pmap);
3718 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3719 if ((*pde & PG_V) == 0)
3721 pte = pmap_pde_to_pte(pde, va);
3722 if ((*pte & PG_V) == 0)
3725 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
3728 pmap_invalidate_page(pmap, va);
3732 * Remove the given range of addresses from the specified map.
3734 * It is assumed that the start and end are properly
3735 * rounded to the page size.
3738 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3740 struct rwlock *lock;
3741 vm_offset_t va, va_next;
3742 pml4_entry_t *pml4e;
3744 pd_entry_t ptpaddr, *pde;
3745 pt_entry_t *pte, PG_G, PG_V;
3746 struct spglist free;
3749 PG_G = pmap_global_bit(pmap);
3750 PG_V = pmap_valid_bit(pmap);
3753 * Perform an unsynchronized read. This is, however, safe.
3755 if (pmap->pm_stats.resident_count == 0)
3761 pmap_delayed_invl_started();
3765 * special handling of removing one page. a very
3766 * common operation and easy to short circuit some
3769 if (sva + PAGE_SIZE == eva) {
3770 pde = pmap_pde(pmap, sva);
3771 if (pde && (*pde & PG_PS) == 0) {
3772 pmap_remove_page(pmap, sva, pde, &free);
3778 for (; sva < eva; sva = va_next) {
3780 if (pmap->pm_stats.resident_count == 0)
3783 pml4e = pmap_pml4e(pmap, sva);
3784 if ((*pml4e & PG_V) == 0) {
3785 va_next = (sva + NBPML4) & ~PML4MASK;
3791 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
3792 if ((*pdpe & PG_V) == 0) {
3793 va_next = (sva + NBPDP) & ~PDPMASK;
3800 * Calculate index for next page table.
3802 va_next = (sva + NBPDR) & ~PDRMASK;
3806 pde = pmap_pdpe_to_pde(pdpe, sva);
3810 * Weed out invalid mappings.
3816 * Check for large page.
3818 if ((ptpaddr & PG_PS) != 0) {
3820 * Are we removing the entire large page? If not,
3821 * demote the mapping and fall through.
3823 if (sva + NBPDR == va_next && eva >= va_next) {
3825 * The TLB entry for a PG_G mapping is
3826 * invalidated by pmap_remove_pde().
3828 if ((ptpaddr & PG_G) == 0)
3830 pmap_remove_pde(pmap, pde, sva, &free, &lock);
3832 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
3834 /* The large page mapping was destroyed. */
3841 * Limit our scan to either the end of the va represented
3842 * by the current page table page, or to the end of the
3843 * range being removed.
3849 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
3852 if (va != va_next) {
3853 pmap_invalidate_range(pmap, va, sva);
3858 if ((*pte & PG_G) == 0)
3860 else if (va == va_next)
3862 if (pmap_remove_pte(pmap, pte, sva, ptpaddr, &free,
3869 pmap_invalidate_range(pmap, va, sva);
3875 pmap_invalidate_all(pmap);
3877 pmap_delayed_invl_finished();
3878 pmap_free_zero_pages(&free);
3882 * Routine: pmap_remove_all
3884 * Removes this physical page from
3885 * all physical maps in which it resides.
3886 * Reflects back modify bits to the pager.
3889 * Original versions of this routine were very
3890 * inefficient because they iteratively called
3891 * pmap_remove (slow...)
3895 pmap_remove_all(vm_page_t m)
3897 struct md_page *pvh;
3900 struct rwlock *lock;
3901 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
3904 struct spglist free;
3905 int pvh_gen, md_gen;
3907 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3908 ("pmap_remove_all: page %p is not managed", m));
3910 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3911 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
3912 pa_to_pvh(VM_PAGE_TO_PHYS(m));
3915 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
3917 if (!PMAP_TRYLOCK(pmap)) {
3918 pvh_gen = pvh->pv_gen;
3922 if (pvh_gen != pvh->pv_gen) {
3929 pde = pmap_pde(pmap, va);
3930 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
3933 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3935 if (!PMAP_TRYLOCK(pmap)) {
3936 pvh_gen = pvh->pv_gen;
3937 md_gen = m->md.pv_gen;
3941 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
3947 PG_A = pmap_accessed_bit(pmap);
3948 PG_M = pmap_modified_bit(pmap);
3949 PG_RW = pmap_rw_bit(pmap);
3950 pmap_resident_count_dec(pmap, 1);
3951 pde = pmap_pde(pmap, pv->pv_va);
3952 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
3953 " a 2mpage in page %p's pv list", m));
3954 pte = pmap_pde_to_pte(pde, pv->pv_va);
3955 tpte = pte_load_clear(pte);
3957 pmap->pm_stats.wired_count--;
3959 vm_page_aflag_set(m, PGA_REFERENCED);
3962 * Update the vm_page_t clean and reference bits.
3964 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3966 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
3967 pmap_invalidate_page(pmap, pv->pv_va);
3968 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3970 free_pv_entry(pmap, pv);
3973 vm_page_aflag_clear(m, PGA_WRITEABLE);
3975 pmap_delayed_invl_wait(m);
3976 pmap_free_zero_pages(&free);
3980 * pmap_protect_pde: do the things to protect a 2mpage in a process
3983 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
3985 pd_entry_t newpde, oldpde;
3986 vm_offset_t eva, va;
3988 boolean_t anychanged;
3989 pt_entry_t PG_G, PG_M, PG_RW;
3991 PG_G = pmap_global_bit(pmap);
3992 PG_M = pmap_modified_bit(pmap);
3993 PG_RW = pmap_rw_bit(pmap);
3995 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3996 KASSERT((sva & PDRMASK) == 0,
3997 ("pmap_protect_pde: sva is not 2mpage aligned"));
4000 oldpde = newpde = *pde;
4001 if (oldpde & PG_MANAGED) {
4003 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4004 va < eva; va += PAGE_SIZE, m++)
4005 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
4008 if ((prot & VM_PROT_WRITE) == 0)
4009 newpde &= ~(PG_RW | PG_M);
4010 if ((prot & VM_PROT_EXECUTE) == 0)
4012 if (newpde != oldpde) {
4013 if (!atomic_cmpset_long(pde, oldpde, newpde))
4015 if (oldpde & PG_G) {
4016 /* See pmap_remove_pde() for explanation. */
4017 if (workaround_erratum383)
4018 pmap_invalidate_page(kernel_pmap, sva);
4020 pmap_invalidate_range(kernel_pmap, sva,
4025 return (anychanged);
4029 * Set the physical protection on the
4030 * specified range of this map as requested.
4033 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4035 vm_offset_t va_next;
4036 pml4_entry_t *pml4e;
4038 pd_entry_t ptpaddr, *pde;
4039 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4040 boolean_t anychanged;
4042 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4043 if (prot == VM_PROT_NONE) {
4044 pmap_remove(pmap, sva, eva);
4048 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4049 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4052 PG_G = pmap_global_bit(pmap);
4053 PG_M = pmap_modified_bit(pmap);
4054 PG_V = pmap_valid_bit(pmap);
4055 PG_RW = pmap_rw_bit(pmap);
4059 for (; sva < eva; sva = va_next) {
4061 pml4e = pmap_pml4e(pmap, sva);
4062 if ((*pml4e & PG_V) == 0) {
4063 va_next = (sva + NBPML4) & ~PML4MASK;
4069 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4070 if ((*pdpe & PG_V) == 0) {
4071 va_next = (sva + NBPDP) & ~PDPMASK;
4077 va_next = (sva + NBPDR) & ~PDRMASK;
4081 pde = pmap_pdpe_to_pde(pdpe, sva);
4085 * Weed out invalid mappings.
4091 * Check for large page.
4093 if ((ptpaddr & PG_PS) != 0) {
4095 * Are we protecting the entire large page? If not,
4096 * demote the mapping and fall through.
4098 if (sva + NBPDR == va_next && eva >= va_next) {
4100 * The TLB entry for a PG_G mapping is
4101 * invalidated by pmap_protect_pde().
4103 if (pmap_protect_pde(pmap, pde, sva, prot))
4106 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4108 * The large page mapping was destroyed.
4117 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4119 pt_entry_t obits, pbits;
4123 obits = pbits = *pte;
4124 if ((pbits & PG_V) == 0)
4127 if ((prot & VM_PROT_WRITE) == 0) {
4128 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4129 (PG_MANAGED | PG_M | PG_RW)) {
4130 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4133 pbits &= ~(PG_RW | PG_M);
4135 if ((prot & VM_PROT_EXECUTE) == 0)
4138 if (pbits != obits) {
4139 if (!atomic_cmpset_long(pte, obits, pbits))
4142 pmap_invalidate_page(pmap, sva);
4149 pmap_invalidate_all(pmap);
4154 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4155 * single page table page (PTP) to a single 2MB page mapping. For promotion
4156 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4157 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4158 * identical characteristics.
4161 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4162 struct rwlock **lockp)
4165 pt_entry_t *firstpte, oldpte, pa, *pte;
4166 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4170 PG_A = pmap_accessed_bit(pmap);
4171 PG_G = pmap_global_bit(pmap);
4172 PG_M = pmap_modified_bit(pmap);
4173 PG_V = pmap_valid_bit(pmap);
4174 PG_RW = pmap_rw_bit(pmap);
4175 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4177 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4180 * Examine the first PTE in the specified PTP. Abort if this PTE is
4181 * either invalid, unused, or does not map the first 4KB physical page
4182 * within a 2MB page.
4184 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4187 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4188 atomic_add_long(&pmap_pde_p_failures, 1);
4189 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4190 " in pmap %p", va, pmap);
4193 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4195 * When PG_M is already clear, PG_RW can be cleared without
4196 * a TLB invalidation.
4198 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4204 * Examine each of the other PTEs in the specified PTP. Abort if this
4205 * PTE maps an unexpected 4KB physical page or does not have identical
4206 * characteristics to the first PTE.
4208 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4209 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4212 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4213 atomic_add_long(&pmap_pde_p_failures, 1);
4214 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4215 " in pmap %p", va, pmap);
4218 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4220 * When PG_M is already clear, PG_RW can be cleared
4221 * without a TLB invalidation.
4223 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4226 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4227 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4228 (va & ~PDRMASK), pmap);
4230 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4231 atomic_add_long(&pmap_pde_p_failures, 1);
4232 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4233 " in pmap %p", va, pmap);
4240 * Save the page table page in its current state until the PDE
4241 * mapping the superpage is demoted by pmap_demote_pde() or
4242 * destroyed by pmap_remove_pde().
4244 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4245 KASSERT(mpte >= vm_page_array &&
4246 mpte < &vm_page_array[vm_page_array_size],
4247 ("pmap_promote_pde: page table page is out of range"));
4248 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4249 ("pmap_promote_pde: page table page's pindex is wrong"));
4250 if (pmap_insert_pt_page(pmap, mpte)) {
4251 atomic_add_long(&pmap_pde_p_failures, 1);
4253 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4259 * Promote the pv entries.
4261 if ((newpde & PG_MANAGED) != 0)
4262 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4265 * Propagate the PAT index to its proper position.
4267 newpde = pmap_swap_pat(pmap, newpde);
4270 * Map the superpage.
4272 if (workaround_erratum383)
4273 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4275 pde_store(pde, PG_PS | newpde);
4277 atomic_add_long(&pmap_pde_promotions, 1);
4278 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4279 " in pmap %p", va, pmap);
4283 * Insert the given physical page (p) at
4284 * the specified virtual address (v) in the
4285 * target physical map with the protection requested.
4287 * If specified, the page will be wired down, meaning
4288 * that the related pte can not be reclaimed.
4290 * NB: This is the only routine which MAY NOT lazy-evaluate
4291 * or lose information. That is, this routine must actually
4292 * insert this page into the given map NOW.
4294 * When destroying both a page table and PV entry, this function
4295 * performs the TLB invalidation before releasing the PV list
4296 * lock, so we do not need pmap_delayed_invl_page() calls here.
4299 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4300 u_int flags, int8_t psind __unused)
4302 struct rwlock *lock;
4304 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4305 pt_entry_t newpte, origpte;
4311 PG_A = pmap_accessed_bit(pmap);
4312 PG_G = pmap_global_bit(pmap);
4313 PG_M = pmap_modified_bit(pmap);
4314 PG_V = pmap_valid_bit(pmap);
4315 PG_RW = pmap_rw_bit(pmap);
4317 va = trunc_page(va);
4318 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4319 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4320 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4322 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4323 va >= kmi.clean_eva,
4324 ("pmap_enter: managed mapping within the clean submap"));
4325 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4326 VM_OBJECT_ASSERT_LOCKED(m->object);
4327 pa = VM_PAGE_TO_PHYS(m);
4328 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4329 if ((flags & VM_PROT_WRITE) != 0)
4331 if ((prot & VM_PROT_WRITE) != 0)
4333 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4334 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4335 if ((prot & VM_PROT_EXECUTE) == 0)
4337 if ((flags & PMAP_ENTER_WIRED) != 0)
4339 if (va < VM_MAXUSER_ADDRESS)
4341 if (pmap == kernel_pmap)
4343 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, 0);
4346 * Set modified bit gratuitously for writeable mappings if
4347 * the page is unmanaged. We do not want to take a fault
4348 * to do the dirty bit accounting for these mappings.
4350 if ((m->oflags & VPO_UNMANAGED) != 0) {
4351 if ((newpte & PG_RW) != 0)
4361 * In the case that a page table page is not
4362 * resident, we are creating it here.
4365 pde = pmap_pde(pmap, va);
4366 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4367 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4368 pte = pmap_pde_to_pte(pde, va);
4369 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4370 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4373 } else if (va < VM_MAXUSER_ADDRESS) {
4375 * Here if the pte page isn't mapped, or if it has been
4378 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4379 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4380 nosleep ? NULL : &lock);
4381 if (mpte == NULL && nosleep) {
4385 return (KERN_RESOURCE_SHORTAGE);
4389 panic("pmap_enter: invalid page directory va=%#lx", va);
4394 * Is the specified virtual address already mapped?
4396 if ((origpte & PG_V) != 0) {
4398 * Wiring change, just update stats. We don't worry about
4399 * wiring PT pages as they remain resident as long as there
4400 * are valid mappings in them. Hence, if a user page is wired,
4401 * the PT page will be also.
4403 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4404 pmap->pm_stats.wired_count++;
4405 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4406 pmap->pm_stats.wired_count--;
4409 * Remove the extra PT page reference.
4413 KASSERT(mpte->wire_count > 0,
4414 ("pmap_enter: missing reference to page table page,"
4419 * Has the physical page changed?
4421 opa = origpte & PG_FRAME;
4424 * No, might be a protection or wiring change.
4426 if ((origpte & PG_MANAGED) != 0) {
4427 newpte |= PG_MANAGED;
4428 if ((newpte & PG_RW) != 0)
4429 vm_page_aflag_set(m, PGA_WRITEABLE);
4431 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4437 * Increment the counters.
4439 if ((newpte & PG_W) != 0)
4440 pmap->pm_stats.wired_count++;
4441 pmap_resident_count_inc(pmap, 1);
4445 * Enter on the PV list if part of our managed memory.
4447 if ((m->oflags & VPO_UNMANAGED) == 0) {
4448 newpte |= PG_MANAGED;
4449 pv = get_pv_entry(pmap, &lock);
4451 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4452 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4454 if ((newpte & PG_RW) != 0)
4455 vm_page_aflag_set(m, PGA_WRITEABLE);
4461 if ((origpte & PG_V) != 0) {
4463 origpte = pte_load_store(pte, newpte);
4464 opa = origpte & PG_FRAME;
4466 if ((origpte & PG_MANAGED) != 0) {
4467 om = PHYS_TO_VM_PAGE(opa);
4468 if ((origpte & (PG_M | PG_RW)) == (PG_M |
4471 if ((origpte & PG_A) != 0)
4472 vm_page_aflag_set(om, PGA_REFERENCED);
4473 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4474 pmap_pvh_free(&om->md, pmap, va);
4475 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4476 TAILQ_EMPTY(&om->md.pv_list) &&
4477 ((om->flags & PG_FICTITIOUS) != 0 ||
4478 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4479 vm_page_aflag_clear(om, PGA_WRITEABLE);
4481 } else if ((newpte & PG_M) == 0 && (origpte & (PG_M |
4482 PG_RW)) == (PG_M | PG_RW)) {
4483 if ((origpte & PG_MANAGED) != 0)
4487 * Although the PTE may still have PG_RW set, TLB
4488 * invalidation may nonetheless be required because
4489 * the PTE no longer has PG_M set.
4491 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4493 * This PTE change does not require TLB invalidation.
4497 if ((origpte & PG_A) != 0)
4498 pmap_invalidate_page(pmap, va);
4500 pte_store(pte, newpte);
4505 * If both the page table page and the reservation are fully
4506 * populated, then attempt promotion.
4508 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4509 pmap_ps_enabled(pmap) &&
4510 (m->flags & PG_FICTITIOUS) == 0 &&
4511 vm_reserv_level_iffullpop(m) == 0)
4512 pmap_promote_pde(pmap, pde, va, &lock);
4517 return (KERN_SUCCESS);
4521 * Tries to create a 2MB page mapping. Returns TRUE if successful and FALSE
4522 * otherwise. Fails if (1) a page table page cannot be allocated without
4523 * blocking, (2) a mapping already exists at the specified virtual address, or
4524 * (3) a pv entry cannot be allocated without reclaiming another pv entry.
4527 pmap_enter_pde(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4528 struct rwlock **lockp)
4530 pd_entry_t *pde, newpde;
4533 struct spglist free;
4535 PG_V = pmap_valid_bit(pmap);
4536 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4538 if ((mpde = pmap_allocpde(pmap, va, NULL)) == NULL) {
4539 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4540 " in pmap %p", va, pmap);
4543 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpde));
4544 pde = &pde[pmap_pde_index(va)];
4545 if ((*pde & PG_V) != 0) {
4546 KASSERT(mpde->wire_count > 1,
4547 ("pmap_enter_pde: mpde's wire count is too low"));
4549 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4550 " in pmap %p", va, pmap);
4553 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
4555 if ((m->oflags & VPO_UNMANAGED) == 0) {
4556 newpde |= PG_MANAGED;
4559 * Abort this mapping if its PV entry could not be created.
4561 if (!pmap_pv_insert_pde(pmap, va, VM_PAGE_TO_PHYS(m),
4564 if (pmap_unwire_ptp(pmap, va, mpde, &free)) {
4566 * Although "va" is not mapped, paging-
4567 * structure caches could nonetheless have
4568 * entries that refer to the freed page table
4569 * pages. Invalidate those entries.
4571 pmap_invalidate_page(pmap, va);
4572 pmap_free_zero_pages(&free);
4574 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4575 " in pmap %p", va, pmap);
4579 if ((prot & VM_PROT_EXECUTE) == 0)
4581 if (va < VM_MAXUSER_ADDRESS)
4585 * Increment counters.
4587 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
4590 * Map the superpage.
4592 pde_store(pde, newpde);
4594 atomic_add_long(&pmap_pde_mappings, 1);
4595 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
4596 " in pmap %p", va, pmap);
4601 * Maps a sequence of resident pages belonging to the same object.
4602 * The sequence begins with the given page m_start. This page is
4603 * mapped at the given virtual address start. Each subsequent page is
4604 * mapped at a virtual address that is offset from start by the same
4605 * amount as the page is offset from m_start within the object. The
4606 * last page in the sequence is the page with the largest offset from
4607 * m_start that can be mapped at a virtual address less than the given
4608 * virtual address end. Not every virtual page between start and end
4609 * is mapped; only those for which a resident page exists with the
4610 * corresponding offset from m_start are mapped.
4613 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
4614 vm_page_t m_start, vm_prot_t prot)
4616 struct rwlock *lock;
4619 vm_pindex_t diff, psize;
4621 VM_OBJECT_ASSERT_LOCKED(m_start->object);
4623 psize = atop(end - start);
4628 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
4629 va = start + ptoa(diff);
4630 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
4631 m->psind == 1 && pmap_ps_enabled(pmap) &&
4632 pmap_enter_pde(pmap, va, m, prot, &lock))
4633 m = &m[NBPDR / PAGE_SIZE - 1];
4635 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
4637 m = TAILQ_NEXT(m, listq);
4645 * this code makes some *MAJOR* assumptions:
4646 * 1. Current pmap & pmap exists.
4649 * 4. No page table pages.
4650 * but is *MUCH* faster than pmap_enter...
4654 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
4656 struct rwlock *lock;
4660 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
4667 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
4668 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
4670 struct spglist free;
4671 pt_entry_t *pte, PG_V;
4674 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
4675 (m->oflags & VPO_UNMANAGED) != 0,
4676 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
4677 PG_V = pmap_valid_bit(pmap);
4678 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4681 * In the case that a page table page is not
4682 * resident, we are creating it here.
4684 if (va < VM_MAXUSER_ADDRESS) {
4685 vm_pindex_t ptepindex;
4689 * Calculate pagetable page index
4691 ptepindex = pmap_pde_pindex(va);
4692 if (mpte && (mpte->pindex == ptepindex)) {
4696 * Get the page directory entry
4698 ptepa = pmap_pde(pmap, va);
4701 * If the page table page is mapped, we just increment
4702 * the hold count, and activate it. Otherwise, we
4703 * attempt to allocate a page table page. If this
4704 * attempt fails, we don't retry. Instead, we give up.
4706 if (ptepa && (*ptepa & PG_V) != 0) {
4709 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
4713 * Pass NULL instead of the PV list lock
4714 * pointer, because we don't intend to sleep.
4716 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
4721 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
4722 pte = &pte[pmap_pte_index(va)];
4736 * Enter on the PV list if part of our managed memory.
4738 if ((m->oflags & VPO_UNMANAGED) == 0 &&
4739 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
4742 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
4744 * Although "va" is not mapped, paging-
4745 * structure caches could nonetheless have
4746 * entries that refer to the freed page table
4747 * pages. Invalidate those entries.
4749 pmap_invalidate_page(pmap, va);
4750 pmap_free_zero_pages(&free);
4758 * Increment counters
4760 pmap_resident_count_inc(pmap, 1);
4762 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
4763 if ((prot & VM_PROT_EXECUTE) == 0)
4767 * Now validate mapping with RO protection
4769 if ((m->oflags & VPO_UNMANAGED) != 0)
4770 pte_store(pte, pa | PG_V | PG_U);
4772 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
4777 * Make a temporary mapping for a physical address. This is only intended
4778 * to be used for panic dumps.
4781 pmap_kenter_temporary(vm_paddr_t pa, int i)
4785 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
4786 pmap_kenter(va, pa);
4788 return ((void *)crashdumpmap);
4792 * This code maps large physical mmap regions into the
4793 * processor address space. Note that some shortcuts
4794 * are taken, but the code works.
4797 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
4798 vm_pindex_t pindex, vm_size_t size)
4801 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
4802 vm_paddr_t pa, ptepa;
4806 PG_A = pmap_accessed_bit(pmap);
4807 PG_M = pmap_modified_bit(pmap);
4808 PG_V = pmap_valid_bit(pmap);
4809 PG_RW = pmap_rw_bit(pmap);
4811 VM_OBJECT_ASSERT_WLOCKED(object);
4812 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
4813 ("pmap_object_init_pt: non-device object"));
4814 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
4815 if (!pmap_ps_enabled(pmap))
4817 if (!vm_object_populate(object, pindex, pindex + atop(size)))
4819 p = vm_page_lookup(object, pindex);
4820 KASSERT(p->valid == VM_PAGE_BITS_ALL,
4821 ("pmap_object_init_pt: invalid page %p", p));
4822 pat_mode = p->md.pat_mode;
4825 * Abort the mapping if the first page is not physically
4826 * aligned to a 2MB page boundary.
4828 ptepa = VM_PAGE_TO_PHYS(p);
4829 if (ptepa & (NBPDR - 1))
4833 * Skip the first page. Abort the mapping if the rest of
4834 * the pages are not physically contiguous or have differing
4835 * memory attributes.
4837 p = TAILQ_NEXT(p, listq);
4838 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
4840 KASSERT(p->valid == VM_PAGE_BITS_ALL,
4841 ("pmap_object_init_pt: invalid page %p", p));
4842 if (pa != VM_PAGE_TO_PHYS(p) ||
4843 pat_mode != p->md.pat_mode)
4845 p = TAILQ_NEXT(p, listq);
4849 * Map using 2MB pages. Since "ptepa" is 2M aligned and
4850 * "size" is a multiple of 2M, adding the PAT setting to "pa"
4851 * will not affect the termination of this loop.
4854 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
4855 pa < ptepa + size; pa += NBPDR) {
4856 pdpg = pmap_allocpde(pmap, addr, NULL);
4859 * The creation of mappings below is only an
4860 * optimization. If a page directory page
4861 * cannot be allocated without blocking,
4862 * continue on to the next mapping rather than
4868 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4869 pde = &pde[pmap_pde_index(addr)];
4870 if ((*pde & PG_V) == 0) {
4871 pde_store(pde, pa | PG_PS | PG_M | PG_A |
4872 PG_U | PG_RW | PG_V);
4873 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
4874 atomic_add_long(&pmap_pde_mappings, 1);
4876 /* Continue on if the PDE is already valid. */
4878 KASSERT(pdpg->wire_count > 0,
4879 ("pmap_object_init_pt: missing reference "
4880 "to page directory page, va: 0x%lx", addr));
4889 * Clear the wired attribute from the mappings for the specified range of
4890 * addresses in the given pmap. Every valid mapping within that range
4891 * must have the wired attribute set. In contrast, invalid mappings
4892 * cannot have the wired attribute set, so they are ignored.
4894 * The wired attribute of the page table entry is not a hardware
4895 * feature, so there is no need to invalidate any TLB entries.
4896 * Since pmap_demote_pde() for the wired entry must never fail,
4897 * pmap_delayed_invl_started()/finished() calls around the
4898 * function are not needed.
4901 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4903 vm_offset_t va_next;
4904 pml4_entry_t *pml4e;
4907 pt_entry_t *pte, PG_V;
4909 PG_V = pmap_valid_bit(pmap);
4911 for (; sva < eva; sva = va_next) {
4912 pml4e = pmap_pml4e(pmap, sva);
4913 if ((*pml4e & PG_V) == 0) {
4914 va_next = (sva + NBPML4) & ~PML4MASK;
4919 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4920 if ((*pdpe & PG_V) == 0) {
4921 va_next = (sva + NBPDP) & ~PDPMASK;
4926 va_next = (sva + NBPDR) & ~PDRMASK;
4929 pde = pmap_pdpe_to_pde(pdpe, sva);
4930 if ((*pde & PG_V) == 0)
4932 if ((*pde & PG_PS) != 0) {
4933 if ((*pde & PG_W) == 0)
4934 panic("pmap_unwire: pde %#jx is missing PG_W",
4938 * Are we unwiring the entire large page? If not,
4939 * demote the mapping and fall through.
4941 if (sva + NBPDR == va_next && eva >= va_next) {
4942 atomic_clear_long(pde, PG_W);
4943 pmap->pm_stats.wired_count -= NBPDR /
4946 } else if (!pmap_demote_pde(pmap, pde, sva))
4947 panic("pmap_unwire: demotion failed");
4951 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4953 if ((*pte & PG_V) == 0)
4955 if ((*pte & PG_W) == 0)
4956 panic("pmap_unwire: pte %#jx is missing PG_W",
4960 * PG_W must be cleared atomically. Although the pmap
4961 * lock synchronizes access to PG_W, another processor
4962 * could be setting PG_M and/or PG_A concurrently.
4964 atomic_clear_long(pte, PG_W);
4965 pmap->pm_stats.wired_count--;
4972 * Copy the range specified by src_addr/len
4973 * from the source map to the range dst_addr/len
4974 * in the destination map.
4976 * This routine is only advisory and need not do anything.
4980 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
4981 vm_offset_t src_addr)
4983 struct rwlock *lock;
4984 struct spglist free;
4986 vm_offset_t end_addr = src_addr + len;
4987 vm_offset_t va_next;
4988 pt_entry_t PG_A, PG_M, PG_V;
4990 if (dst_addr != src_addr)
4993 if (dst_pmap->pm_type != src_pmap->pm_type)
4997 * EPT page table entries that require emulation of A/D bits are
4998 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
4999 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5000 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5001 * implementations flag an EPT misconfiguration for exec-only
5002 * mappings we skip this function entirely for emulated pmaps.
5004 if (pmap_emulate_ad_bits(dst_pmap))
5008 if (dst_pmap < src_pmap) {
5009 PMAP_LOCK(dst_pmap);
5010 PMAP_LOCK(src_pmap);
5012 PMAP_LOCK(src_pmap);
5013 PMAP_LOCK(dst_pmap);
5016 PG_A = pmap_accessed_bit(dst_pmap);
5017 PG_M = pmap_modified_bit(dst_pmap);
5018 PG_V = pmap_valid_bit(dst_pmap);
5020 for (addr = src_addr; addr < end_addr; addr = va_next) {
5021 pt_entry_t *src_pte, *dst_pte;
5022 vm_page_t dstmpde, dstmpte, srcmpte;
5023 pml4_entry_t *pml4e;
5025 pd_entry_t srcptepaddr, *pde;
5027 KASSERT(addr < UPT_MIN_ADDRESS,
5028 ("pmap_copy: invalid to pmap_copy page tables"));
5030 pml4e = pmap_pml4e(src_pmap, addr);
5031 if ((*pml4e & PG_V) == 0) {
5032 va_next = (addr + NBPML4) & ~PML4MASK;
5038 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5039 if ((*pdpe & PG_V) == 0) {
5040 va_next = (addr + NBPDP) & ~PDPMASK;
5046 va_next = (addr + NBPDR) & ~PDRMASK;
5050 pde = pmap_pdpe_to_pde(pdpe, addr);
5052 if (srcptepaddr == 0)
5055 if (srcptepaddr & PG_PS) {
5056 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5058 dstmpde = pmap_allocpde(dst_pmap, addr, NULL);
5059 if (dstmpde == NULL)
5061 pde = (pd_entry_t *)
5062 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpde));
5063 pde = &pde[pmap_pde_index(addr)];
5064 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5065 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr &
5066 PG_PS_FRAME, &lock))) {
5067 *pde = srcptepaddr & ~PG_W;
5068 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5069 atomic_add_long(&pmap_pde_mappings, 1);
5071 dstmpde->wire_count--;
5075 srcptepaddr &= PG_FRAME;
5076 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5077 KASSERT(srcmpte->wire_count > 0,
5078 ("pmap_copy: source page table page is unused"));
5080 if (va_next > end_addr)
5083 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5084 src_pte = &src_pte[pmap_pte_index(addr)];
5086 while (addr < va_next) {
5090 * we only virtual copy managed pages
5092 if ((ptetemp & PG_MANAGED) != 0) {
5093 if (dstmpte != NULL &&
5094 dstmpte->pindex == pmap_pde_pindex(addr))
5095 dstmpte->wire_count++;
5096 else if ((dstmpte = pmap_allocpte(dst_pmap,
5097 addr, NULL)) == NULL)
5099 dst_pte = (pt_entry_t *)
5100 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5101 dst_pte = &dst_pte[pmap_pte_index(addr)];
5102 if (*dst_pte == 0 &&
5103 pmap_try_insert_pv_entry(dst_pmap, addr,
5104 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5107 * Clear the wired, modified, and
5108 * accessed (referenced) bits
5111 *dst_pte = ptetemp & ~(PG_W | PG_M |
5113 pmap_resident_count_inc(dst_pmap, 1);
5116 if (pmap_unwire_ptp(dst_pmap, addr,
5119 * Although "addr" is not
5120 * mapped, paging-structure
5121 * caches could nonetheless
5122 * have entries that refer to
5123 * the freed page table pages.
5124 * Invalidate those entries.
5126 pmap_invalidate_page(dst_pmap,
5128 pmap_free_zero_pages(&free);
5132 if (dstmpte->wire_count >= srcmpte->wire_count)
5142 PMAP_UNLOCK(src_pmap);
5143 PMAP_UNLOCK(dst_pmap);
5147 * Zero the specified hardware page.
5150 pmap_zero_page(vm_page_t m)
5152 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5154 pagezero((void *)va);
5158 * Zero an an area within a single hardware page. off and size must not
5159 * cover an area beyond a single hardware page.
5162 pmap_zero_page_area(vm_page_t m, int off, int size)
5164 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5166 if (off == 0 && size == PAGE_SIZE)
5167 pagezero((void *)va);
5169 bzero((char *)va + off, size);
5173 * Copy 1 specified hardware page to another.
5176 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5178 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5179 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5181 pagecopy((void *)src, (void *)dst);
5184 int unmapped_buf_allowed = 1;
5187 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5188 vm_offset_t b_offset, int xfersize)
5192 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5196 while (xfersize > 0) {
5197 a_pg_offset = a_offset & PAGE_MASK;
5198 pages[0] = ma[a_offset >> PAGE_SHIFT];
5199 b_pg_offset = b_offset & PAGE_MASK;
5200 pages[1] = mb[b_offset >> PAGE_SHIFT];
5201 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5202 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5203 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5204 a_cp = (char *)vaddr[0] + a_pg_offset;
5205 b_cp = (char *)vaddr[1] + b_pg_offset;
5206 bcopy(a_cp, b_cp, cnt);
5207 if (__predict_false(mapped))
5208 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5216 * Returns true if the pmap's pv is one of the first
5217 * 16 pvs linked to from this page. This count may
5218 * be changed upwards or downwards in the future; it
5219 * is only necessary that true be returned for a small
5220 * subset of pmaps for proper page aging.
5223 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5225 struct md_page *pvh;
5226 struct rwlock *lock;
5231 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5232 ("pmap_page_exists_quick: page %p is not managed", m));
5234 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5236 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5237 if (PV_PMAP(pv) == pmap) {
5245 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5246 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5247 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5248 if (PV_PMAP(pv) == pmap) {
5262 * pmap_page_wired_mappings:
5264 * Return the number of managed mappings to the given physical page
5268 pmap_page_wired_mappings(vm_page_t m)
5270 struct rwlock *lock;
5271 struct md_page *pvh;
5275 int count, md_gen, pvh_gen;
5277 if ((m->oflags & VPO_UNMANAGED) != 0)
5279 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5283 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5285 if (!PMAP_TRYLOCK(pmap)) {
5286 md_gen = m->md.pv_gen;
5290 if (md_gen != m->md.pv_gen) {
5295 pte = pmap_pte(pmap, pv->pv_va);
5296 if ((*pte & PG_W) != 0)
5300 if ((m->flags & PG_FICTITIOUS) == 0) {
5301 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5302 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5304 if (!PMAP_TRYLOCK(pmap)) {
5305 md_gen = m->md.pv_gen;
5306 pvh_gen = pvh->pv_gen;
5310 if (md_gen != m->md.pv_gen ||
5311 pvh_gen != pvh->pv_gen) {
5316 pte = pmap_pde(pmap, pv->pv_va);
5317 if ((*pte & PG_W) != 0)
5327 * Returns TRUE if the given page is mapped individually or as part of
5328 * a 2mpage. Otherwise, returns FALSE.
5331 pmap_page_is_mapped(vm_page_t m)
5333 struct rwlock *lock;
5336 if ((m->oflags & VPO_UNMANAGED) != 0)
5338 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5340 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5341 ((m->flags & PG_FICTITIOUS) == 0 &&
5342 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5348 * Destroy all managed, non-wired mappings in the given user-space
5349 * pmap. This pmap cannot be active on any processor besides the
5352 * This function cannot be applied to the kernel pmap. Moreover, it
5353 * is not intended for general use. It is only to be used during
5354 * process termination. Consequently, it can be implemented in ways
5355 * that make it faster than pmap_remove(). First, it can more quickly
5356 * destroy mappings by iterating over the pmap's collection of PV
5357 * entries, rather than searching the page table. Second, it doesn't
5358 * have to test and clear the page table entries atomically, because
5359 * no processor is currently accessing the user address space. In
5360 * particular, a page table entry's dirty bit won't change state once
5361 * this function starts.
5364 pmap_remove_pages(pmap_t pmap)
5367 pt_entry_t *pte, tpte;
5368 pt_entry_t PG_M, PG_RW, PG_V;
5369 struct spglist free;
5370 vm_page_t m, mpte, mt;
5372 struct md_page *pvh;
5373 struct pv_chunk *pc, *npc;
5374 struct rwlock *lock;
5376 uint64_t inuse, bitmask;
5377 int allfree, field, freed, idx;
5378 boolean_t superpage;
5382 * Assert that the given pmap is only active on the current
5383 * CPU. Unfortunately, we cannot block another CPU from
5384 * activating the pmap while this function is executing.
5386 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5389 cpuset_t other_cpus;
5391 other_cpus = all_cpus;
5393 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5394 CPU_AND(&other_cpus, &pmap->pm_active);
5396 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5401 PG_M = pmap_modified_bit(pmap);
5402 PG_V = pmap_valid_bit(pmap);
5403 PG_RW = pmap_rw_bit(pmap);
5407 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5410 for (field = 0; field < _NPCM; field++) {
5411 inuse = ~pc->pc_map[field] & pc_freemask[field];
5412 while (inuse != 0) {
5414 bitmask = 1UL << bit;
5415 idx = field * 64 + bit;
5416 pv = &pc->pc_pventry[idx];
5419 pte = pmap_pdpe(pmap, pv->pv_va);
5421 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5423 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5426 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5428 pte = &pte[pmap_pte_index(pv->pv_va)];
5432 * Keep track whether 'tpte' is a
5433 * superpage explicitly instead of
5434 * relying on PG_PS being set.
5436 * This is because PG_PS is numerically
5437 * identical to PG_PTE_PAT and thus a
5438 * regular page could be mistaken for
5444 if ((tpte & PG_V) == 0) {
5445 panic("bad pte va %lx pte %lx",
5450 * We cannot remove wired pages from a process' mapping at this time
5458 pa = tpte & PG_PS_FRAME;
5460 pa = tpte & PG_FRAME;
5462 m = PHYS_TO_VM_PAGE(pa);
5463 KASSERT(m->phys_addr == pa,
5464 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5465 m, (uintmax_t)m->phys_addr,
5468 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5469 m < &vm_page_array[vm_page_array_size],
5470 ("pmap_remove_pages: bad tpte %#jx",
5476 * Update the vm_page_t clean/reference bits.
5478 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5480 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5486 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5489 pc->pc_map[field] |= bitmask;
5491 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
5492 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
5493 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5495 if (TAILQ_EMPTY(&pvh->pv_list)) {
5496 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5497 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
5498 TAILQ_EMPTY(&mt->md.pv_list))
5499 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5501 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
5503 pmap_resident_count_dec(pmap, 1);
5504 KASSERT(mpte->wire_count == NPTEPG,
5505 ("pmap_remove_pages: pte page wire count error"));
5506 mpte->wire_count = 0;
5507 pmap_add_delayed_free_list(mpte, &free, FALSE);
5508 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
5511 pmap_resident_count_dec(pmap, 1);
5512 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5514 if ((m->aflags & PGA_WRITEABLE) != 0 &&
5515 TAILQ_EMPTY(&m->md.pv_list) &&
5516 (m->flags & PG_FICTITIOUS) == 0) {
5517 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5518 if (TAILQ_EMPTY(&pvh->pv_list))
5519 vm_page_aflag_clear(m, PGA_WRITEABLE);
5522 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
5526 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5527 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5528 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5530 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5536 pmap_invalidate_all(pmap);
5538 pmap_free_zero_pages(&free);
5542 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
5544 struct rwlock *lock;
5546 struct md_page *pvh;
5547 pt_entry_t *pte, mask;
5548 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5550 int md_gen, pvh_gen;
5554 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5557 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5559 if (!PMAP_TRYLOCK(pmap)) {
5560 md_gen = m->md.pv_gen;
5564 if (md_gen != m->md.pv_gen) {
5569 pte = pmap_pte(pmap, pv->pv_va);
5572 PG_M = pmap_modified_bit(pmap);
5573 PG_RW = pmap_rw_bit(pmap);
5574 mask |= PG_RW | PG_M;
5577 PG_A = pmap_accessed_bit(pmap);
5578 PG_V = pmap_valid_bit(pmap);
5579 mask |= PG_V | PG_A;
5581 rv = (*pte & mask) == mask;
5586 if ((m->flags & PG_FICTITIOUS) == 0) {
5587 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5588 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5590 if (!PMAP_TRYLOCK(pmap)) {
5591 md_gen = m->md.pv_gen;
5592 pvh_gen = pvh->pv_gen;
5596 if (md_gen != m->md.pv_gen ||
5597 pvh_gen != pvh->pv_gen) {
5602 pte = pmap_pde(pmap, pv->pv_va);
5605 PG_M = pmap_modified_bit(pmap);
5606 PG_RW = pmap_rw_bit(pmap);
5607 mask |= PG_RW | PG_M;
5610 PG_A = pmap_accessed_bit(pmap);
5611 PG_V = pmap_valid_bit(pmap);
5612 mask |= PG_V | PG_A;
5614 rv = (*pte & mask) == mask;
5628 * Return whether or not the specified physical page was modified
5629 * in any physical maps.
5632 pmap_is_modified(vm_page_t m)
5635 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5636 ("pmap_is_modified: page %p is not managed", m));
5639 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5640 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
5641 * is clear, no PTEs can have PG_M set.
5643 VM_OBJECT_ASSERT_WLOCKED(m->object);
5644 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
5646 return (pmap_page_test_mappings(m, FALSE, TRUE));
5650 * pmap_is_prefaultable:
5652 * Return whether or not the specified virtual address is eligible
5656 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
5659 pt_entry_t *pte, PG_V;
5662 PG_V = pmap_valid_bit(pmap);
5665 pde = pmap_pde(pmap, addr);
5666 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
5667 pte = pmap_pde_to_pte(pde, addr);
5668 rv = (*pte & PG_V) == 0;
5675 * pmap_is_referenced:
5677 * Return whether or not the specified physical page was referenced
5678 * in any physical maps.
5681 pmap_is_referenced(vm_page_t m)
5684 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5685 ("pmap_is_referenced: page %p is not managed", m));
5686 return (pmap_page_test_mappings(m, TRUE, FALSE));
5690 * Clear the write and modified bits in each of the given page's mappings.
5693 pmap_remove_write(vm_page_t m)
5695 struct md_page *pvh;
5697 struct rwlock *lock;
5698 pv_entry_t next_pv, pv;
5700 pt_entry_t oldpte, *pte, PG_M, PG_RW;
5702 int pvh_gen, md_gen;
5704 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5705 ("pmap_remove_write: page %p is not managed", m));
5708 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5709 * set by another thread while the object is locked. Thus,
5710 * if PGA_WRITEABLE is clear, no page table entries need updating.
5712 VM_OBJECT_ASSERT_WLOCKED(m->object);
5713 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
5715 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5716 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
5717 pa_to_pvh(VM_PAGE_TO_PHYS(m));
5720 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
5722 if (!PMAP_TRYLOCK(pmap)) {
5723 pvh_gen = pvh->pv_gen;
5727 if (pvh_gen != pvh->pv_gen) {
5733 PG_RW = pmap_rw_bit(pmap);
5735 pde = pmap_pde(pmap, va);
5736 if ((*pde & PG_RW) != 0)
5737 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
5738 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
5739 ("inconsistent pv lock %p %p for page %p",
5740 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
5743 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5745 if (!PMAP_TRYLOCK(pmap)) {
5746 pvh_gen = pvh->pv_gen;
5747 md_gen = m->md.pv_gen;
5751 if (pvh_gen != pvh->pv_gen ||
5752 md_gen != m->md.pv_gen) {
5758 PG_M = pmap_modified_bit(pmap);
5759 PG_RW = pmap_rw_bit(pmap);
5760 pde = pmap_pde(pmap, pv->pv_va);
5761 KASSERT((*pde & PG_PS) == 0,
5762 ("pmap_remove_write: found a 2mpage in page %p's pv list",
5764 pte = pmap_pde_to_pte(pde, pv->pv_va);
5767 if (oldpte & PG_RW) {
5768 if (!atomic_cmpset_long(pte, oldpte, oldpte &
5771 if ((oldpte & PG_M) != 0)
5773 pmap_invalidate_page(pmap, pv->pv_va);
5778 vm_page_aflag_clear(m, PGA_WRITEABLE);
5779 pmap_delayed_invl_wait(m);
5782 static __inline boolean_t
5783 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
5786 if (!pmap_emulate_ad_bits(pmap))
5789 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
5792 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
5793 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
5794 * if the EPT_PG_WRITE bit is set.
5796 if ((pte & EPT_PG_WRITE) != 0)
5800 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
5802 if ((pte & EPT_PG_EXECUTE) == 0 ||
5803 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
5810 * pmap_ts_referenced:
5812 * Return a count of reference bits for a page, clearing those bits.
5813 * It is not necessary for every reference bit to be cleared, but it
5814 * is necessary that 0 only be returned when there are truly no
5815 * reference bits set.
5817 * As an optimization, update the page's dirty field if a modified bit is
5818 * found while counting reference bits. This opportunistic update can be
5819 * performed at low cost and can eliminate the need for some future calls
5820 * to pmap_is_modified(). However, since this function stops after
5821 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
5822 * dirty pages. Those dirty pages will only be detected by a future call
5823 * to pmap_is_modified().
5825 * A DI block is not needed within this function, because
5826 * invalidations are performed before the PV list lock is
5830 pmap_ts_referenced(vm_page_t m)
5832 struct md_page *pvh;
5835 struct rwlock *lock;
5836 pd_entry_t oldpde, *pde;
5837 pt_entry_t *pte, PG_A, PG_M, PG_RW;
5840 int cleared, md_gen, not_cleared, pvh_gen;
5841 struct spglist free;
5844 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5845 ("pmap_ts_referenced: page %p is not managed", m));
5848 pa = VM_PAGE_TO_PHYS(m);
5849 lock = PHYS_TO_PV_LIST_LOCK(pa);
5850 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
5854 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
5855 goto small_mappings;
5861 if (!PMAP_TRYLOCK(pmap)) {
5862 pvh_gen = pvh->pv_gen;
5866 if (pvh_gen != pvh->pv_gen) {
5871 PG_A = pmap_accessed_bit(pmap);
5872 PG_M = pmap_modified_bit(pmap);
5873 PG_RW = pmap_rw_bit(pmap);
5875 pde = pmap_pde(pmap, pv->pv_va);
5877 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5879 * Although "oldpde" is mapping a 2MB page, because
5880 * this function is called at a 4KB page granularity,
5881 * we only update the 4KB page under test.
5885 if ((oldpde & PG_A) != 0) {
5887 * Since this reference bit is shared by 512 4KB
5888 * pages, it should not be cleared every time it is
5889 * tested. Apply a simple "hash" function on the
5890 * physical page number, the virtual superpage number,
5891 * and the pmap address to select one 4KB page out of
5892 * the 512 on which testing the reference bit will
5893 * result in clearing that reference bit. This
5894 * function is designed to avoid the selection of the
5895 * same 4KB page for every 2MB page mapping.
5897 * On demotion, a mapping that hasn't been referenced
5898 * is simply destroyed. To avoid the possibility of a
5899 * subsequent page fault on a demoted wired mapping,
5900 * always leave its reference bit set. Moreover,
5901 * since the superpage is wired, the current state of
5902 * its reference bit won't affect page replacement.
5904 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
5905 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
5906 (oldpde & PG_W) == 0) {
5907 if (safe_to_clear_referenced(pmap, oldpde)) {
5908 atomic_clear_long(pde, PG_A);
5909 pmap_invalidate_page(pmap, pv->pv_va);
5911 } else if (pmap_demote_pde_locked(pmap, pde,
5912 pv->pv_va, &lock)) {
5914 * Remove the mapping to a single page
5915 * so that a subsequent access may
5916 * repromote. Since the underlying
5917 * page table page is fully populated,
5918 * this removal never frees a page
5922 va += VM_PAGE_TO_PHYS(m) - (oldpde &
5924 pte = pmap_pde_to_pte(pde, va);
5925 pmap_remove_pte(pmap, pte, va, *pde,
5927 pmap_invalidate_page(pmap, va);
5933 * The superpage mapping was removed
5934 * entirely and therefore 'pv' is no
5942 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
5943 ("inconsistent pv lock %p %p for page %p",
5944 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
5949 /* Rotate the PV list if it has more than one entry. */
5950 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
5951 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5952 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5955 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
5957 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
5959 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
5966 if (!PMAP_TRYLOCK(pmap)) {
5967 pvh_gen = pvh->pv_gen;
5968 md_gen = m->md.pv_gen;
5972 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
5977 PG_A = pmap_accessed_bit(pmap);
5978 PG_M = pmap_modified_bit(pmap);
5979 PG_RW = pmap_rw_bit(pmap);
5980 pde = pmap_pde(pmap, pv->pv_va);
5981 KASSERT((*pde & PG_PS) == 0,
5982 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
5984 pte = pmap_pde_to_pte(pde, pv->pv_va);
5985 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5987 if ((*pte & PG_A) != 0) {
5988 if (safe_to_clear_referenced(pmap, *pte)) {
5989 atomic_clear_long(pte, PG_A);
5990 pmap_invalidate_page(pmap, pv->pv_va);
5992 } else if ((*pte & PG_W) == 0) {
5994 * Wired pages cannot be paged out so
5995 * doing accessed bit emulation for
5996 * them is wasted effort. We do the
5997 * hard work for unwired pages only.
5999 pmap_remove_pte(pmap, pte, pv->pv_va,
6000 *pde, &free, &lock);
6001 pmap_invalidate_page(pmap, pv->pv_va);
6006 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6007 ("inconsistent pv lock %p %p for page %p",
6008 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6013 /* Rotate the PV list if it has more than one entry. */
6014 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6015 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6016 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6019 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6020 not_cleared < PMAP_TS_REFERENCED_MAX);
6023 pmap_free_zero_pages(&free);
6024 return (cleared + not_cleared);
6028 * Apply the given advice to the specified range of addresses within the
6029 * given pmap. Depending on the advice, clear the referenced and/or
6030 * modified flags in each mapping and set the mapped page's dirty field.
6033 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6035 struct rwlock *lock;
6036 pml4_entry_t *pml4e;
6038 pd_entry_t oldpde, *pde;
6039 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6040 vm_offset_t va, va_next;
6042 boolean_t anychanged;
6044 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6048 * A/D bit emulation requires an alternate code path when clearing
6049 * the modified and accessed bits below. Since this function is
6050 * advisory in nature we skip it entirely for pmaps that require
6051 * A/D bit emulation.
6053 if (pmap_emulate_ad_bits(pmap))
6056 PG_A = pmap_accessed_bit(pmap);
6057 PG_G = pmap_global_bit(pmap);
6058 PG_M = pmap_modified_bit(pmap);
6059 PG_V = pmap_valid_bit(pmap);
6060 PG_RW = pmap_rw_bit(pmap);
6062 pmap_delayed_invl_started();
6064 for (; sva < eva; sva = va_next) {
6065 pml4e = pmap_pml4e(pmap, sva);
6066 if ((*pml4e & PG_V) == 0) {
6067 va_next = (sva + NBPML4) & ~PML4MASK;
6072 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6073 if ((*pdpe & PG_V) == 0) {
6074 va_next = (sva + NBPDP) & ~PDPMASK;
6079 va_next = (sva + NBPDR) & ~PDRMASK;
6082 pde = pmap_pdpe_to_pde(pdpe, sva);
6084 if ((oldpde & PG_V) == 0)
6086 else if ((oldpde & PG_PS) != 0) {
6087 if ((oldpde & PG_MANAGED) == 0)
6090 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6095 * The large page mapping was destroyed.
6101 * Unless the page mappings are wired, remove the
6102 * mapping to a single page so that a subsequent
6103 * access may repromote. Since the underlying page
6104 * table page is fully populated, this removal never
6105 * frees a page table page.
6107 if ((oldpde & PG_W) == 0) {
6108 pte = pmap_pde_to_pte(pde, sva);
6109 KASSERT((*pte & PG_V) != 0,
6110 ("pmap_advise: invalid PTE"));
6111 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6121 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6123 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6125 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6126 if (advice == MADV_DONTNEED) {
6128 * Future calls to pmap_is_modified()
6129 * can be avoided by making the page
6132 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6135 atomic_clear_long(pte, PG_M | PG_A);
6136 } else if ((*pte & PG_A) != 0)
6137 atomic_clear_long(pte, PG_A);
6141 if ((*pte & PG_G) != 0) {
6148 if (va != va_next) {
6149 pmap_invalidate_range(pmap, va, sva);
6154 pmap_invalidate_range(pmap, va, sva);
6157 pmap_invalidate_all(pmap);
6159 pmap_delayed_invl_finished();
6163 * Clear the modify bits on the specified physical page.
6166 pmap_clear_modify(vm_page_t m)
6168 struct md_page *pvh;
6170 pv_entry_t next_pv, pv;
6171 pd_entry_t oldpde, *pde;
6172 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6173 struct rwlock *lock;
6175 int md_gen, pvh_gen;
6177 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6178 ("pmap_clear_modify: page %p is not managed", m));
6179 VM_OBJECT_ASSERT_WLOCKED(m->object);
6180 KASSERT(!vm_page_xbusied(m),
6181 ("pmap_clear_modify: page %p is exclusive busied", m));
6184 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6185 * If the object containing the page is locked and the page is not
6186 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6188 if ((m->aflags & PGA_WRITEABLE) == 0)
6190 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6191 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6192 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6195 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6197 if (!PMAP_TRYLOCK(pmap)) {
6198 pvh_gen = pvh->pv_gen;
6202 if (pvh_gen != pvh->pv_gen) {
6207 PG_M = pmap_modified_bit(pmap);
6208 PG_V = pmap_valid_bit(pmap);
6209 PG_RW = pmap_rw_bit(pmap);
6211 pde = pmap_pde(pmap, va);
6213 if ((oldpde & PG_RW) != 0) {
6214 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6215 if ((oldpde & PG_W) == 0) {
6217 * Write protect the mapping to a
6218 * single page so that a subsequent
6219 * write access may repromote.
6221 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6223 pte = pmap_pde_to_pte(pde, va);
6225 if ((oldpte & PG_V) != 0) {
6226 while (!atomic_cmpset_long(pte,
6228 oldpte & ~(PG_M | PG_RW)))
6231 pmap_invalidate_page(pmap, va);
6238 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6240 if (!PMAP_TRYLOCK(pmap)) {
6241 md_gen = m->md.pv_gen;
6242 pvh_gen = pvh->pv_gen;
6246 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6251 PG_M = pmap_modified_bit(pmap);
6252 PG_RW = pmap_rw_bit(pmap);
6253 pde = pmap_pde(pmap, pv->pv_va);
6254 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6255 " a 2mpage in page %p's pv list", m));
6256 pte = pmap_pde_to_pte(pde, pv->pv_va);
6257 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6258 atomic_clear_long(pte, PG_M);
6259 pmap_invalidate_page(pmap, pv->pv_va);
6267 * Miscellaneous support routines follow
6270 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6271 static __inline void
6272 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6277 * The cache mode bits are all in the low 32-bits of the
6278 * PTE, so we can just spin on updating the low 32-bits.
6281 opte = *(u_int *)pte;
6282 npte = opte & ~mask;
6284 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6287 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6288 static __inline void
6289 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6294 * The cache mode bits are all in the low 32-bits of the
6295 * PDE, so we can just spin on updating the low 32-bits.
6298 opde = *(u_int *)pde;
6299 npde = opde & ~mask;
6301 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6305 * Map a set of physical memory pages into the kernel virtual
6306 * address space. Return a pointer to where it is mapped. This
6307 * routine is intended to be used for mapping device memory,
6311 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6313 struct pmap_preinit_mapping *ppim;
6314 vm_offset_t va, offset;
6318 offset = pa & PAGE_MASK;
6319 size = round_page(offset + size);
6320 pa = trunc_page(pa);
6322 if (!pmap_initialized) {
6324 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6325 ppim = pmap_preinit_mapping + i;
6326 if (ppim->va == 0) {
6330 ppim->va = virtual_avail;
6331 virtual_avail += size;
6337 panic("%s: too many preinit mappings", __func__);
6340 * If we have a preinit mapping, re-use it.
6342 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6343 ppim = pmap_preinit_mapping + i;
6344 if (ppim->pa == pa && ppim->sz == size &&
6346 return ((void *)(ppim->va + offset));
6349 * If the specified range of physical addresses fits within
6350 * the direct map window, use the direct map.
6352 if (pa < dmaplimit && pa + size < dmaplimit) {
6353 va = PHYS_TO_DMAP(pa);
6354 if (!pmap_change_attr(va, size, mode))
6355 return ((void *)(va + offset));
6357 va = kva_alloc(size);
6359 panic("%s: Couldn't allocate KVA", __func__);
6361 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6362 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6363 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6364 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6365 return ((void *)(va + offset));
6369 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6372 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6376 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6379 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6383 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6385 struct pmap_preinit_mapping *ppim;
6389 /* If we gave a direct map region in pmap_mapdev, do nothing */
6390 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6392 offset = va & PAGE_MASK;
6393 size = round_page(offset + size);
6394 va = trunc_page(va);
6395 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6396 ppim = pmap_preinit_mapping + i;
6397 if (ppim->va == va && ppim->sz == size) {
6398 if (pmap_initialized)
6404 if (va + size == virtual_avail)
6409 if (pmap_initialized)
6414 * Tries to demote a 1GB page mapping.
6417 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6419 pdp_entry_t newpdpe, oldpdpe;
6420 pd_entry_t *firstpde, newpde, *pde;
6421 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6425 PG_A = pmap_accessed_bit(pmap);
6426 PG_M = pmap_modified_bit(pmap);
6427 PG_V = pmap_valid_bit(pmap);
6428 PG_RW = pmap_rw_bit(pmap);
6430 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6432 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6433 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6434 if ((mpde = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6435 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6436 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6437 " in pmap %p", va, pmap);
6440 mpdepa = VM_PAGE_TO_PHYS(mpde);
6441 firstpde = (pd_entry_t *)PHYS_TO_DMAP(mpdepa);
6442 newpdpe = mpdepa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6443 KASSERT((oldpdpe & PG_A) != 0,
6444 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6445 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6446 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
6450 * Initialize the page directory page.
6452 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
6458 * Demote the mapping.
6463 * Invalidate a stale recursive mapping of the page directory page.
6465 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
6467 pmap_pdpe_demotions++;
6468 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
6469 " in pmap %p", va, pmap);
6474 * Sets the memory attribute for the specified page.
6477 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6480 m->md.pat_mode = ma;
6483 * If "m" is a normal page, update its direct mapping. This update
6484 * can be relied upon to perform any cache operations that are
6485 * required for data coherence.
6487 if ((m->flags & PG_FICTITIOUS) == 0 &&
6488 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6490 panic("memory attribute change on the direct map failed");
6494 * Changes the specified virtual address range's memory type to that given by
6495 * the parameter "mode". The specified virtual address range must be
6496 * completely contained within either the direct map or the kernel map. If
6497 * the virtual address range is contained within the kernel map, then the
6498 * memory type for each of the corresponding ranges of the direct map is also
6499 * changed. (The corresponding ranges of the direct map are those ranges that
6500 * map the same physical pages as the specified virtual address range.) These
6501 * changes to the direct map are necessary because Intel describes the
6502 * behavior of their processors as "undefined" if two or more mappings to the
6503 * same physical page have different memory types.
6505 * Returns zero if the change completed successfully, and either EINVAL or
6506 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6507 * of the virtual address range was not mapped, and ENOMEM is returned if
6508 * there was insufficient memory available to complete the change. In the
6509 * latter case, the memory type may have been changed on some part of the
6510 * virtual address range or the direct map.
6513 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6517 PMAP_LOCK(kernel_pmap);
6518 error = pmap_change_attr_locked(va, size, mode);
6519 PMAP_UNLOCK(kernel_pmap);
6524 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
6526 vm_offset_t base, offset, tmpva;
6527 vm_paddr_t pa_start, pa_end, pa_end1;
6531 int cache_bits_pte, cache_bits_pde, error;
6534 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6535 base = trunc_page(va);
6536 offset = va & PAGE_MASK;
6537 size = round_page(offset + size);
6540 * Only supported on kernel virtual addresses, including the direct
6541 * map but excluding the recursive map.
6543 if (base < DMAP_MIN_ADDRESS)
6546 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
6547 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
6551 * Pages that aren't mapped aren't supported. Also break down 2MB pages
6552 * into 4KB pages if required.
6554 for (tmpva = base; tmpva < base + size; ) {
6555 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6556 if (pdpe == NULL || *pdpe == 0)
6558 if (*pdpe & PG_PS) {
6560 * If the current 1GB page already has the required
6561 * memory type, then we need not demote this page. Just
6562 * increment tmpva to the next 1GB page frame.
6564 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
6565 tmpva = trunc_1gpage(tmpva) + NBPDP;
6570 * If the current offset aligns with a 1GB page frame
6571 * and there is at least 1GB left within the range, then
6572 * we need not break down this page into 2MB pages.
6574 if ((tmpva & PDPMASK) == 0 &&
6575 tmpva + PDPMASK < base + size) {
6579 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
6582 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6587 * If the current 2MB page already has the required
6588 * memory type, then we need not demote this page. Just
6589 * increment tmpva to the next 2MB page frame.
6591 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
6592 tmpva = trunc_2mpage(tmpva) + NBPDR;
6597 * If the current offset aligns with a 2MB page frame
6598 * and there is at least 2MB left within the range, then
6599 * we need not break down this page into 4KB pages.
6601 if ((tmpva & PDRMASK) == 0 &&
6602 tmpva + PDRMASK < base + size) {
6606 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
6609 pte = pmap_pde_to_pte(pde, tmpva);
6617 * Ok, all the pages exist, so run through them updating their
6618 * cache mode if required.
6620 pa_start = pa_end = 0;
6621 for (tmpva = base; tmpva < base + size; ) {
6622 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6623 if (*pdpe & PG_PS) {
6624 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
6625 pmap_pde_attr(pdpe, cache_bits_pde,
6629 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6630 (*pdpe & PG_PS_FRAME) < dmaplimit) {
6631 if (pa_start == pa_end) {
6632 /* Start physical address run. */
6633 pa_start = *pdpe & PG_PS_FRAME;
6634 pa_end = pa_start + NBPDP;
6635 } else if (pa_end == (*pdpe & PG_PS_FRAME))
6638 /* Run ended, update direct map. */
6639 error = pmap_change_attr_locked(
6640 PHYS_TO_DMAP(pa_start),
6641 pa_end - pa_start, mode);
6644 /* Start physical address run. */
6645 pa_start = *pdpe & PG_PS_FRAME;
6646 pa_end = pa_start + NBPDP;
6649 tmpva = trunc_1gpage(tmpva) + NBPDP;
6652 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6654 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
6655 pmap_pde_attr(pde, cache_bits_pde,
6659 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6660 (*pde & PG_PS_FRAME) < dmaplimit) {
6661 if (pa_start == pa_end) {
6662 /* Start physical address run. */
6663 pa_start = *pde & PG_PS_FRAME;
6664 pa_end = pa_start + NBPDR;
6665 } else if (pa_end == (*pde & PG_PS_FRAME))
6668 /* Run ended, update direct map. */
6669 error = pmap_change_attr_locked(
6670 PHYS_TO_DMAP(pa_start),
6671 pa_end - pa_start, mode);
6674 /* Start physical address run. */
6675 pa_start = *pde & PG_PS_FRAME;
6676 pa_end = pa_start + NBPDR;
6679 tmpva = trunc_2mpage(tmpva) + NBPDR;
6681 pte = pmap_pde_to_pte(pde, tmpva);
6682 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
6683 pmap_pte_attr(pte, cache_bits_pte,
6687 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6688 (*pte & PG_PS_FRAME) < dmaplimit) {
6689 if (pa_start == pa_end) {
6690 /* Start physical address run. */
6691 pa_start = *pte & PG_FRAME;
6692 pa_end = pa_start + PAGE_SIZE;
6693 } else if (pa_end == (*pte & PG_FRAME))
6694 pa_end += PAGE_SIZE;
6696 /* Run ended, update direct map. */
6697 error = pmap_change_attr_locked(
6698 PHYS_TO_DMAP(pa_start),
6699 pa_end - pa_start, mode);
6702 /* Start physical address run. */
6703 pa_start = *pte & PG_FRAME;
6704 pa_end = pa_start + PAGE_SIZE;
6710 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
6711 pa_end1 = MIN(pa_end, dmaplimit);
6712 if (pa_start != pa_end1)
6713 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
6714 pa_end1 - pa_start, mode);
6718 * Flush CPU caches if required to make sure any data isn't cached that
6719 * shouldn't be, etc.
6722 pmap_invalidate_range(kernel_pmap, base, tmpva);
6723 pmap_invalidate_cache_range(base, tmpva, FALSE);
6729 * Demotes any mapping within the direct map region that covers more than the
6730 * specified range of physical addresses. This range's size must be a power
6731 * of two and its starting address must be a multiple of its size. Since the
6732 * demotion does not change any attributes of the mapping, a TLB invalidation
6733 * is not mandatory. The caller may, however, request a TLB invalidation.
6736 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
6745 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
6746 KASSERT((base & (len - 1)) == 0,
6747 ("pmap_demote_DMAP: base is not a multiple of len"));
6748 if (len < NBPDP && base < dmaplimit) {
6749 va = PHYS_TO_DMAP(base);
6751 PMAP_LOCK(kernel_pmap);
6752 pdpe = pmap_pdpe(kernel_pmap, va);
6753 if ((*pdpe & X86_PG_V) == 0)
6754 panic("pmap_demote_DMAP: invalid PDPE");
6755 if ((*pdpe & PG_PS) != 0) {
6756 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
6757 panic("pmap_demote_DMAP: PDPE failed");
6761 pde = pmap_pdpe_to_pde(pdpe, va);
6762 if ((*pde & X86_PG_V) == 0)
6763 panic("pmap_demote_DMAP: invalid PDE");
6764 if ((*pde & PG_PS) != 0) {
6765 if (!pmap_demote_pde(kernel_pmap, pde, va))
6766 panic("pmap_demote_DMAP: PDE failed");
6770 if (changed && invalidate)
6771 pmap_invalidate_page(kernel_pmap, va);
6772 PMAP_UNLOCK(kernel_pmap);
6777 * perform the pmap work for mincore
6780 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
6783 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
6787 PG_A = pmap_accessed_bit(pmap);
6788 PG_M = pmap_modified_bit(pmap);
6789 PG_V = pmap_valid_bit(pmap);
6790 PG_RW = pmap_rw_bit(pmap);
6794 pdep = pmap_pde(pmap, addr);
6795 if (pdep != NULL && (*pdep & PG_V)) {
6796 if (*pdep & PG_PS) {
6798 /* Compute the physical address of the 4KB page. */
6799 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
6801 val = MINCORE_SUPER;
6803 pte = *pmap_pde_to_pte(pdep, addr);
6804 pa = pte & PG_FRAME;
6812 if ((pte & PG_V) != 0) {
6813 val |= MINCORE_INCORE;
6814 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6815 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
6816 if ((pte & PG_A) != 0)
6817 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
6819 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
6820 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
6821 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
6822 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
6823 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
6826 PA_UNLOCK_COND(*locked_pa);
6832 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
6834 uint32_t gen, new_gen, pcid_next;
6836 CRITICAL_ASSERT(curthread);
6837 gen = PCPU_GET(pcid_gen);
6838 if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN ||
6839 pmap->pm_pcids[cpuid].pm_gen == gen)
6840 return (CR3_PCID_SAVE);
6841 pcid_next = PCPU_GET(pcid_next);
6842 KASSERT(pcid_next <= PMAP_PCID_OVERMAX, ("cpu %d pcid_next %#x",
6844 if (pcid_next == PMAP_PCID_OVERMAX) {
6848 PCPU_SET(pcid_gen, new_gen);
6849 pcid_next = PMAP_PCID_KERN + 1;
6853 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
6854 pmap->pm_pcids[cpuid].pm_gen = new_gen;
6855 PCPU_SET(pcid_next, pcid_next + 1);
6860 pmap_activate_sw(struct thread *td)
6862 pmap_t oldpmap, pmap;
6863 uint64_t cached, cr3;
6867 oldpmap = PCPU_GET(curpmap);
6868 pmap = vmspace_pmap(td->td_proc->p_vmspace);
6869 if (oldpmap == pmap)
6871 cpuid = PCPU_GET(cpuid);
6873 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
6875 CPU_SET(cpuid, &pmap->pm_active);
6878 if (pmap_pcid_enabled) {
6879 cached = pmap_pcid_alloc(pmap, cpuid);
6880 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
6881 pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
6882 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
6883 pmap->pm_pcids[cpuid].pm_pcid));
6884 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
6885 pmap == kernel_pmap,
6886 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
6887 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
6890 * If the INVPCID instruction is not available,
6891 * invltlb_pcid_handler() is used for handle
6892 * invalidate_all IPI, which checks for curpmap ==
6893 * smp_tlb_pmap. Below operations sequence has a
6894 * window where %CR3 is loaded with the new pmap's
6895 * PML4 address, but curpmap value is not yet updated.
6896 * This causes invltlb IPI handler, called between the
6897 * updates, to execute as NOP, which leaves stale TLB
6900 * Note that the most typical use of
6901 * pmap_activate_sw(), from the context switch, is
6902 * immune to this race, because interrupts are
6903 * disabled (while the thread lock is owned), and IPI
6904 * happends after curpmap is updated. Protect other
6905 * callers in a similar way, by disabling interrupts
6906 * around the %cr3 register reload and curpmap
6910 rflags = intr_disable();
6912 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
6913 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
6916 PCPU_INC(pm_save_cnt);
6918 PCPU_SET(curpmap, pmap);
6920 intr_restore(rflags);
6921 } else if (cr3 != pmap->pm_cr3) {
6922 load_cr3(pmap->pm_cr3);
6923 PCPU_SET(curpmap, pmap);
6926 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
6928 CPU_CLR(cpuid, &oldpmap->pm_active);
6933 pmap_activate(struct thread *td)
6937 pmap_activate_sw(td);
6942 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
6947 * Increase the starting virtual address of the given mapping if a
6948 * different alignment might result in more superpage mappings.
6951 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
6952 vm_offset_t *addr, vm_size_t size)
6954 vm_offset_t superpage_offset;
6958 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
6959 offset += ptoa(object->pg_color);
6960 superpage_offset = offset & PDRMASK;
6961 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
6962 (*addr & PDRMASK) == superpage_offset)
6964 if ((*addr & PDRMASK) < superpage_offset)
6965 *addr = (*addr & ~PDRMASK) + superpage_offset;
6967 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
6971 static unsigned long num_dirty_emulations;
6972 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
6973 &num_dirty_emulations, 0, NULL);
6975 static unsigned long num_accessed_emulations;
6976 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
6977 &num_accessed_emulations, 0, NULL);
6979 static unsigned long num_superpage_accessed_emulations;
6980 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
6981 &num_superpage_accessed_emulations, 0, NULL);
6983 static unsigned long ad_emulation_superpage_promotions;
6984 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
6985 &ad_emulation_superpage_promotions, 0, NULL);
6986 #endif /* INVARIANTS */
6989 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
6992 struct rwlock *lock;
6995 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
6997 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
6998 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7000 if (!pmap_emulate_ad_bits(pmap))
7003 PG_A = pmap_accessed_bit(pmap);
7004 PG_M = pmap_modified_bit(pmap);
7005 PG_V = pmap_valid_bit(pmap);
7006 PG_RW = pmap_rw_bit(pmap);
7012 pde = pmap_pde(pmap, va);
7013 if (pde == NULL || (*pde & PG_V) == 0)
7016 if ((*pde & PG_PS) != 0) {
7017 if (ftype == VM_PROT_READ) {
7019 atomic_add_long(&num_superpage_accessed_emulations, 1);
7027 pte = pmap_pde_to_pte(pde, va);
7028 if ((*pte & PG_V) == 0)
7031 if (ftype == VM_PROT_WRITE) {
7032 if ((*pte & PG_RW) == 0)
7035 * Set the modified and accessed bits simultaneously.
7037 * Intel EPT PTEs that do software emulation of A/D bits map
7038 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7039 * An EPT misconfiguration is triggered if the PTE is writable
7040 * but not readable (WR=10). This is avoided by setting PG_A
7041 * and PG_M simultaneously.
7043 *pte |= PG_M | PG_A;
7048 /* try to promote the mapping */
7049 if (va < VM_MAXUSER_ADDRESS)
7050 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7054 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7056 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7057 pmap_ps_enabled(pmap) &&
7058 (m->flags & PG_FICTITIOUS) == 0 &&
7059 vm_reserv_level_iffullpop(m) == 0) {
7060 pmap_promote_pde(pmap, pde, va, &lock);
7062 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7066 if (ftype == VM_PROT_WRITE)
7067 atomic_add_long(&num_dirty_emulations, 1);
7069 atomic_add_long(&num_accessed_emulations, 1);
7071 rv = 0; /* success */
7080 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7085 pt_entry_t *pte, PG_V;
7089 PG_V = pmap_valid_bit(pmap);
7092 pml4 = pmap_pml4e(pmap, va);
7094 if ((*pml4 & PG_V) == 0)
7097 pdp = pmap_pml4e_to_pdpe(pml4, va);
7099 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7102 pde = pmap_pdpe_to_pde(pdp, va);
7104 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7107 pte = pmap_pde_to_pte(pde, va);
7116 * Get the kernel virtual address of a set of physical pages. If there are
7117 * physical addresses not covered by the DMAP perform a transient mapping
7118 * that will be removed when calling pmap_unmap_io_transient.
7120 * \param page The pages the caller wishes to obtain the virtual
7121 * address on the kernel memory map.
7122 * \param vaddr On return contains the kernel virtual memory address
7123 * of the pages passed in the page parameter.
7124 * \param count Number of pages passed in.
7125 * \param can_fault TRUE if the thread using the mapped pages can take
7126 * page faults, FALSE otherwise.
7128 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7129 * finished or FALSE otherwise.
7133 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7134 boolean_t can_fault)
7137 boolean_t needs_mapping;
7139 int cache_bits, error, i;
7142 * Allocate any KVA space that we need, this is done in a separate
7143 * loop to prevent calling vmem_alloc while pinned.
7145 needs_mapping = FALSE;
7146 for (i = 0; i < count; i++) {
7147 paddr = VM_PAGE_TO_PHYS(page[i]);
7148 if (__predict_false(paddr >= dmaplimit)) {
7149 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7150 M_BESTFIT | M_WAITOK, &vaddr[i]);
7151 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7152 needs_mapping = TRUE;
7154 vaddr[i] = PHYS_TO_DMAP(paddr);
7158 /* Exit early if everything is covered by the DMAP */
7163 * NB: The sequence of updating a page table followed by accesses
7164 * to the corresponding pages used in the !DMAP case is subject to
7165 * the situation described in the "AMD64 Architecture Programmer's
7166 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7167 * Coherency Considerations". Therefore, issuing the INVLPG right
7168 * after modifying the PTE bits is crucial.
7172 for (i = 0; i < count; i++) {
7173 paddr = VM_PAGE_TO_PHYS(page[i]);
7174 if (paddr >= dmaplimit) {
7177 * Slow path, since we can get page faults
7178 * while mappings are active don't pin the
7179 * thread to the CPU and instead add a global
7180 * mapping visible to all CPUs.
7182 pmap_qenter(vaddr[i], &page[i], 1);
7184 pte = vtopte(vaddr[i]);
7185 cache_bits = pmap_cache_bits(kernel_pmap,
7186 page[i]->md.pat_mode, 0);
7187 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7194 return (needs_mapping);
7198 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7199 boolean_t can_fault)
7206 for (i = 0; i < count; i++) {
7207 paddr = VM_PAGE_TO_PHYS(page[i]);
7208 if (paddr >= dmaplimit) {
7210 pmap_qremove(vaddr[i], 1);
7211 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7217 pmap_quick_enter_page(vm_page_t m)
7221 paddr = VM_PAGE_TO_PHYS(m);
7222 if (paddr < dmaplimit)
7223 return (PHYS_TO_DMAP(paddr));
7224 mtx_lock_spin(&qframe_mtx);
7225 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7226 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7227 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7232 pmap_quick_remove_page(vm_offset_t addr)
7237 pte_store(vtopte(qframe), 0);
7239 mtx_unlock_spin(&qframe_mtx);
7242 #include "opt_ddb.h"
7244 #include <ddb/ddb.h>
7246 DB_SHOW_COMMAND(pte, pmap_print_pte)
7252 pt_entry_t *pte, PG_V;
7256 va = (vm_offset_t)addr;
7257 pmap = PCPU_GET(curpmap); /* XXX */
7259 db_printf("show pte addr\n");
7262 PG_V = pmap_valid_bit(pmap);
7263 pml4 = pmap_pml4e(pmap, va);
7264 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
7265 if ((*pml4 & PG_V) == 0) {
7269 pdp = pmap_pml4e_to_pdpe(pml4, va);
7270 db_printf(" pdpe %#016lx", *pdp);
7271 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
7275 pde = pmap_pdpe_to_pde(pdp, va);
7276 db_printf(" pde %#016lx", *pde);
7277 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
7281 pte = pmap_pde_to_pte(pde, va);
7282 db_printf(" pte %#016lx\n", *pte);
7285 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
7290 a = (vm_paddr_t)addr;
7291 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
7293 db_printf("show phys2dmap addr\n");