2 * Copyright (c) 1991 Regents of the University of California.
4 * Copyright (c) 1994 John S. Dyson
6 * Copyright (c) 1994 David Greenman
8 * Copyright (c) 2003 Peter Wemm
10 * Copyright (c) 2005-2010 Alan L. Cox <alc@cs.rice.edu>
11 * All rights reserved.
13 * This code is derived from software contributed to Berkeley by
14 * the Systems Programming Group of the University of Utah Computer
15 * Science Department and William Jolitz of UUNET Technologies Inc.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
25 * 3. All advertising materials mentioning features or use of this software
26 * must display the following acknowledgement:
27 * This product includes software developed by the University of
28 * California, Berkeley and its contributors.
29 * 4. Neither the name of the University nor the names of its contributors
30 * may be used to endorse or promote products derived from this software
31 * without specific prior written permission.
33 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
34 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
35 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
36 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
37 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
38 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
39 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
40 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
41 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
42 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
45 * from: @(#)pmap.c 7.7 (Berkeley) 5/12/91
48 * Copyright (c) 2003 Networks Associates Technology, Inc.
49 * All rights reserved.
51 * This software was developed for the FreeBSD Project by Jake Burkholder,
52 * Safeport Network Services, and Network Associates Laboratories, the
53 * Security Research Division of Network Associates, Inc. under
54 * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
55 * CHATS research program.
57 * Redistribution and use in source and binary forms, with or without
58 * modification, are permitted provided that the following conditions
60 * 1. Redistributions of source code must retain the above copyright
61 * notice, this list of conditions and the following disclaimer.
62 * 2. Redistributions in binary form must reproduce the above copyright
63 * notice, this list of conditions and the following disclaimer in the
64 * documentation and/or other materials provided with the distribution.
66 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
67 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
68 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
69 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
70 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
71 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
72 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
73 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
74 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
75 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
79 #define AMD64_NPT_AWARE
81 #include <sys/cdefs.h>
82 __FBSDID("$FreeBSD$");
85 * Manages physical address maps.
87 * Since the information managed by this module is
88 * also stored by the logical address mapping module,
89 * this module may throw away valid virtual-to-physical
90 * mappings at almost any time. However, invalidations
91 * of virtual-to-physical mappings must be done as
94 * In order to cope with hardware architectures which
95 * make virtual-to-physical map invalidates expensive,
96 * this module may delay invalidate or reduced protection
97 * operations until such time as they are actually
98 * necessary. This module is given full information as
99 * to which processors are currently using which maps,
100 * and to when physical maps must be made correct.
103 #include "opt_pmap.h"
106 #include <sys/param.h>
107 #include <sys/bitstring.h>
109 #include <sys/systm.h>
110 #include <sys/kernel.h>
112 #include <sys/lock.h>
113 #include <sys/malloc.h>
114 #include <sys/mman.h>
115 #include <sys/mutex.h>
116 #include <sys/proc.h>
117 #include <sys/rwlock.h>
119 #include <sys/turnstile.h>
120 #include <sys/vmem.h>
121 #include <sys/vmmeter.h>
122 #include <sys/sched.h>
123 #include <sys/sysctl.h>
127 #include <vm/vm_param.h>
128 #include <vm/vm_kern.h>
129 #include <vm/vm_page.h>
130 #include <vm/vm_map.h>
131 #include <vm/vm_object.h>
132 #include <vm/vm_extern.h>
133 #include <vm/vm_pageout.h>
134 #include <vm/vm_pager.h>
135 #include <vm/vm_phys.h>
136 #include <vm/vm_radix.h>
137 #include <vm/vm_reserv.h>
140 #include <machine/intr_machdep.h>
141 #include <x86/apicvar.h>
142 #include <machine/cpu.h>
143 #include <machine/cputypes.h>
144 #include <machine/md_var.h>
145 #include <machine/pcb.h>
146 #include <machine/specialreg.h>
148 #include <machine/smp.h>
151 static __inline boolean_t
152 pmap_type_guest(pmap_t pmap)
155 return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
158 static __inline boolean_t
159 pmap_emulate_ad_bits(pmap_t pmap)
162 return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
165 static __inline pt_entry_t
166 pmap_valid_bit(pmap_t pmap)
170 switch (pmap->pm_type) {
176 if (pmap_emulate_ad_bits(pmap))
177 mask = EPT_PG_EMUL_V;
182 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
188 static __inline pt_entry_t
189 pmap_rw_bit(pmap_t pmap)
193 switch (pmap->pm_type) {
199 if (pmap_emulate_ad_bits(pmap))
200 mask = EPT_PG_EMUL_RW;
205 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
211 static __inline pt_entry_t
212 pmap_global_bit(pmap_t pmap)
216 switch (pmap->pm_type) {
225 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
231 static __inline pt_entry_t
232 pmap_accessed_bit(pmap_t pmap)
236 switch (pmap->pm_type) {
242 if (pmap_emulate_ad_bits(pmap))
248 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
254 static __inline pt_entry_t
255 pmap_modified_bit(pmap_t pmap)
259 switch (pmap->pm_type) {
265 if (pmap_emulate_ad_bits(pmap))
271 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
277 extern struct pcpu __pcpu[];
279 #if !defined(DIAGNOSTIC)
280 #ifdef __GNUC_GNU_INLINE__
281 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
283 #define PMAP_INLINE extern inline
290 #define PV_STAT(x) do { x ; } while (0)
292 #define PV_STAT(x) do { } while (0)
295 #define pa_index(pa) ((pa) >> PDRSHIFT)
296 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
298 #define NPV_LIST_LOCKS MAXCPU
300 #define PHYS_TO_PV_LIST_LOCK(pa) \
301 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
303 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
304 struct rwlock **_lockp = (lockp); \
305 struct rwlock *_new_lock; \
307 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
308 if (_new_lock != *_lockp) { \
309 if (*_lockp != NULL) \
310 rw_wunlock(*_lockp); \
311 *_lockp = _new_lock; \
316 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
317 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
319 #define RELEASE_PV_LIST_LOCK(lockp) do { \
320 struct rwlock **_lockp = (lockp); \
322 if (*_lockp != NULL) { \
323 rw_wunlock(*_lockp); \
328 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
329 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
331 struct pmap kernel_pmap_store;
333 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
334 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
337 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
338 "Number of kernel page table pages allocated on bootup");
341 vm_paddr_t dmaplimit;
342 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
345 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
347 static int pat_works = 1;
348 SYSCTL_INT(_vm_pmap, OID_AUTO, pat_works, CTLFLAG_RD, &pat_works, 1,
349 "Is page attribute table fully functional?");
351 static int pg_ps_enabled = 1;
352 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
353 &pg_ps_enabled, 0, "Are large page mappings enabled?");
355 #define PAT_INDEX_SIZE 8
356 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
358 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
359 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
360 u_int64_t KPDPphys; /* phys addr of kernel level 3 */
361 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
363 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
364 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
365 static int ndmpdpphys; /* number of DMPDPphys pages */
368 * pmap_mapdev support pre initialization (i.e. console)
370 #define PMAP_PREINIT_MAPPING_COUNT 8
371 static struct pmap_preinit_mapping {
376 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
377 static int pmap_initialized;
380 * Data for the pv entry allocation mechanism.
381 * Updates to pv_invl_gen are protected by the pv_list_locks[]
382 * elements, but reads are not.
384 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
385 static struct mtx pv_chunks_mutex;
386 static struct rwlock pv_list_locks[NPV_LIST_LOCKS];
387 static u_long pv_invl_gen[NPV_LIST_LOCKS];
388 static struct md_page *pv_table;
389 static struct md_page pv_dummy;
392 * All those kernel PT submaps that BSD is so fond of
394 pt_entry_t *CMAP1 = 0;
396 static vm_offset_t qframe = 0;
397 static struct mtx qframe_mtx;
399 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
401 int pmap_pcid_enabled = 1;
402 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
403 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
404 int invpcid_works = 0;
405 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
406 "Is the invpcid instruction available ?");
409 pmap_pcid_save_cnt_proc(SYSCTL_HANDLER_ARGS)
416 res += cpuid_to_pcpu[i]->pc_pm_save_cnt;
418 return (sysctl_handle_64(oidp, &res, 0, req));
420 SYSCTL_PROC(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLTYPE_U64 | CTLFLAG_RW |
421 CTLFLAG_MPSAFE, NULL, 0, pmap_pcid_save_cnt_proc, "QU",
422 "Count of saved TLB context on switch");
424 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
425 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
426 static struct mtx invl_gen_mtx;
427 static u_long pmap_invl_gen = 0;
428 /* Fake lock object to satisfy turnstiles interface. */
429 static struct lock_object invl_gen_ts = {
433 #define PMAP_ASSERT_NOT_IN_DI() \
434 KASSERT(curthread->td_md.md_invl_gen.gen == 0, ("DI already started"))
437 * Start a new Delayed Invalidation (DI) block of code, executed by
438 * the current thread. Within a DI block, the current thread may
439 * destroy both the page table and PV list entries for a mapping and
440 * then release the corresponding PV list lock before ensuring that
441 * the mapping is flushed from the TLBs of any processors with the
445 pmap_delayed_invl_started(void)
447 struct pmap_invl_gen *invl_gen;
450 invl_gen = &curthread->td_md.md_invl_gen;
451 PMAP_ASSERT_NOT_IN_DI();
452 mtx_lock(&invl_gen_mtx);
453 if (LIST_EMPTY(&pmap_invl_gen_tracker))
454 currgen = pmap_invl_gen;
456 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
457 invl_gen->gen = currgen + 1;
458 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
459 mtx_unlock(&invl_gen_mtx);
463 * Finish the DI block, previously started by the current thread. All
464 * required TLB flushes for the pages marked by
465 * pmap_delayed_invl_page() must be finished before this function is
468 * This function works by bumping the global DI generation number to
469 * the generation number of the current thread's DI, unless there is a
470 * pending DI that started earlier. In the latter case, bumping the
471 * global DI generation number would incorrectly signal that the
472 * earlier DI had finished. Instead, this function bumps the earlier
473 * DI's generation number to match the generation number of the
474 * current thread's DI.
477 pmap_delayed_invl_finished(void)
479 struct pmap_invl_gen *invl_gen, *next;
480 struct turnstile *ts;
482 invl_gen = &curthread->td_md.md_invl_gen;
483 KASSERT(invl_gen->gen != 0, ("missed invl_started"));
484 mtx_lock(&invl_gen_mtx);
485 next = LIST_NEXT(invl_gen, link);
487 turnstile_chain_lock(&invl_gen_ts);
488 ts = turnstile_lookup(&invl_gen_ts);
489 pmap_invl_gen = invl_gen->gen;
491 turnstile_broadcast(ts, TS_SHARED_QUEUE);
492 turnstile_unpend(ts, TS_SHARED_LOCK);
494 turnstile_chain_unlock(&invl_gen_ts);
496 next->gen = invl_gen->gen;
498 LIST_REMOVE(invl_gen, link);
499 mtx_unlock(&invl_gen_mtx);
504 static long invl_wait;
505 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
506 "Number of times DI invalidation blocked pmap_remove_all/write");
510 pmap_delayed_invl_genp(vm_page_t m)
513 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
517 * Ensure that all currently executing DI blocks, that need to flush
518 * TLB for the given page m, actually flushed the TLB at the time the
519 * function returned. If the page m has an empty PV list and we call
520 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
521 * valid mapping for the page m in either its page table or TLB.
523 * This function works by blocking until the global DI generation
524 * number catches up with the generation number associated with the
525 * given page m and its PV list. Since this function's callers
526 * typically own an object lock and sometimes own a page lock, it
527 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
531 pmap_delayed_invl_wait(vm_page_t m)
534 struct turnstile *ts;
537 bool accounted = false;
541 m_gen = pmap_delayed_invl_genp(m);
542 while (*m_gen > pmap_invl_gen) {
545 atomic_add_long(&invl_wait, 1);
549 ts = turnstile_trywait(&invl_gen_ts);
550 if (*m_gen > pmap_invl_gen)
551 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
553 turnstile_cancel(ts);
558 * Mark the page m's PV list as participating in the current thread's
559 * DI block. Any threads concurrently using m's PV list to remove or
560 * restrict all mappings to m will wait for the current thread's DI
561 * block to complete before proceeding.
563 * The function works by setting the DI generation number for m's PV
564 * list to at least the DI generation number of the current thread.
565 * This forces a caller of pmap_delayed_invl_wait() to block until
566 * current thread calls pmap_delayed_invl_finished().
569 pmap_delayed_invl_page(vm_page_t m)
573 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
574 gen = curthread->td_md.md_invl_gen.gen;
577 m_gen = pmap_delayed_invl_genp(m);
585 static caddr_t crashdumpmap;
587 static void free_pv_chunk(struct pv_chunk *pc);
588 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
589 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
590 static int popcnt_pc_map_pq(uint64_t *map);
591 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
592 static void reserve_pv_entries(pmap_t pmap, int needed,
593 struct rwlock **lockp);
594 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
595 struct rwlock **lockp);
596 static boolean_t pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
597 struct rwlock **lockp);
598 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
599 struct rwlock **lockp);
600 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
601 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
604 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode);
605 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
606 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
607 vm_offset_t va, struct rwlock **lockp);
608 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
610 static boolean_t pmap_enter_pde(pmap_t pmap, vm_offset_t va, vm_page_t m,
611 vm_prot_t prot, struct rwlock **lockp);
612 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
613 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
614 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
615 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
616 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
617 static vm_page_t pmap_lookup_pt_page(pmap_t pmap, vm_offset_t va);
618 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask);
619 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
620 struct rwlock **lockp);
621 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
623 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
624 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
625 struct spglist *free, struct rwlock **lockp);
626 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
627 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
628 static void pmap_remove_pt_page(pmap_t pmap, vm_page_t mpte);
629 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
630 struct spglist *free);
631 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
632 vm_page_t m, struct rwlock **lockp);
633 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
635 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
637 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
638 struct rwlock **lockp);
639 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
640 struct rwlock **lockp);
641 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
642 struct rwlock **lockp);
644 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
645 struct spglist *free);
646 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
647 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
650 * Move the kernel virtual free pointer to the next
651 * 2MB. This is used to help improve performance
652 * by using a large (2MB) page for much of the kernel
653 * (.text, .data, .bss)
656 pmap_kmem_choose(vm_offset_t addr)
658 vm_offset_t newaddr = addr;
660 newaddr = roundup2(addr, NBPDR);
664 /********************/
665 /* Inline functions */
666 /********************/
668 /* Return a non-clipped PD index for a given VA */
669 static __inline vm_pindex_t
670 pmap_pde_pindex(vm_offset_t va)
672 return (va >> PDRSHIFT);
676 /* Return a pointer to the PML4 slot that corresponds to a VA */
677 static __inline pml4_entry_t *
678 pmap_pml4e(pmap_t pmap, vm_offset_t va)
681 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
684 /* Return a pointer to the PDP slot that corresponds to a VA */
685 static __inline pdp_entry_t *
686 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
690 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
691 return (&pdpe[pmap_pdpe_index(va)]);
694 /* Return a pointer to the PDP slot that corresponds to a VA */
695 static __inline pdp_entry_t *
696 pmap_pdpe(pmap_t pmap, vm_offset_t va)
701 PG_V = pmap_valid_bit(pmap);
702 pml4e = pmap_pml4e(pmap, va);
703 if ((*pml4e & PG_V) == 0)
705 return (pmap_pml4e_to_pdpe(pml4e, va));
708 /* Return a pointer to the PD slot that corresponds to a VA */
709 static __inline pd_entry_t *
710 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
714 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
715 return (&pde[pmap_pde_index(va)]);
718 /* Return a pointer to the PD slot that corresponds to a VA */
719 static __inline pd_entry_t *
720 pmap_pde(pmap_t pmap, vm_offset_t va)
725 PG_V = pmap_valid_bit(pmap);
726 pdpe = pmap_pdpe(pmap, va);
727 if (pdpe == NULL || (*pdpe & PG_V) == 0)
729 return (pmap_pdpe_to_pde(pdpe, va));
732 /* Return a pointer to the PT slot that corresponds to a VA */
733 static __inline pt_entry_t *
734 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
738 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
739 return (&pte[pmap_pte_index(va)]);
742 /* Return a pointer to the PT slot that corresponds to a VA */
743 static __inline pt_entry_t *
744 pmap_pte(pmap_t pmap, vm_offset_t va)
749 PG_V = pmap_valid_bit(pmap);
750 pde = pmap_pde(pmap, va);
751 if (pde == NULL || (*pde & PG_V) == 0)
753 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
754 return ((pt_entry_t *)pde);
755 return (pmap_pde_to_pte(pde, va));
759 pmap_resident_count_inc(pmap_t pmap, int count)
762 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
763 pmap->pm_stats.resident_count += count;
767 pmap_resident_count_dec(pmap_t pmap, int count)
770 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
771 KASSERT(pmap->pm_stats.resident_count >= count,
772 ("pmap %p resident count underflow %ld %d", pmap,
773 pmap->pm_stats.resident_count, count));
774 pmap->pm_stats.resident_count -= count;
777 PMAP_INLINE pt_entry_t *
778 vtopte(vm_offset_t va)
780 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
782 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
784 return (PTmap + ((va >> PAGE_SHIFT) & mask));
787 static __inline pd_entry_t *
788 vtopde(vm_offset_t va)
790 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
792 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
794 return (PDmap + ((va >> PDRSHIFT) & mask));
798 allocpages(vm_paddr_t *firstaddr, int n)
803 bzero((void *)ret, n * PAGE_SIZE);
804 *firstaddr += n * PAGE_SIZE;
808 CTASSERT(powerof2(NDMPML4E));
810 /* number of kernel PDP slots */
811 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
814 nkpt_init(vm_paddr_t addr)
821 pt_pages = howmany(addr, 1 << PDRSHIFT);
822 pt_pages += NKPDPE(pt_pages);
825 * Add some slop beyond the bare minimum required for bootstrapping
828 * This is quite important when allocating KVA for kernel modules.
829 * The modules are required to be linked in the negative 2GB of
830 * the address space. If we run out of KVA in this region then
831 * pmap_growkernel() will need to allocate page table pages to map
832 * the entire 512GB of KVA space which is an unnecessary tax on
835 * Secondly, device memory mapped as part of setting up the low-
836 * level console(s) is taken from KVA, starting at virtual_avail.
837 * This is because cninit() is called after pmap_bootstrap() but
838 * before vm_init() and pmap_init(). 20MB for a frame buffer is
841 pt_pages += 32; /* 64MB additional slop. */
847 create_pagetables(vm_paddr_t *firstaddr)
849 int i, j, ndm1g, nkpdpe;
855 /* Allocate page table pages for the direct map */
856 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
857 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
859 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
860 if (ndmpdpphys > NDMPML4E) {
862 * Each NDMPML4E allows 512 GB, so limit to that,
863 * and then readjust ndmpdp and ndmpdpphys.
865 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
866 Maxmem = atop(NDMPML4E * NBPML4);
867 ndmpdpphys = NDMPML4E;
868 ndmpdp = NDMPML4E * NPDEPG;
870 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
872 if ((amd_feature & AMDID_PAGE1GB) != 0)
873 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
875 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
876 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
879 KPML4phys = allocpages(firstaddr, 1);
880 KPDPphys = allocpages(firstaddr, NKPML4E);
883 * Allocate the initial number of kernel page table pages required to
884 * bootstrap. We defer this until after all memory-size dependent
885 * allocations are done (e.g. direct map), so that we don't have to
886 * build in too much slop in our estimate.
888 * Note that when NKPML4E > 1, we have an empty page underneath
889 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
890 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
892 nkpt_init(*firstaddr);
893 nkpdpe = NKPDPE(nkpt);
895 KPTphys = allocpages(firstaddr, nkpt);
896 KPDphys = allocpages(firstaddr, nkpdpe);
898 /* Fill in the underlying page table pages */
899 /* Nominally read-only (but really R/W) from zero to physfree */
900 /* XXX not fully used, underneath 2M pages */
901 pt_p = (pt_entry_t *)KPTphys;
902 for (i = 0; ptoa(i) < *firstaddr; i++)
903 pt_p[i] = ptoa(i) | X86_PG_RW | X86_PG_V | X86_PG_G;
905 /* Now map the page tables at their location within PTmap */
906 pd_p = (pd_entry_t *)KPDphys;
907 for (i = 0; i < nkpt; i++)
908 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
910 /* Map from zero to end of allocations under 2M pages */
911 /* This replaces some of the KPTphys entries above */
912 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
913 pd_p[i] = (i << PDRSHIFT) | X86_PG_RW | X86_PG_V | PG_PS |
916 /* And connect up the PD to the PDP (leaving room for L4 pages) */
917 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
918 for (i = 0; i < nkpdpe; i++)
919 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
923 * Now, set up the direct map region using 2MB and/or 1GB pages. If
924 * the end of physical memory is not aligned to a 1GB page boundary,
925 * then the residual physical memory is mapped with 2MB pages. Later,
926 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
927 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
928 * that are partially used.
930 pd_p = (pd_entry_t *)DMPDphys;
931 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
932 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
933 /* Preset PG_M and PG_A because demotion expects it. */
934 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | X86_PG_G |
937 pdp_p = (pdp_entry_t *)DMPDPphys;
938 for (i = 0; i < ndm1g; i++) {
939 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
940 /* Preset PG_M and PG_A because demotion expects it. */
941 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | X86_PG_G |
944 for (j = 0; i < ndmpdp; i++, j++) {
945 pdp_p[i] = DMPDphys + ptoa(j);
946 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_U;
949 /* And recursively map PML4 to itself in order to get PTmap */
950 p4_p = (pml4_entry_t *)KPML4phys;
951 p4_p[PML4PML4I] = KPML4phys;
952 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | PG_U;
954 /* Connect the Direct Map slot(s) up to the PML4. */
955 for (i = 0; i < ndmpdpphys; i++) {
956 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
957 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | PG_U;
960 /* Connect the KVA slots up to the PML4 */
961 for (i = 0; i < NKPML4E; i++) {
962 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
963 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V | PG_U;
968 * Bootstrap the system enough to run with virtual memory.
970 * On amd64 this is called after mapping has already been enabled
971 * and just syncs the pmap module with what has already been done.
972 * [We can't call it easily with mapping off since the kernel is not
973 * mapped with PA == VA, hence we would have to relocate every address
974 * from the linked base (virtual) address "KERNBASE" to the actual
975 * (physical) address starting relative to 0]
978 pmap_bootstrap(vm_paddr_t *firstaddr)
985 * Create an initial set of page tables to run the kernel in.
987 create_pagetables(firstaddr);
990 * Add a physical memory segment (vm_phys_seg) corresponding to the
991 * preallocated kernel page table pages so that vm_page structures
992 * representing these pages will be created. The vm_page structures
993 * are required for promotion of the corresponding kernel virtual
994 * addresses to superpage mappings.
996 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
998 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
999 virtual_avail = pmap_kmem_choose(virtual_avail);
1001 virtual_end = VM_MAX_KERNEL_ADDRESS;
1004 /* XXX do %cr0 as well */
1005 load_cr4(rcr4() | CR4_PGE);
1006 load_cr3(KPML4phys);
1007 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1008 load_cr4(rcr4() | CR4_SMEP);
1011 * Initialize the kernel pmap (which is statically allocated).
1013 PMAP_LOCK_INIT(kernel_pmap);
1014 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1015 kernel_pmap->pm_cr3 = KPML4phys;
1016 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1017 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1018 kernel_pmap->pm_flags = pmap_flags;
1021 * Initialize the TLB invalidations generation number lock.
1023 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1026 * Reserve some special page table entries/VA space for temporary
1029 #define SYSMAP(c, p, v, n) \
1030 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1036 * Crashdump maps. The first page is reused as CMAP1 for the
1039 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1040 CADDR1 = crashdumpmap;
1044 /* Initialize the PAT MSR. */
1047 /* Initialize TLB Context Id. */
1048 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1049 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1050 /* Check for INVPCID support */
1051 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1053 for (i = 0; i < MAXCPU; i++) {
1054 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1055 kernel_pmap->pm_pcids[i].pm_gen = 1;
1057 __pcpu[0].pc_pcid_next = PMAP_PCID_KERN + 1;
1058 __pcpu[0].pc_pcid_gen = 1;
1060 * pcpu area for APs is zeroed during AP startup.
1061 * pc_pcid_next and pc_pcid_gen are initialized by AP
1062 * during pcpu setup.
1064 load_cr4(rcr4() | CR4_PCIDE);
1066 pmap_pcid_enabled = 0;
1071 * Setup the PAT MSR.
1076 int pat_table[PAT_INDEX_SIZE];
1081 /* Bail if this CPU doesn't implement PAT. */
1082 if ((cpu_feature & CPUID_PAT) == 0)
1085 /* Set default PAT index table. */
1086 for (i = 0; i < PAT_INDEX_SIZE; i++)
1088 pat_table[PAT_WRITE_BACK] = 0;
1089 pat_table[PAT_WRITE_THROUGH] = 1;
1090 pat_table[PAT_UNCACHEABLE] = 3;
1091 pat_table[PAT_WRITE_COMBINING] = 3;
1092 pat_table[PAT_WRITE_PROTECTED] = 3;
1093 pat_table[PAT_UNCACHED] = 3;
1095 /* Initialize default PAT entries. */
1096 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1097 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1098 PAT_VALUE(2, PAT_UNCACHED) |
1099 PAT_VALUE(3, PAT_UNCACHEABLE) |
1100 PAT_VALUE(4, PAT_WRITE_BACK) |
1101 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1102 PAT_VALUE(6, PAT_UNCACHED) |
1103 PAT_VALUE(7, PAT_UNCACHEABLE);
1107 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1108 * Program 5 and 6 as WP and WC.
1109 * Leave 4 and 7 as WB and UC.
1111 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1112 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1113 PAT_VALUE(6, PAT_WRITE_COMBINING);
1114 pat_table[PAT_UNCACHED] = 2;
1115 pat_table[PAT_WRITE_PROTECTED] = 5;
1116 pat_table[PAT_WRITE_COMBINING] = 6;
1119 * Just replace PAT Index 2 with WC instead of UC-.
1121 pat_msr &= ~PAT_MASK(2);
1122 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1123 pat_table[PAT_WRITE_COMBINING] = 2;
1128 load_cr4(cr4 & ~CR4_PGE);
1130 /* Disable caches (CD = 1, NW = 0). */
1132 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1134 /* Flushes caches and TLBs. */
1138 /* Update PAT and index table. */
1139 wrmsr(MSR_PAT, pat_msr);
1140 for (i = 0; i < PAT_INDEX_SIZE; i++)
1141 pat_index[i] = pat_table[i];
1143 /* Flush caches and TLBs again. */
1147 /* Restore caches and PGE. */
1153 * Initialize a vm_page's machine-dependent fields.
1156 pmap_page_init(vm_page_t m)
1159 TAILQ_INIT(&m->md.pv_list);
1160 m->md.pat_mode = PAT_WRITE_BACK;
1164 * Initialize the pmap module.
1165 * Called by vm_init, to initialize any structures that the pmap
1166 * system needs to map virtual memory.
1171 struct pmap_preinit_mapping *ppim;
1174 int error, i, pv_npg;
1177 * Initialize the vm page array entries for the kernel pmap's
1180 for (i = 0; i < nkpt; i++) {
1181 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1182 KASSERT(mpte >= vm_page_array &&
1183 mpte < &vm_page_array[vm_page_array_size],
1184 ("pmap_init: page table page is out of range"));
1185 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1186 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1190 * If the kernel is running on a virtual machine, then it must assume
1191 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1192 * be prepared for the hypervisor changing the vendor and family that
1193 * are reported by CPUID. Consequently, the workaround for AMD Family
1194 * 10h Erratum 383 is enabled if the processor's feature set does not
1195 * include at least one feature that is only supported by older Intel
1196 * or newer AMD processors.
1198 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1199 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1200 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1202 workaround_erratum383 = 1;
1205 * Are large page mappings enabled?
1207 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1208 if (pg_ps_enabled) {
1209 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1210 ("pmap_init: can't assign to pagesizes[1]"));
1211 pagesizes[1] = NBPDR;
1215 * Initialize the pv chunk list mutex.
1217 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1220 * Initialize the pool of pv list locks.
1222 for (i = 0; i < NPV_LIST_LOCKS; i++)
1223 rw_init(&pv_list_locks[i], "pmap pv list");
1226 * Calculate the size of the pv head table for superpages.
1228 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1231 * Allocate memory for the pv head table for superpages.
1233 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1235 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1237 for (i = 0; i < pv_npg; i++)
1238 TAILQ_INIT(&pv_table[i].pv_list);
1239 TAILQ_INIT(&pv_dummy.pv_list);
1241 pmap_initialized = 1;
1242 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1243 ppim = pmap_preinit_mapping + i;
1246 /* Make the direct map consistent */
1247 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1248 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1249 ppim->sz, ppim->mode);
1253 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1254 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1257 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1258 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1259 (vmem_addr_t *)&qframe);
1261 panic("qframe allocation failed");
1264 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1265 "2MB page mapping counters");
1267 static u_long pmap_pde_demotions;
1268 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1269 &pmap_pde_demotions, 0, "2MB page demotions");
1271 static u_long pmap_pde_mappings;
1272 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1273 &pmap_pde_mappings, 0, "2MB page mappings");
1275 static u_long pmap_pde_p_failures;
1276 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1277 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1279 static u_long pmap_pde_promotions;
1280 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1281 &pmap_pde_promotions, 0, "2MB page promotions");
1283 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1284 "1GB page mapping counters");
1286 static u_long pmap_pdpe_demotions;
1287 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1288 &pmap_pdpe_demotions, 0, "1GB page demotions");
1290 /***************************************************
1291 * Low level helper routines.....
1292 ***************************************************/
1295 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1297 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1299 switch (pmap->pm_type) {
1302 /* Verify that both PAT bits are not set at the same time */
1303 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1304 ("Invalid PAT bits in entry %#lx", entry));
1306 /* Swap the PAT bits if one of them is set */
1307 if ((entry & x86_pat_bits) != 0)
1308 entry ^= x86_pat_bits;
1312 * Nothing to do - the memory attributes are represented
1313 * the same way for regular pages and superpages.
1317 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1324 * Determine the appropriate bits to set in a PTE or PDE for a specified
1328 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1330 int cache_bits, pat_flag, pat_idx;
1332 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1333 panic("Unknown caching mode %d\n", mode);
1335 switch (pmap->pm_type) {
1338 /* The PAT bit is different for PTE's and PDE's. */
1339 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1341 /* Map the caching mode to a PAT index. */
1342 pat_idx = pat_index[mode];
1344 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1347 cache_bits |= pat_flag;
1349 cache_bits |= PG_NC_PCD;
1351 cache_bits |= PG_NC_PWT;
1355 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1359 panic("unsupported pmap type %d", pmap->pm_type);
1362 return (cache_bits);
1366 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1370 switch (pmap->pm_type) {
1373 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1376 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1379 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1385 static __inline boolean_t
1386 pmap_ps_enabled(pmap_t pmap)
1389 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1393 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1396 switch (pmap->pm_type) {
1403 * This is a little bogus since the generation number is
1404 * supposed to be bumped up when a region of the address
1405 * space is invalidated in the page tables.
1407 * In this case the old PDE entry is valid but yet we want
1408 * to make sure that any mappings using the old entry are
1409 * invalidated in the TLB.
1411 * The reason this works as expected is because we rendezvous
1412 * "all" host cpus and force any vcpu context to exit as a
1415 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1418 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1420 pde_store(pde, newpde);
1424 * After changing the page size for the specified virtual address in the page
1425 * table, flush the corresponding entries from the processor's TLB. Only the
1426 * calling processor's TLB is affected.
1428 * The calling thread must be pinned to a processor.
1431 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1435 if (pmap_type_guest(pmap))
1438 KASSERT(pmap->pm_type == PT_X86,
1439 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1441 PG_G = pmap_global_bit(pmap);
1443 if ((newpde & PG_PS) == 0)
1444 /* Demotion: flush a specific 2MB page mapping. */
1446 else if ((newpde & PG_G) == 0)
1448 * Promotion: flush every 4KB page mapping from the TLB
1449 * because there are too many to flush individually.
1454 * Promotion: flush every 4KB page mapping from the TLB,
1455 * including any global (PG_G) mappings.
1463 * For SMP, these functions have to use the IPI mechanism for coherence.
1465 * N.B.: Before calling any of the following TLB invalidation functions,
1466 * the calling processor must ensure that all stores updating a non-
1467 * kernel page table are globally performed. Otherwise, another
1468 * processor could cache an old, pre-update entry without being
1469 * invalidated. This can happen one of two ways: (1) The pmap becomes
1470 * active on another processor after its pm_active field is checked by
1471 * one of the following functions but before a store updating the page
1472 * table is globally performed. (2) The pmap becomes active on another
1473 * processor before its pm_active field is checked but due to
1474 * speculative loads one of the following functions stills reads the
1475 * pmap as inactive on the other processor.
1477 * The kernel page table is exempt because its pm_active field is
1478 * immutable. The kernel page table is always active on every
1483 * Interrupt the cpus that are executing in the guest context.
1484 * This will force the vcpu to exit and the cached EPT mappings
1485 * will be invalidated by the host before the next vmresume.
1487 static __inline void
1488 pmap_invalidate_ept(pmap_t pmap)
1493 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1494 ("pmap_invalidate_ept: absurd pm_active"));
1497 * The TLB mappings associated with a vcpu context are not
1498 * flushed each time a different vcpu is chosen to execute.
1500 * This is in contrast with a process's vtop mappings that
1501 * are flushed from the TLB on each context switch.
1503 * Therefore we need to do more than just a TLB shootdown on
1504 * the active cpus in 'pmap->pm_active'. To do this we keep
1505 * track of the number of invalidations performed on this pmap.
1507 * Each vcpu keeps a cache of this counter and compares it
1508 * just before a vmresume. If the counter is out-of-date an
1509 * invept will be done to flush stale mappings from the TLB.
1511 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1514 * Force the vcpu to exit and trap back into the hypervisor.
1516 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1517 ipi_selected(pmap->pm_active, ipinum);
1522 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1527 if (pmap_type_guest(pmap)) {
1528 pmap_invalidate_ept(pmap);
1532 KASSERT(pmap->pm_type == PT_X86,
1533 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1536 if (pmap == kernel_pmap) {
1540 cpuid = PCPU_GET(cpuid);
1541 if (pmap == PCPU_GET(curpmap))
1543 else if (pmap_pcid_enabled)
1544 pmap->pm_pcids[cpuid].pm_gen = 0;
1545 if (pmap_pcid_enabled) {
1548 pmap->pm_pcids[i].pm_gen = 0;
1551 mask = &pmap->pm_active;
1553 smp_masked_invlpg(*mask, va);
1557 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1558 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1561 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1567 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1568 pmap_invalidate_all(pmap);
1572 if (pmap_type_guest(pmap)) {
1573 pmap_invalidate_ept(pmap);
1577 KASSERT(pmap->pm_type == PT_X86,
1578 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1581 cpuid = PCPU_GET(cpuid);
1582 if (pmap == kernel_pmap) {
1583 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1587 if (pmap == PCPU_GET(curpmap)) {
1588 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1590 } else if (pmap_pcid_enabled) {
1591 pmap->pm_pcids[cpuid].pm_gen = 0;
1593 if (pmap_pcid_enabled) {
1596 pmap->pm_pcids[i].pm_gen = 0;
1599 mask = &pmap->pm_active;
1601 smp_masked_invlpg_range(*mask, sva, eva);
1606 pmap_invalidate_all(pmap_t pmap)
1609 struct invpcid_descr d;
1612 if (pmap_type_guest(pmap)) {
1613 pmap_invalidate_ept(pmap);
1617 KASSERT(pmap->pm_type == PT_X86,
1618 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1621 if (pmap == kernel_pmap) {
1622 if (pmap_pcid_enabled && invpcid_works) {
1623 bzero(&d, sizeof(d));
1624 invpcid(&d, INVPCID_CTXGLOB);
1630 cpuid = PCPU_GET(cpuid);
1631 if (pmap == PCPU_GET(curpmap)) {
1632 if (pmap_pcid_enabled) {
1633 if (invpcid_works) {
1634 d.pcid = pmap->pm_pcids[cpuid].pm_pcid;
1637 invpcid(&d, INVPCID_CTX);
1639 load_cr3(pmap->pm_cr3 | pmap->pm_pcids
1640 [PCPU_GET(cpuid)].pm_pcid);
1645 } else if (pmap_pcid_enabled) {
1646 pmap->pm_pcids[cpuid].pm_gen = 0;
1648 if (pmap_pcid_enabled) {
1651 pmap->pm_pcids[i].pm_gen = 0;
1654 mask = &pmap->pm_active;
1656 smp_masked_invltlb(*mask, pmap);
1661 pmap_invalidate_cache(void)
1671 cpuset_t invalidate; /* processors that invalidate their TLB */
1676 u_int store; /* processor that updates the PDE */
1680 pmap_update_pde_action(void *arg)
1682 struct pde_action *act = arg;
1684 if (act->store == PCPU_GET(cpuid))
1685 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1689 pmap_update_pde_teardown(void *arg)
1691 struct pde_action *act = arg;
1693 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1694 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1698 * Change the page size for the specified virtual address in a way that
1699 * prevents any possibility of the TLB ever having two entries that map the
1700 * same virtual address using different page sizes. This is the recommended
1701 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1702 * machine check exception for a TLB state that is improperly diagnosed as a
1706 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1708 struct pde_action act;
1709 cpuset_t active, other_cpus;
1713 cpuid = PCPU_GET(cpuid);
1714 other_cpus = all_cpus;
1715 CPU_CLR(cpuid, &other_cpus);
1716 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1719 active = pmap->pm_active;
1721 if (CPU_OVERLAP(&active, &other_cpus)) {
1723 act.invalidate = active;
1727 act.newpde = newpde;
1728 CPU_SET(cpuid, &active);
1729 smp_rendezvous_cpus(active,
1730 smp_no_rendevous_barrier, pmap_update_pde_action,
1731 pmap_update_pde_teardown, &act);
1733 pmap_update_pde_store(pmap, pde, newpde);
1734 if (CPU_ISSET(cpuid, &active))
1735 pmap_update_pde_invalidate(pmap, va, newpde);
1741 * Normal, non-SMP, invalidation functions.
1744 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1747 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1751 KASSERT(pmap->pm_type == PT_X86,
1752 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1754 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1756 else if (pmap_pcid_enabled)
1757 pmap->pm_pcids[0].pm_gen = 0;
1761 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1765 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1769 KASSERT(pmap->pm_type == PT_X86,
1770 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1772 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1773 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1775 } else if (pmap_pcid_enabled) {
1776 pmap->pm_pcids[0].pm_gen = 0;
1781 pmap_invalidate_all(pmap_t pmap)
1783 struct invpcid_descr d;
1785 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1789 KASSERT(pmap->pm_type == PT_X86,
1790 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
1792 if (pmap == kernel_pmap) {
1793 if (pmap_pcid_enabled && invpcid_works) {
1794 bzero(&d, sizeof(d));
1795 invpcid(&d, INVPCID_CTXGLOB);
1799 } else if (pmap == PCPU_GET(curpmap)) {
1800 if (pmap_pcid_enabled) {
1801 if (invpcid_works) {
1802 d.pcid = pmap->pm_pcids[0].pm_pcid;
1805 invpcid(&d, INVPCID_CTX);
1807 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[0].
1813 } else if (pmap_pcid_enabled) {
1814 pmap->pm_pcids[0].pm_gen = 0;
1819 pmap_invalidate_cache(void)
1826 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1829 pmap_update_pde_store(pmap, pde, newpde);
1830 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1831 pmap_update_pde_invalidate(pmap, va, newpde);
1833 pmap->pm_pcids[0].pm_gen = 0;
1837 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
1840 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
1844 sva &= ~(vm_offset_t)cpu_clflush_line_size;
1846 KASSERT((sva & PAGE_MASK) == 0,
1847 ("pmap_invalidate_cache_range: sva not page-aligned"));
1848 KASSERT((eva & PAGE_MASK) == 0,
1849 ("pmap_invalidate_cache_range: eva not page-aligned"));
1852 if ((cpu_feature & CPUID_SS) != 0 && !force)
1853 ; /* If "Self Snoop" is supported and allowed, do nothing. */
1854 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
1855 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1857 * XXX: Some CPUs fault, hang, or trash the local APIC
1858 * registers if we use CLFLUSH on the local APIC
1859 * range. The local APIC is always uncached, so we
1860 * don't need to flush for that range anyway.
1862 if (pmap_kextract(sva) == lapic_paddr)
1866 * Otherwise, do per-cache line flush. Use the sfence
1867 * instruction to insure that previous stores are
1868 * included in the write-back. The processor
1869 * propagates flush to other processors in the cache
1873 for (; sva < eva; sva += cpu_clflush_line_size)
1876 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
1877 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1878 if (pmap_kextract(sva) == lapic_paddr)
1881 * Writes are ordered by CLFLUSH on Intel CPUs.
1883 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1885 for (; sva < eva; sva += cpu_clflush_line_size)
1887 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1892 * No targeted cache flush methods are supported by CPU,
1893 * or the supplied range is bigger than 2MB.
1894 * Globally invalidate cache.
1896 pmap_invalidate_cache();
1901 * Remove the specified set of pages from the data and instruction caches.
1903 * In contrast to pmap_invalidate_cache_range(), this function does not
1904 * rely on the CPU's self-snoop feature, because it is intended for use
1905 * when moving pages into a different cache domain.
1908 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1910 vm_offset_t daddr, eva;
1914 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
1915 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1916 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
1917 pmap_invalidate_cache();
1921 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
1923 for (i = 0; i < count; i++) {
1924 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
1925 eva = daddr + PAGE_SIZE;
1926 for (; daddr < eva; daddr += cpu_clflush_line_size) {
1935 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
1941 * Routine: pmap_extract
1943 * Extract the physical page address associated
1944 * with the given map/virtual_address pair.
1947 pmap_extract(pmap_t pmap, vm_offset_t va)
1951 pt_entry_t *pte, PG_V;
1955 PG_V = pmap_valid_bit(pmap);
1957 pdpe = pmap_pdpe(pmap, va);
1958 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
1959 if ((*pdpe & PG_PS) != 0)
1960 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
1962 pde = pmap_pdpe_to_pde(pdpe, va);
1963 if ((*pde & PG_V) != 0) {
1964 if ((*pde & PG_PS) != 0) {
1965 pa = (*pde & PG_PS_FRAME) |
1968 pte = pmap_pde_to_pte(pde, va);
1969 pa = (*pte & PG_FRAME) |
1980 * Routine: pmap_extract_and_hold
1982 * Atomically extract and hold the physical page
1983 * with the given pmap and virtual address pair
1984 * if that mapping permits the given protection.
1987 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1989 pd_entry_t pde, *pdep;
1990 pt_entry_t pte, PG_RW, PG_V;
1996 PG_RW = pmap_rw_bit(pmap);
1997 PG_V = pmap_valid_bit(pmap);
2000 pdep = pmap_pde(pmap, va);
2001 if (pdep != NULL && (pde = *pdep)) {
2003 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2004 if (vm_page_pa_tryrelock(pmap, (pde &
2005 PG_PS_FRAME) | (va & PDRMASK), &pa))
2007 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
2012 pte = *pmap_pde_to_pte(pdep, va);
2014 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2015 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2018 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
2029 pmap_kextract(vm_offset_t va)
2034 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2035 pa = DMAP_TO_PHYS(va);
2039 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2042 * Beware of a concurrent promotion that changes the
2043 * PDE at this point! For example, vtopte() must not
2044 * be used to access the PTE because it would use the
2045 * new PDE. It is, however, safe to use the old PDE
2046 * because the page table page is preserved by the
2049 pa = *pmap_pde_to_pte(&pde, va);
2050 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2056 /***************************************************
2057 * Low level mapping routines.....
2058 ***************************************************/
2061 * Add a wired page to the kva.
2062 * Note: not SMP coherent.
2065 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2070 pte_store(pte, pa | X86_PG_RW | X86_PG_V | X86_PG_G);
2073 static __inline void
2074 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2080 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2081 pte_store(pte, pa | X86_PG_RW | X86_PG_V | X86_PG_G | cache_bits);
2085 * Remove a page from the kernel pagetables.
2086 * Note: not SMP coherent.
2089 pmap_kremove(vm_offset_t va)
2098 * Used to map a range of physical addresses into kernel
2099 * virtual address space.
2101 * The value passed in '*virt' is a suggested virtual address for
2102 * the mapping. Architectures which can support a direct-mapped
2103 * physical to virtual region can return the appropriate address
2104 * within that region, leaving '*virt' unchanged. Other
2105 * architectures should map the pages starting at '*virt' and
2106 * update '*virt' with the first usable address after the mapped
2110 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2112 return PHYS_TO_DMAP(start);
2117 * Add a list of wired pages to the kva
2118 * this routine is only used for temporary
2119 * kernel mappings that do not need to have
2120 * page modification or references recorded.
2121 * Note that old mappings are simply written
2122 * over. The page *must* be wired.
2123 * Note: SMP coherent. Uses a ranged shootdown IPI.
2126 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2128 pt_entry_t *endpte, oldpte, pa, *pte;
2134 endpte = pte + count;
2135 while (pte < endpte) {
2137 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2138 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2139 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2141 pte_store(pte, pa | X86_PG_G | X86_PG_RW | X86_PG_V);
2145 if (__predict_false((oldpte & X86_PG_V) != 0))
2146 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2151 * This routine tears out page mappings from the
2152 * kernel -- it is meant only for temporary mappings.
2153 * Note: SMP coherent. Uses a ranged shootdown IPI.
2156 pmap_qremove(vm_offset_t sva, int count)
2161 while (count-- > 0) {
2162 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2166 pmap_invalidate_range(kernel_pmap, sva, va);
2169 /***************************************************
2170 * Page table page management routines.....
2171 ***************************************************/
2172 static __inline void
2173 pmap_free_zero_pages(struct spglist *free)
2177 while ((m = SLIST_FIRST(free)) != NULL) {
2178 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2179 /* Preserve the page's PG_ZERO setting. */
2180 vm_page_free_toq(m);
2185 * Schedule the specified unused page table page to be freed. Specifically,
2186 * add the page to the specified list of pages that will be released to the
2187 * physical memory manager after the TLB has been updated.
2189 static __inline void
2190 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2191 boolean_t set_PG_ZERO)
2195 m->flags |= PG_ZERO;
2197 m->flags &= ~PG_ZERO;
2198 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2202 * Inserts the specified page table page into the specified pmap's collection
2203 * of idle page table pages. Each of a pmap's page table pages is responsible
2204 * for mapping a distinct range of virtual addresses. The pmap's collection is
2205 * ordered by this virtual address range.
2208 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2211 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2212 return (vm_radix_insert(&pmap->pm_root, mpte));
2216 * Looks for a page table page mapping the specified virtual address in the
2217 * specified pmap's collection of idle page table pages. Returns NULL if there
2218 * is no page table page corresponding to the specified virtual address.
2220 static __inline vm_page_t
2221 pmap_lookup_pt_page(pmap_t pmap, vm_offset_t va)
2224 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2225 return (vm_radix_lookup(&pmap->pm_root, pmap_pde_pindex(va)));
2229 * Removes the specified page table page from the specified pmap's collection
2230 * of idle page table pages. The specified page table page must be a member of
2231 * the pmap's collection.
2233 static __inline void
2234 pmap_remove_pt_page(pmap_t pmap, vm_page_t mpte)
2237 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2238 vm_radix_remove(&pmap->pm_root, mpte->pindex);
2242 * Decrements a page table page's wire count, which is used to record the
2243 * number of valid page table entries within the page. If the wire count
2244 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2245 * page table page was unmapped and FALSE otherwise.
2247 static inline boolean_t
2248 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2252 if (m->wire_count == 0) {
2253 _pmap_unwire_ptp(pmap, va, m, free);
2260 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2263 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2265 * unmap the page table page
2267 if (m->pindex >= (NUPDE + NUPDPE)) {
2270 pml4 = pmap_pml4e(pmap, va);
2272 } else if (m->pindex >= NUPDE) {
2275 pdp = pmap_pdpe(pmap, va);
2280 pd = pmap_pde(pmap, va);
2283 pmap_resident_count_dec(pmap, 1);
2284 if (m->pindex < NUPDE) {
2285 /* We just released a PT, unhold the matching PD */
2288 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2289 pmap_unwire_ptp(pmap, va, pdpg, free);
2291 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2292 /* We just released a PD, unhold the matching PDP */
2295 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2296 pmap_unwire_ptp(pmap, va, pdppg, free);
2300 * This is a release store so that the ordinary store unmapping
2301 * the page table page is globally performed before TLB shoot-
2304 atomic_subtract_rel_int(&vm_cnt.v_wire_count, 1);
2307 * Put page on a list so that it is released after
2308 * *ALL* TLB shootdown is done
2310 pmap_add_delayed_free_list(m, free, TRUE);
2314 * After removing a page table entry, this routine is used to
2315 * conditionally free the page, and manage the hold/wire counts.
2318 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2319 struct spglist *free)
2323 if (va >= VM_MAXUSER_ADDRESS)
2325 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2326 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2327 return (pmap_unwire_ptp(pmap, va, mpte, free));
2331 pmap_pinit0(pmap_t pmap)
2335 PMAP_LOCK_INIT(pmap);
2336 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2337 pmap->pm_cr3 = KPML4phys;
2338 pmap->pm_root.rt_root = 0;
2339 CPU_ZERO(&pmap->pm_active);
2340 TAILQ_INIT(&pmap->pm_pvchunk);
2341 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2342 pmap->pm_flags = pmap_flags;
2344 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2345 pmap->pm_pcids[i].pm_gen = 0;
2347 PCPU_SET(curpmap, kernel_pmap);
2348 pmap_activate(curthread);
2349 CPU_FILL(&kernel_pmap->pm_active);
2353 pmap_pinit_pml4(vm_page_t pml4pg)
2355 pml4_entry_t *pm_pml4;
2358 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2360 /* Wire in kernel global address entries. */
2361 for (i = 0; i < NKPML4E; i++) {
2362 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2365 for (i = 0; i < ndmpdpphys; i++) {
2366 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2370 /* install self-referential address mapping entry(s) */
2371 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2372 X86_PG_A | X86_PG_M;
2376 * Initialize a preallocated and zeroed pmap structure,
2377 * such as one in a vmspace structure.
2380 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2383 vm_paddr_t pml4phys;
2387 * allocate the page directory page
2389 while ((pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2390 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL)
2393 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2394 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2396 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2397 pmap->pm_pcids[i].pm_gen = 0;
2399 pmap->pm_cr3 = ~0; /* initialize to an invalid value */
2401 if ((pml4pg->flags & PG_ZERO) == 0)
2402 pagezero(pmap->pm_pml4);
2405 * Do not install the host kernel mappings in the nested page
2406 * tables. These mappings are meaningless in the guest physical
2409 if ((pmap->pm_type = pm_type) == PT_X86) {
2410 pmap->pm_cr3 = pml4phys;
2411 pmap_pinit_pml4(pml4pg);
2414 pmap->pm_root.rt_root = 0;
2415 CPU_ZERO(&pmap->pm_active);
2416 TAILQ_INIT(&pmap->pm_pvchunk);
2417 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2418 pmap->pm_flags = flags;
2419 pmap->pm_eptgen = 0;
2425 pmap_pinit(pmap_t pmap)
2428 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2432 * This routine is called if the desired page table page does not exist.
2434 * If page table page allocation fails, this routine may sleep before
2435 * returning NULL. It sleeps only if a lock pointer was given.
2437 * Note: If a page allocation fails at page table level two or three,
2438 * one or two pages may be held during the wait, only to be released
2439 * afterwards. This conservative approach is easily argued to avoid
2443 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2445 vm_page_t m, pdppg, pdpg;
2446 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2448 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2450 PG_A = pmap_accessed_bit(pmap);
2451 PG_M = pmap_modified_bit(pmap);
2452 PG_V = pmap_valid_bit(pmap);
2453 PG_RW = pmap_rw_bit(pmap);
2456 * Allocate a page table page.
2458 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2459 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2460 if (lockp != NULL) {
2461 RELEASE_PV_LIST_LOCK(lockp);
2463 PMAP_ASSERT_NOT_IN_DI();
2469 * Indicate the need to retry. While waiting, the page table
2470 * page may have been allocated.
2474 if ((m->flags & PG_ZERO) == 0)
2478 * Map the pagetable page into the process address space, if
2479 * it isn't already there.
2482 if (ptepindex >= (NUPDE + NUPDPE)) {
2484 vm_pindex_t pml4index;
2486 /* Wire up a new PDPE page */
2487 pml4index = ptepindex - (NUPDE + NUPDPE);
2488 pml4 = &pmap->pm_pml4[pml4index];
2489 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2491 } else if (ptepindex >= NUPDE) {
2492 vm_pindex_t pml4index;
2493 vm_pindex_t pdpindex;
2497 /* Wire up a new PDE page */
2498 pdpindex = ptepindex - NUPDE;
2499 pml4index = pdpindex >> NPML4EPGSHIFT;
2501 pml4 = &pmap->pm_pml4[pml4index];
2502 if ((*pml4 & PG_V) == 0) {
2503 /* Have to allocate a new pdp, recurse */
2504 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2507 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2508 vm_page_free_zero(m);
2512 /* Add reference to pdp page */
2513 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2514 pdppg->wire_count++;
2516 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2518 /* Now find the pdp page */
2519 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2520 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2523 vm_pindex_t pml4index;
2524 vm_pindex_t pdpindex;
2529 /* Wire up a new PTE page */
2530 pdpindex = ptepindex >> NPDPEPGSHIFT;
2531 pml4index = pdpindex >> NPML4EPGSHIFT;
2533 /* First, find the pdp and check that its valid. */
2534 pml4 = &pmap->pm_pml4[pml4index];
2535 if ((*pml4 & PG_V) == 0) {
2536 /* Have to allocate a new pd, recurse */
2537 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2540 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2541 vm_page_free_zero(m);
2544 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2545 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2547 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2548 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2549 if ((*pdp & PG_V) == 0) {
2550 /* Have to allocate a new pd, recurse */
2551 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2554 atomic_subtract_int(&vm_cnt.v_wire_count,
2556 vm_page_free_zero(m);
2560 /* Add reference to the pd page */
2561 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2565 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2567 /* Now we know where the page directory page is */
2568 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2569 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2572 pmap_resident_count_inc(pmap, 1);
2578 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2580 vm_pindex_t pdpindex, ptepindex;
2581 pdp_entry_t *pdpe, PG_V;
2584 PG_V = pmap_valid_bit(pmap);
2587 pdpe = pmap_pdpe(pmap, va);
2588 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2589 /* Add a reference to the pd page. */
2590 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2593 /* Allocate a pd page. */
2594 ptepindex = pmap_pde_pindex(va);
2595 pdpindex = ptepindex >> NPDPEPGSHIFT;
2596 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2597 if (pdpg == NULL && lockp != NULL)
2604 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2606 vm_pindex_t ptepindex;
2607 pd_entry_t *pd, PG_V;
2610 PG_V = pmap_valid_bit(pmap);
2613 * Calculate pagetable page index
2615 ptepindex = pmap_pde_pindex(va);
2618 * Get the page directory entry
2620 pd = pmap_pde(pmap, va);
2623 * This supports switching from a 2MB page to a
2626 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2627 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2629 * Invalidation of the 2MB page mapping may have caused
2630 * the deallocation of the underlying PD page.
2637 * If the page table page is mapped, we just increment the
2638 * hold count, and activate it.
2640 if (pd != NULL && (*pd & PG_V) != 0) {
2641 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2645 * Here if the pte page isn't mapped, or if it has been
2648 m = _pmap_allocpte(pmap, ptepindex, lockp);
2649 if (m == NULL && lockp != NULL)
2656 /***************************************************
2657 * Pmap allocation/deallocation routines.
2658 ***************************************************/
2661 * Release any resources held by the given physical map.
2662 * Called when a pmap initialized by pmap_pinit is being released.
2663 * Should only be called if the map contains no valid mappings.
2666 pmap_release(pmap_t pmap)
2671 KASSERT(pmap->pm_stats.resident_count == 0,
2672 ("pmap_release: pmap resident count %ld != 0",
2673 pmap->pm_stats.resident_count));
2674 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2675 ("pmap_release: pmap has reserved page table page(s)"));
2676 KASSERT(CPU_EMPTY(&pmap->pm_active),
2677 ("releasing active pmap %p", pmap));
2679 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2681 for (i = 0; i < NKPML4E; i++) /* KVA */
2682 pmap->pm_pml4[KPML4BASE + i] = 0;
2683 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
2684 pmap->pm_pml4[DMPML4I + i] = 0;
2685 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
2688 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2689 vm_page_free_zero(m);
2693 kvm_size(SYSCTL_HANDLER_ARGS)
2695 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2697 return sysctl_handle_long(oidp, &ksize, 0, req);
2699 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2700 0, 0, kvm_size, "LU", "Size of KVM");
2703 kvm_free(SYSCTL_HANDLER_ARGS)
2705 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2707 return sysctl_handle_long(oidp, &kfree, 0, req);
2709 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2710 0, 0, kvm_free, "LU", "Amount of KVM free");
2713 * grow the number of kernel page table entries, if needed
2716 pmap_growkernel(vm_offset_t addr)
2720 pd_entry_t *pde, newpdir;
2723 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2726 * Return if "addr" is within the range of kernel page table pages
2727 * that were preallocated during pmap bootstrap. Moreover, leave
2728 * "kernel_vm_end" and the kernel page table as they were.
2730 * The correctness of this action is based on the following
2731 * argument: vm_map_insert() allocates contiguous ranges of the
2732 * kernel virtual address space. It calls this function if a range
2733 * ends after "kernel_vm_end". If the kernel is mapped between
2734 * "kernel_vm_end" and "addr", then the range cannot begin at
2735 * "kernel_vm_end". In fact, its beginning address cannot be less
2736 * than the kernel. Thus, there is no immediate need to allocate
2737 * any new kernel page table pages between "kernel_vm_end" and
2740 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
2743 addr = roundup2(addr, NBPDR);
2744 if (addr - 1 >= kernel_map->max_offset)
2745 addr = kernel_map->max_offset;
2746 while (kernel_vm_end < addr) {
2747 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
2748 if ((*pdpe & X86_PG_V) == 0) {
2749 /* We need a new PDP entry */
2750 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
2751 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
2752 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2754 panic("pmap_growkernel: no memory to grow kernel");
2755 if ((nkpg->flags & PG_ZERO) == 0)
2756 pmap_zero_page(nkpg);
2757 paddr = VM_PAGE_TO_PHYS(nkpg);
2758 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
2759 X86_PG_A | X86_PG_M);
2760 continue; /* try again */
2762 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
2763 if ((*pde & X86_PG_V) != 0) {
2764 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2765 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2766 kernel_vm_end = kernel_map->max_offset;
2772 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
2773 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
2776 panic("pmap_growkernel: no memory to grow kernel");
2777 if ((nkpg->flags & PG_ZERO) == 0)
2778 pmap_zero_page(nkpg);
2779 paddr = VM_PAGE_TO_PHYS(nkpg);
2780 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
2781 pde_store(pde, newpdir);
2783 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2784 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2785 kernel_vm_end = kernel_map->max_offset;
2792 /***************************************************
2793 * page management routines.
2794 ***************************************************/
2796 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
2797 CTASSERT(_NPCM == 3);
2798 CTASSERT(_NPCPV == 168);
2800 static __inline struct pv_chunk *
2801 pv_to_chunk(pv_entry_t pv)
2804 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
2807 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
2809 #define PC_FREE0 0xfffffffffffffffful
2810 #define PC_FREE1 0xfffffffffffffffful
2811 #define PC_FREE2 0x000000fffffffffful
2813 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
2816 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2818 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2819 "Current number of pv entry chunks");
2820 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2821 "Current number of pv entry chunks allocated");
2822 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2823 "Current number of pv entry chunks frees");
2824 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
2825 "Number of times tried to get a chunk page but failed.");
2827 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
2828 static int pv_entry_spare;
2830 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2831 "Current number of pv entry frees");
2832 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
2833 "Current number of pv entry allocs");
2834 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2835 "Current number of pv entries");
2836 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2837 "Current number of spare pv entries");
2841 * We are in a serious low memory condition. Resort to
2842 * drastic measures to free some pages so we can allocate
2843 * another pv entry chunk.
2845 * Returns NULL if PV entries were reclaimed from the specified pmap.
2847 * We do not, however, unmap 2mpages because subsequent accesses will
2848 * allocate per-page pv entries until repromotion occurs, thereby
2849 * exacerbating the shortage of free pv entries.
2852 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
2854 struct pch new_tail;
2855 struct pv_chunk *pc;
2856 struct md_page *pvh;
2859 pt_entry_t *pte, tpte;
2860 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
2864 struct spglist free;
2866 int bit, field, freed;
2868 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2869 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
2872 PG_G = PG_A = PG_M = PG_RW = 0;
2874 TAILQ_INIT(&new_tail);
2875 pmap_delayed_invl_started();
2876 mtx_lock(&pv_chunks_mutex);
2877 while ((pc = TAILQ_FIRST(&pv_chunks)) != NULL && SLIST_EMPTY(&free)) {
2878 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2879 mtx_unlock(&pv_chunks_mutex);
2880 if (pmap != pc->pc_pmap) {
2882 pmap_invalidate_all(pmap);
2883 if (pmap != locked_pmap)
2886 pmap_delayed_invl_finished();
2887 pmap_delayed_invl_started();
2889 /* Avoid deadlock and lock recursion. */
2890 if (pmap > locked_pmap) {
2891 RELEASE_PV_LIST_LOCK(lockp);
2893 } else if (pmap != locked_pmap &&
2894 !PMAP_TRYLOCK(pmap)) {
2896 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2897 mtx_lock(&pv_chunks_mutex);
2900 PG_G = pmap_global_bit(pmap);
2901 PG_A = pmap_accessed_bit(pmap);
2902 PG_M = pmap_modified_bit(pmap);
2903 PG_RW = pmap_rw_bit(pmap);
2907 * Destroy every non-wired, 4 KB page mapping in the chunk.
2910 for (field = 0; field < _NPCM; field++) {
2911 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2912 inuse != 0; inuse &= ~(1UL << bit)) {
2914 pv = &pc->pc_pventry[field * 64 + bit];
2916 pde = pmap_pde(pmap, va);
2917 if ((*pde & PG_PS) != 0)
2919 pte = pmap_pde_to_pte(pde, va);
2920 if ((*pte & PG_W) != 0)
2922 tpte = pte_load_clear(pte);
2923 if ((tpte & PG_G) != 0)
2924 pmap_invalidate_page(pmap, va);
2925 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
2926 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
2928 if ((tpte & PG_A) != 0)
2929 vm_page_aflag_set(m, PGA_REFERENCED);
2930 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
2931 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
2933 if (TAILQ_EMPTY(&m->md.pv_list) &&
2934 (m->flags & PG_FICTITIOUS) == 0) {
2935 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
2936 if (TAILQ_EMPTY(&pvh->pv_list)) {
2937 vm_page_aflag_clear(m,
2941 pmap_delayed_invl_page(m);
2942 pc->pc_map[field] |= 1UL << bit;
2943 pmap_unuse_pt(pmap, va, *pde, &free);
2948 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2949 mtx_lock(&pv_chunks_mutex);
2952 /* Every freed mapping is for a 4 KB page. */
2953 pmap_resident_count_dec(pmap, freed);
2954 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
2955 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
2956 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
2957 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2958 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
2959 pc->pc_map[2] == PC_FREE2) {
2960 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
2961 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
2962 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
2963 /* Entire chunk is free; return it. */
2964 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
2965 dump_drop_page(m_pc->phys_addr);
2966 mtx_lock(&pv_chunks_mutex);
2969 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2970 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2971 mtx_lock(&pv_chunks_mutex);
2972 /* One freed pv entry in locked_pmap is sufficient. */
2973 if (pmap == locked_pmap)
2976 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
2977 mtx_unlock(&pv_chunks_mutex);
2979 pmap_invalidate_all(pmap);
2980 if (pmap != locked_pmap)
2983 pmap_delayed_invl_finished();
2984 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
2985 m_pc = SLIST_FIRST(&free);
2986 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2987 /* Recycle a freed page table page. */
2988 m_pc->wire_count = 1;
2989 atomic_add_int(&vm_cnt.v_wire_count, 1);
2991 pmap_free_zero_pages(&free);
2996 * free the pv_entry back to the free list
2999 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3001 struct pv_chunk *pc;
3002 int idx, field, bit;
3004 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3005 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3006 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3007 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3008 pc = pv_to_chunk(pv);
3009 idx = pv - &pc->pc_pventry[0];
3012 pc->pc_map[field] |= 1ul << bit;
3013 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3014 pc->pc_map[2] != PC_FREE2) {
3015 /* 98% of the time, pc is already at the head of the list. */
3016 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3017 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3018 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3022 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3027 free_pv_chunk(struct pv_chunk *pc)
3031 mtx_lock(&pv_chunks_mutex);
3032 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3033 mtx_unlock(&pv_chunks_mutex);
3034 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3035 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3036 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3037 /* entire chunk is free, return it */
3038 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3039 dump_drop_page(m->phys_addr);
3040 vm_page_unwire(m, PQ_NONE);
3045 * Returns a new PV entry, allocating a new PV chunk from the system when
3046 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3047 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3050 * The given PV list lock may be released.
3053 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3057 struct pv_chunk *pc;
3060 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3061 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3063 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3065 for (field = 0; field < _NPCM; field++) {
3066 if (pc->pc_map[field]) {
3067 bit = bsfq(pc->pc_map[field]);
3071 if (field < _NPCM) {
3072 pv = &pc->pc_pventry[field * 64 + bit];
3073 pc->pc_map[field] &= ~(1ul << bit);
3074 /* If this was the last item, move it to tail */
3075 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3076 pc->pc_map[2] == 0) {
3077 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3078 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3081 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3082 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3086 /* No free items, allocate another chunk */
3087 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3090 if (lockp == NULL) {
3091 PV_STAT(pc_chunk_tryfail++);
3094 m = reclaim_pv_chunk(pmap, lockp);
3098 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3099 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3100 dump_add_page(m->phys_addr);
3101 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3103 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3104 pc->pc_map[1] = PC_FREE1;
3105 pc->pc_map[2] = PC_FREE2;
3106 mtx_lock(&pv_chunks_mutex);
3107 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3108 mtx_unlock(&pv_chunks_mutex);
3109 pv = &pc->pc_pventry[0];
3110 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3111 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3112 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3117 * Returns the number of one bits within the given PV chunk map.
3119 * The erratas for Intel processors state that "POPCNT Instruction May
3120 * Take Longer to Execute Than Expected". It is believed that the
3121 * issue is the spurious dependency on the destination register.
3122 * Provide a hint to the register rename logic that the destination
3123 * value is overwritten, by clearing it, as suggested in the
3124 * optimization manual. It should be cheap for unaffected processors
3127 * Reference numbers for erratas are
3128 * 4th Gen Core: HSD146
3129 * 5th Gen Core: BDM85
3130 * 6th Gen Core: SKL029
3133 popcnt_pc_map_pq(uint64_t *map)
3137 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3138 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3139 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3140 : "=&r" (result), "=&r" (tmp)
3141 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3146 * Ensure that the number of spare PV entries in the specified pmap meets or
3147 * exceeds the given count, "needed".
3149 * The given PV list lock may be released.
3152 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3154 struct pch new_tail;
3155 struct pv_chunk *pc;
3159 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3160 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3163 * Newly allocated PV chunks must be stored in a private list until
3164 * the required number of PV chunks have been allocated. Otherwise,
3165 * reclaim_pv_chunk() could recycle one of these chunks. In
3166 * contrast, these chunks must be added to the pmap upon allocation.
3168 TAILQ_INIT(&new_tail);
3171 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3173 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3174 bit_count((bitstr_t *)pc->pc_map, 0,
3175 sizeof(pc->pc_map) * NBBY, &free);
3178 free = popcnt_pc_map_pq(pc->pc_map);
3182 if (avail >= needed)
3185 for (; avail < needed; avail += _NPCPV) {
3186 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3189 m = reclaim_pv_chunk(pmap, lockp);
3193 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3194 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3195 dump_add_page(m->phys_addr);
3196 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3198 pc->pc_map[0] = PC_FREE0;
3199 pc->pc_map[1] = PC_FREE1;
3200 pc->pc_map[2] = PC_FREE2;
3201 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3202 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3203 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3205 if (!TAILQ_EMPTY(&new_tail)) {
3206 mtx_lock(&pv_chunks_mutex);
3207 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3208 mtx_unlock(&pv_chunks_mutex);
3213 * First find and then remove the pv entry for the specified pmap and virtual
3214 * address from the specified pv list. Returns the pv entry if found and NULL
3215 * otherwise. This operation can be performed on pv lists for either 4KB or
3216 * 2MB page mappings.
3218 static __inline pv_entry_t
3219 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3223 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3224 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3225 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3234 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3235 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3236 * entries for each of the 4KB page mappings.
3239 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3240 struct rwlock **lockp)
3242 struct md_page *pvh;
3243 struct pv_chunk *pc;
3245 vm_offset_t va_last;
3249 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3250 KASSERT((pa & PDRMASK) == 0,
3251 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3252 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3255 * Transfer the 2mpage's pv entry for this mapping to the first
3256 * page's pv list. Once this transfer begins, the pv list lock
3257 * must not be released until the last pv entry is reinstantiated.
3259 pvh = pa_to_pvh(pa);
3260 va = trunc_2mpage(va);
3261 pv = pmap_pvh_remove(pvh, pmap, va);
3262 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3263 m = PHYS_TO_VM_PAGE(pa);
3264 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3266 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3267 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3268 va_last = va + NBPDR - PAGE_SIZE;
3270 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3271 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3272 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3273 for (field = 0; field < _NPCM; field++) {
3274 while (pc->pc_map[field]) {
3275 bit = bsfq(pc->pc_map[field]);
3276 pc->pc_map[field] &= ~(1ul << bit);
3277 pv = &pc->pc_pventry[field * 64 + bit];
3281 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3282 ("pmap_pv_demote_pde: page %p is not managed", m));
3283 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3289 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3290 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3293 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3294 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3295 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3297 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3298 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3302 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3303 * replace the many pv entries for the 4KB page mappings by a single pv entry
3304 * for the 2MB page mapping.
3307 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3308 struct rwlock **lockp)
3310 struct md_page *pvh;
3312 vm_offset_t va_last;
3315 KASSERT((pa & PDRMASK) == 0,
3316 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3317 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3320 * Transfer the first page's pv entry for this mapping to the 2mpage's
3321 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3322 * a transfer avoids the possibility that get_pv_entry() calls
3323 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3324 * mappings that is being promoted.
3326 m = PHYS_TO_VM_PAGE(pa);
3327 va = trunc_2mpage(va);
3328 pv = pmap_pvh_remove(&m->md, pmap, va);
3329 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3330 pvh = pa_to_pvh(pa);
3331 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3333 /* Free the remaining NPTEPG - 1 pv entries. */
3334 va_last = va + NBPDR - PAGE_SIZE;
3338 pmap_pvh_free(&m->md, pmap, va);
3339 } while (va < va_last);
3343 * First find and then destroy the pv entry for the specified pmap and virtual
3344 * address. This operation can be performed on pv lists for either 4KB or 2MB
3348 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3352 pv = pmap_pvh_remove(pvh, pmap, va);
3353 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3354 free_pv_entry(pmap, pv);
3358 * Conditionally create the PV entry for a 4KB page mapping if the required
3359 * memory can be allocated without resorting to reclamation.
3362 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3363 struct rwlock **lockp)
3367 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3368 /* Pass NULL instead of the lock pointer to disable reclamation. */
3369 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3371 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3372 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3380 * Conditionally create the PV entry for a 2MB page mapping if the required
3381 * memory can be allocated without resorting to reclamation.
3384 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3385 struct rwlock **lockp)
3387 struct md_page *pvh;
3390 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3391 /* Pass NULL instead of the lock pointer to disable reclamation. */
3392 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3394 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3395 pvh = pa_to_pvh(pa);
3396 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3404 * Fills a page table page with mappings to consecutive physical pages.
3407 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3411 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3413 newpte += PAGE_SIZE;
3418 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3419 * mapping is invalidated.
3422 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3424 struct rwlock *lock;
3428 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3435 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3436 struct rwlock **lockp)
3438 pd_entry_t newpde, oldpde;
3439 pt_entry_t *firstpte, newpte;
3440 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3443 struct spglist free;
3446 PG_G = pmap_global_bit(pmap);
3447 PG_A = pmap_accessed_bit(pmap);
3448 PG_M = pmap_modified_bit(pmap);
3449 PG_RW = pmap_rw_bit(pmap);
3450 PG_V = pmap_valid_bit(pmap);
3451 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3453 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3455 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3456 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3457 if ((oldpde & PG_A) != 0 && (mpte = pmap_lookup_pt_page(pmap, va)) !=
3459 pmap_remove_pt_page(pmap, mpte);
3461 KASSERT((oldpde & PG_W) == 0,
3462 ("pmap_demote_pde: page table page for a wired mapping"
3466 * Invalidate the 2MB page mapping and return "failure" if the
3467 * mapping was never accessed or the allocation of the new
3468 * page table page fails. If the 2MB page mapping belongs to
3469 * the direct map region of the kernel's address space, then
3470 * the page allocation request specifies the highest possible
3471 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3472 * normal. Page table pages are preallocated for every other
3473 * part of the kernel address space, so the direct map region
3474 * is the only part of the kernel address space that must be
3477 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3478 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3479 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3480 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3482 pmap_remove_pde(pmap, pde, trunc_2mpage(va), &free,
3484 pmap_invalidate_page(pmap, trunc_2mpage(va));
3485 pmap_free_zero_pages(&free);
3486 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3487 " in pmap %p", va, pmap);
3490 if (va < VM_MAXUSER_ADDRESS)
3491 pmap_resident_count_inc(pmap, 1);
3493 mptepa = VM_PAGE_TO_PHYS(mpte);
3494 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3495 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3496 KASSERT((oldpde & PG_A) != 0,
3497 ("pmap_demote_pde: oldpde is missing PG_A"));
3498 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3499 ("pmap_demote_pde: oldpde is missing PG_M"));
3500 newpte = oldpde & ~PG_PS;
3501 newpte = pmap_swap_pat(pmap, newpte);
3504 * If the page table page is new, initialize it.
3506 if (mpte->wire_count == 1) {
3507 mpte->wire_count = NPTEPG;
3508 pmap_fill_ptp(firstpte, newpte);
3510 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3511 ("pmap_demote_pde: firstpte and newpte map different physical"
3515 * If the mapping has changed attributes, update the page table
3518 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3519 pmap_fill_ptp(firstpte, newpte);
3522 * The spare PV entries must be reserved prior to demoting the
3523 * mapping, that is, prior to changing the PDE. Otherwise, the state
3524 * of the PDE and the PV lists will be inconsistent, which can result
3525 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3526 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3527 * PV entry for the 2MB page mapping that is being demoted.
3529 if ((oldpde & PG_MANAGED) != 0)
3530 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3533 * Demote the mapping. This pmap is locked. The old PDE has
3534 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3535 * set. Thus, there is no danger of a race with another
3536 * processor changing the setting of PG_A and/or PG_M between
3537 * the read above and the store below.
3539 if (workaround_erratum383)
3540 pmap_update_pde(pmap, va, pde, newpde);
3542 pde_store(pde, newpde);
3545 * Invalidate a stale recursive mapping of the page table page.
3547 if (va >= VM_MAXUSER_ADDRESS)
3548 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3551 * Demote the PV entry.
3553 if ((oldpde & PG_MANAGED) != 0)
3554 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3556 atomic_add_long(&pmap_pde_demotions, 1);
3557 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3558 " in pmap %p", va, pmap);
3563 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3566 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3572 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3573 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3574 mpte = pmap_lookup_pt_page(pmap, va);
3576 panic("pmap_remove_kernel_pde: Missing pt page.");
3578 pmap_remove_pt_page(pmap, mpte);
3579 mptepa = VM_PAGE_TO_PHYS(mpte);
3580 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3583 * Initialize the page table page.
3585 pagezero((void *)PHYS_TO_DMAP(mptepa));
3588 * Demote the mapping.
3590 if (workaround_erratum383)
3591 pmap_update_pde(pmap, va, pde, newpde);
3593 pde_store(pde, newpde);
3596 * Invalidate a stale recursive mapping of the page table page.
3598 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3602 * pmap_remove_pde: do the things to unmap a superpage in a process
3605 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
3606 struct spglist *free, struct rwlock **lockp)
3608 struct md_page *pvh;
3610 vm_offset_t eva, va;
3612 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3614 PG_G = pmap_global_bit(pmap);
3615 PG_A = pmap_accessed_bit(pmap);
3616 PG_M = pmap_modified_bit(pmap);
3617 PG_RW = pmap_rw_bit(pmap);
3619 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3620 KASSERT((sva & PDRMASK) == 0,
3621 ("pmap_remove_pde: sva is not 2mpage aligned"));
3622 oldpde = pte_load_clear(pdq);
3624 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
3627 * Machines that don't support invlpg, also don't support
3631 pmap_invalidate_page(kernel_pmap, sva);
3632 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
3633 if (oldpde & PG_MANAGED) {
3634 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
3635 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
3636 pmap_pvh_free(pvh, pmap, sva);
3638 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3639 va < eva; va += PAGE_SIZE, m++) {
3640 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3643 vm_page_aflag_set(m, PGA_REFERENCED);
3644 if (TAILQ_EMPTY(&m->md.pv_list) &&
3645 TAILQ_EMPTY(&pvh->pv_list))
3646 vm_page_aflag_clear(m, PGA_WRITEABLE);
3647 pmap_delayed_invl_page(m);
3650 if (pmap == kernel_pmap) {
3651 pmap_remove_kernel_pde(pmap, pdq, sva);
3653 mpte = pmap_lookup_pt_page(pmap, sva);
3655 pmap_remove_pt_page(pmap, mpte);
3656 pmap_resident_count_dec(pmap, 1);
3657 KASSERT(mpte->wire_count == NPTEPG,
3658 ("pmap_remove_pde: pte page wire count error"));
3659 mpte->wire_count = 0;
3660 pmap_add_delayed_free_list(mpte, free, FALSE);
3661 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3664 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
3668 * pmap_remove_pte: do the things to unmap a page in a process
3671 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
3672 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
3674 struct md_page *pvh;
3675 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
3678 PG_A = pmap_accessed_bit(pmap);
3679 PG_M = pmap_modified_bit(pmap);
3680 PG_RW = pmap_rw_bit(pmap);
3682 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3683 oldpte = pte_load_clear(ptq);
3685 pmap->pm_stats.wired_count -= 1;
3686 pmap_resident_count_dec(pmap, 1);
3687 if (oldpte & PG_MANAGED) {
3688 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
3689 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3692 vm_page_aflag_set(m, PGA_REFERENCED);
3693 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3694 pmap_pvh_free(&m->md, pmap, va);
3695 if (TAILQ_EMPTY(&m->md.pv_list) &&
3696 (m->flags & PG_FICTITIOUS) == 0) {
3697 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3698 if (TAILQ_EMPTY(&pvh->pv_list))
3699 vm_page_aflag_clear(m, PGA_WRITEABLE);
3701 pmap_delayed_invl_page(m);
3703 return (pmap_unuse_pt(pmap, va, ptepde, free));
3707 * Remove a single page from a process address space
3710 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
3711 struct spglist *free)
3713 struct rwlock *lock;
3714 pt_entry_t *pte, PG_V;
3716 PG_V = pmap_valid_bit(pmap);
3717 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3718 if ((*pde & PG_V) == 0)
3720 pte = pmap_pde_to_pte(pde, va);
3721 if ((*pte & PG_V) == 0)
3724 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
3727 pmap_invalidate_page(pmap, va);
3731 * Remove the given range of addresses from the specified map.
3733 * It is assumed that the start and end are properly
3734 * rounded to the page size.
3737 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3739 struct rwlock *lock;
3740 vm_offset_t va, va_next;
3741 pml4_entry_t *pml4e;
3743 pd_entry_t ptpaddr, *pde;
3744 pt_entry_t *pte, PG_G, PG_V;
3745 struct spglist free;
3748 PG_G = pmap_global_bit(pmap);
3749 PG_V = pmap_valid_bit(pmap);
3752 * Perform an unsynchronized read. This is, however, safe.
3754 if (pmap->pm_stats.resident_count == 0)
3760 pmap_delayed_invl_started();
3764 * special handling of removing one page. a very
3765 * common operation and easy to short circuit some
3768 if (sva + PAGE_SIZE == eva) {
3769 pde = pmap_pde(pmap, sva);
3770 if (pde && (*pde & PG_PS) == 0) {
3771 pmap_remove_page(pmap, sva, pde, &free);
3777 for (; sva < eva; sva = va_next) {
3779 if (pmap->pm_stats.resident_count == 0)
3782 pml4e = pmap_pml4e(pmap, sva);
3783 if ((*pml4e & PG_V) == 0) {
3784 va_next = (sva + NBPML4) & ~PML4MASK;
3790 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
3791 if ((*pdpe & PG_V) == 0) {
3792 va_next = (sva + NBPDP) & ~PDPMASK;
3799 * Calculate index for next page table.
3801 va_next = (sva + NBPDR) & ~PDRMASK;
3805 pde = pmap_pdpe_to_pde(pdpe, sva);
3809 * Weed out invalid mappings.
3815 * Check for large page.
3817 if ((ptpaddr & PG_PS) != 0) {
3819 * Are we removing the entire large page? If not,
3820 * demote the mapping and fall through.
3822 if (sva + NBPDR == va_next && eva >= va_next) {
3824 * The TLB entry for a PG_G mapping is
3825 * invalidated by pmap_remove_pde().
3827 if ((ptpaddr & PG_G) == 0)
3829 pmap_remove_pde(pmap, pde, sva, &free, &lock);
3831 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
3833 /* The large page mapping was destroyed. */
3840 * Limit our scan to either the end of the va represented
3841 * by the current page table page, or to the end of the
3842 * range being removed.
3848 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
3851 if (va != va_next) {
3852 pmap_invalidate_range(pmap, va, sva);
3857 if ((*pte & PG_G) == 0)
3859 else if (va == va_next)
3861 if (pmap_remove_pte(pmap, pte, sva, ptpaddr, &free,
3868 pmap_invalidate_range(pmap, va, sva);
3874 pmap_invalidate_all(pmap);
3876 pmap_delayed_invl_finished();
3877 pmap_free_zero_pages(&free);
3881 * Routine: pmap_remove_all
3883 * Removes this physical page from
3884 * all physical maps in which it resides.
3885 * Reflects back modify bits to the pager.
3888 * Original versions of this routine were very
3889 * inefficient because they iteratively called
3890 * pmap_remove (slow...)
3894 pmap_remove_all(vm_page_t m)
3896 struct md_page *pvh;
3899 struct rwlock *lock;
3900 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
3903 struct spglist free;
3904 int pvh_gen, md_gen;
3906 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3907 ("pmap_remove_all: page %p is not managed", m));
3909 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3910 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
3911 pa_to_pvh(VM_PAGE_TO_PHYS(m));
3914 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
3916 if (!PMAP_TRYLOCK(pmap)) {
3917 pvh_gen = pvh->pv_gen;
3921 if (pvh_gen != pvh->pv_gen) {
3928 pde = pmap_pde(pmap, va);
3929 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
3932 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3934 if (!PMAP_TRYLOCK(pmap)) {
3935 pvh_gen = pvh->pv_gen;
3936 md_gen = m->md.pv_gen;
3940 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
3946 PG_A = pmap_accessed_bit(pmap);
3947 PG_M = pmap_modified_bit(pmap);
3948 PG_RW = pmap_rw_bit(pmap);
3949 pmap_resident_count_dec(pmap, 1);
3950 pde = pmap_pde(pmap, pv->pv_va);
3951 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
3952 " a 2mpage in page %p's pv list", m));
3953 pte = pmap_pde_to_pte(pde, pv->pv_va);
3954 tpte = pte_load_clear(pte);
3956 pmap->pm_stats.wired_count--;
3958 vm_page_aflag_set(m, PGA_REFERENCED);
3961 * Update the vm_page_t clean and reference bits.
3963 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3965 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
3966 pmap_invalidate_page(pmap, pv->pv_va);
3967 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3969 free_pv_entry(pmap, pv);
3972 vm_page_aflag_clear(m, PGA_WRITEABLE);
3974 pmap_delayed_invl_wait(m);
3975 pmap_free_zero_pages(&free);
3979 * pmap_protect_pde: do the things to protect a 2mpage in a process
3982 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
3984 pd_entry_t newpde, oldpde;
3985 vm_offset_t eva, va;
3987 boolean_t anychanged;
3988 pt_entry_t PG_G, PG_M, PG_RW;
3990 PG_G = pmap_global_bit(pmap);
3991 PG_M = pmap_modified_bit(pmap);
3992 PG_RW = pmap_rw_bit(pmap);
3994 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3995 KASSERT((sva & PDRMASK) == 0,
3996 ("pmap_protect_pde: sva is not 2mpage aligned"));
3999 oldpde = newpde = *pde;
4000 if (oldpde & PG_MANAGED) {
4002 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4003 va < eva; va += PAGE_SIZE, m++)
4004 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
4007 if ((prot & VM_PROT_WRITE) == 0)
4008 newpde &= ~(PG_RW | PG_M);
4009 if ((prot & VM_PROT_EXECUTE) == 0)
4011 if (newpde != oldpde) {
4012 if (!atomic_cmpset_long(pde, oldpde, newpde))
4015 pmap_invalidate_page(pmap, sva);
4019 return (anychanged);
4023 * Set the physical protection on the
4024 * specified range of this map as requested.
4027 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4029 vm_offset_t va_next;
4030 pml4_entry_t *pml4e;
4032 pd_entry_t ptpaddr, *pde;
4033 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4034 boolean_t anychanged;
4036 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4037 if (prot == VM_PROT_NONE) {
4038 pmap_remove(pmap, sva, eva);
4042 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4043 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4046 PG_G = pmap_global_bit(pmap);
4047 PG_M = pmap_modified_bit(pmap);
4048 PG_V = pmap_valid_bit(pmap);
4049 PG_RW = pmap_rw_bit(pmap);
4053 for (; sva < eva; sva = va_next) {
4055 pml4e = pmap_pml4e(pmap, sva);
4056 if ((*pml4e & PG_V) == 0) {
4057 va_next = (sva + NBPML4) & ~PML4MASK;
4063 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4064 if ((*pdpe & PG_V) == 0) {
4065 va_next = (sva + NBPDP) & ~PDPMASK;
4071 va_next = (sva + NBPDR) & ~PDRMASK;
4075 pde = pmap_pdpe_to_pde(pdpe, sva);
4079 * Weed out invalid mappings.
4085 * Check for large page.
4087 if ((ptpaddr & PG_PS) != 0) {
4089 * Are we protecting the entire large page? If not,
4090 * demote the mapping and fall through.
4092 if (sva + NBPDR == va_next && eva >= va_next) {
4094 * The TLB entry for a PG_G mapping is
4095 * invalidated by pmap_protect_pde().
4097 if (pmap_protect_pde(pmap, pde, sva, prot))
4100 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4102 * The large page mapping was destroyed.
4111 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4113 pt_entry_t obits, pbits;
4117 obits = pbits = *pte;
4118 if ((pbits & PG_V) == 0)
4121 if ((prot & VM_PROT_WRITE) == 0) {
4122 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4123 (PG_MANAGED | PG_M | PG_RW)) {
4124 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4127 pbits &= ~(PG_RW | PG_M);
4129 if ((prot & VM_PROT_EXECUTE) == 0)
4132 if (pbits != obits) {
4133 if (!atomic_cmpset_long(pte, obits, pbits))
4136 pmap_invalidate_page(pmap, sva);
4143 pmap_invalidate_all(pmap);
4148 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4149 * single page table page (PTP) to a single 2MB page mapping. For promotion
4150 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4151 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4152 * identical characteristics.
4155 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4156 struct rwlock **lockp)
4159 pt_entry_t *firstpte, oldpte, pa, *pte;
4160 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4164 PG_A = pmap_accessed_bit(pmap);
4165 PG_G = pmap_global_bit(pmap);
4166 PG_M = pmap_modified_bit(pmap);
4167 PG_V = pmap_valid_bit(pmap);
4168 PG_RW = pmap_rw_bit(pmap);
4169 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4171 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4174 * Examine the first PTE in the specified PTP. Abort if this PTE is
4175 * either invalid, unused, or does not map the first 4KB physical page
4176 * within a 2MB page.
4178 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4181 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4182 atomic_add_long(&pmap_pde_p_failures, 1);
4183 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4184 " in pmap %p", va, pmap);
4187 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4189 * When PG_M is already clear, PG_RW can be cleared without
4190 * a TLB invalidation.
4192 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4198 * Examine each of the other PTEs in the specified PTP. Abort if this
4199 * PTE maps an unexpected 4KB physical page or does not have identical
4200 * characteristics to the first PTE.
4202 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4203 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4206 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4207 atomic_add_long(&pmap_pde_p_failures, 1);
4208 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4209 " in pmap %p", va, pmap);
4212 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4214 * When PG_M is already clear, PG_RW can be cleared
4215 * without a TLB invalidation.
4217 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4220 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4221 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4222 (va & ~PDRMASK), pmap);
4224 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4225 atomic_add_long(&pmap_pde_p_failures, 1);
4226 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4227 " in pmap %p", va, pmap);
4234 * Save the page table page in its current state until the PDE
4235 * mapping the superpage is demoted by pmap_demote_pde() or
4236 * destroyed by pmap_remove_pde().
4238 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4239 KASSERT(mpte >= vm_page_array &&
4240 mpte < &vm_page_array[vm_page_array_size],
4241 ("pmap_promote_pde: page table page is out of range"));
4242 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4243 ("pmap_promote_pde: page table page's pindex is wrong"));
4244 if (pmap_insert_pt_page(pmap, mpte)) {
4245 atomic_add_long(&pmap_pde_p_failures, 1);
4247 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4253 * Promote the pv entries.
4255 if ((newpde & PG_MANAGED) != 0)
4256 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4259 * Propagate the PAT index to its proper position.
4261 newpde = pmap_swap_pat(pmap, newpde);
4264 * Map the superpage.
4266 if (workaround_erratum383)
4267 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4269 pde_store(pde, PG_PS | newpde);
4271 atomic_add_long(&pmap_pde_promotions, 1);
4272 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4273 " in pmap %p", va, pmap);
4277 * Insert the given physical page (p) at
4278 * the specified virtual address (v) in the
4279 * target physical map with the protection requested.
4281 * If specified, the page will be wired down, meaning
4282 * that the related pte can not be reclaimed.
4284 * NB: This is the only routine which MAY NOT lazy-evaluate
4285 * or lose information. That is, this routine must actually
4286 * insert this page into the given map NOW.
4288 * When destroying both a page table and PV entry, this function
4289 * performs the TLB invalidation before releasing the PV list
4290 * lock, so we do not need pmap_delayed_invl_page() calls here.
4293 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4294 u_int flags, int8_t psind __unused)
4296 struct rwlock *lock;
4298 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4299 pt_entry_t newpte, origpte;
4305 PG_A = pmap_accessed_bit(pmap);
4306 PG_G = pmap_global_bit(pmap);
4307 PG_M = pmap_modified_bit(pmap);
4308 PG_V = pmap_valid_bit(pmap);
4309 PG_RW = pmap_rw_bit(pmap);
4311 va = trunc_page(va);
4312 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4313 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4314 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4316 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4317 va >= kmi.clean_eva,
4318 ("pmap_enter: managed mapping within the clean submap"));
4319 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4320 VM_OBJECT_ASSERT_LOCKED(m->object);
4321 pa = VM_PAGE_TO_PHYS(m);
4322 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4323 if ((flags & VM_PROT_WRITE) != 0)
4325 if ((prot & VM_PROT_WRITE) != 0)
4327 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4328 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4329 if ((prot & VM_PROT_EXECUTE) == 0)
4331 if ((flags & PMAP_ENTER_WIRED) != 0)
4333 if (va < VM_MAXUSER_ADDRESS)
4335 if (pmap == kernel_pmap)
4337 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, 0);
4340 * Set modified bit gratuitously for writeable mappings if
4341 * the page is unmanaged. We do not want to take a fault
4342 * to do the dirty bit accounting for these mappings.
4344 if ((m->oflags & VPO_UNMANAGED) != 0) {
4345 if ((newpte & PG_RW) != 0)
4355 * In the case that a page table page is not
4356 * resident, we are creating it here.
4359 pde = pmap_pde(pmap, va);
4360 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4361 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4362 pte = pmap_pde_to_pte(pde, va);
4363 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4364 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4367 } else if (va < VM_MAXUSER_ADDRESS) {
4369 * Here if the pte page isn't mapped, or if it has been
4372 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4373 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4374 nosleep ? NULL : &lock);
4375 if (mpte == NULL && nosleep) {
4379 return (KERN_RESOURCE_SHORTAGE);
4383 panic("pmap_enter: invalid page directory va=%#lx", va);
4388 * Is the specified virtual address already mapped?
4390 if ((origpte & PG_V) != 0) {
4392 * Wiring change, just update stats. We don't worry about
4393 * wiring PT pages as they remain resident as long as there
4394 * are valid mappings in them. Hence, if a user page is wired,
4395 * the PT page will be also.
4397 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4398 pmap->pm_stats.wired_count++;
4399 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4400 pmap->pm_stats.wired_count--;
4403 * Remove the extra PT page reference.
4407 KASSERT(mpte->wire_count > 0,
4408 ("pmap_enter: missing reference to page table page,"
4413 * Has the physical page changed?
4415 opa = origpte & PG_FRAME;
4418 * No, might be a protection or wiring change.
4420 if ((origpte & PG_MANAGED) != 0) {
4421 newpte |= PG_MANAGED;
4422 if ((newpte & PG_RW) != 0)
4423 vm_page_aflag_set(m, PGA_WRITEABLE);
4425 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4431 * Increment the counters.
4433 if ((newpte & PG_W) != 0)
4434 pmap->pm_stats.wired_count++;
4435 pmap_resident_count_inc(pmap, 1);
4439 * Enter on the PV list if part of our managed memory.
4441 if ((m->oflags & VPO_UNMANAGED) == 0) {
4442 newpte |= PG_MANAGED;
4443 pv = get_pv_entry(pmap, &lock);
4445 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4446 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4448 if ((newpte & PG_RW) != 0)
4449 vm_page_aflag_set(m, PGA_WRITEABLE);
4455 if ((origpte & PG_V) != 0) {
4457 origpte = pte_load_store(pte, newpte);
4458 opa = origpte & PG_FRAME;
4460 if ((origpte & PG_MANAGED) != 0) {
4461 om = PHYS_TO_VM_PAGE(opa);
4462 if ((origpte & (PG_M | PG_RW)) == (PG_M |
4465 if ((origpte & PG_A) != 0)
4466 vm_page_aflag_set(om, PGA_REFERENCED);
4467 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4468 pmap_pvh_free(&om->md, pmap, va);
4469 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4470 TAILQ_EMPTY(&om->md.pv_list) &&
4471 ((om->flags & PG_FICTITIOUS) != 0 ||
4472 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4473 vm_page_aflag_clear(om, PGA_WRITEABLE);
4475 } else if ((newpte & PG_M) == 0 && (origpte & (PG_M |
4476 PG_RW)) == (PG_M | PG_RW)) {
4477 if ((origpte & PG_MANAGED) != 0)
4481 * Although the PTE may still have PG_RW set, TLB
4482 * invalidation may nonetheless be required because
4483 * the PTE no longer has PG_M set.
4485 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4487 * This PTE change does not require TLB invalidation.
4491 if ((origpte & PG_A) != 0)
4492 pmap_invalidate_page(pmap, va);
4494 pte_store(pte, newpte);
4499 * If both the page table page and the reservation are fully
4500 * populated, then attempt promotion.
4502 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4503 pmap_ps_enabled(pmap) &&
4504 (m->flags & PG_FICTITIOUS) == 0 &&
4505 vm_reserv_level_iffullpop(m) == 0)
4506 pmap_promote_pde(pmap, pde, va, &lock);
4511 return (KERN_SUCCESS);
4515 * Tries to create a 2MB page mapping. Returns TRUE if successful and FALSE
4516 * otherwise. Fails if (1) a page table page cannot be allocated without
4517 * blocking, (2) a mapping already exists at the specified virtual address, or
4518 * (3) a pv entry cannot be allocated without reclaiming another pv entry.
4521 pmap_enter_pde(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4522 struct rwlock **lockp)
4524 pd_entry_t *pde, newpde;
4527 struct spglist free;
4529 PG_V = pmap_valid_bit(pmap);
4530 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4532 if ((mpde = pmap_allocpde(pmap, va, NULL)) == NULL) {
4533 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4534 " in pmap %p", va, pmap);
4537 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpde));
4538 pde = &pde[pmap_pde_index(va)];
4539 if ((*pde & PG_V) != 0) {
4540 KASSERT(mpde->wire_count > 1,
4541 ("pmap_enter_pde: mpde's wire count is too low"));
4543 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4544 " in pmap %p", va, pmap);
4547 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
4549 if ((m->oflags & VPO_UNMANAGED) == 0) {
4550 newpde |= PG_MANAGED;
4553 * Abort this mapping if its PV entry could not be created.
4555 if (!pmap_pv_insert_pde(pmap, va, VM_PAGE_TO_PHYS(m),
4558 if (pmap_unwire_ptp(pmap, va, mpde, &free)) {
4560 * Although "va" is not mapped, paging-
4561 * structure caches could nonetheless have
4562 * entries that refer to the freed page table
4563 * pages. Invalidate those entries.
4565 pmap_invalidate_page(pmap, va);
4566 pmap_free_zero_pages(&free);
4568 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4569 " in pmap %p", va, pmap);
4573 if ((prot & VM_PROT_EXECUTE) == 0)
4575 if (va < VM_MAXUSER_ADDRESS)
4579 * Increment counters.
4581 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
4584 * Map the superpage.
4586 pde_store(pde, newpde);
4588 atomic_add_long(&pmap_pde_mappings, 1);
4589 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
4590 " in pmap %p", va, pmap);
4595 * Maps a sequence of resident pages belonging to the same object.
4596 * The sequence begins with the given page m_start. This page is
4597 * mapped at the given virtual address start. Each subsequent page is
4598 * mapped at a virtual address that is offset from start by the same
4599 * amount as the page is offset from m_start within the object. The
4600 * last page in the sequence is the page with the largest offset from
4601 * m_start that can be mapped at a virtual address less than the given
4602 * virtual address end. Not every virtual page between start and end
4603 * is mapped; only those for which a resident page exists with the
4604 * corresponding offset from m_start are mapped.
4607 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
4608 vm_page_t m_start, vm_prot_t prot)
4610 struct rwlock *lock;
4613 vm_pindex_t diff, psize;
4615 VM_OBJECT_ASSERT_LOCKED(m_start->object);
4617 psize = atop(end - start);
4622 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
4623 va = start + ptoa(diff);
4624 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
4625 m->psind == 1 && pmap_ps_enabled(pmap) &&
4626 pmap_enter_pde(pmap, va, m, prot, &lock))
4627 m = &m[NBPDR / PAGE_SIZE - 1];
4629 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
4631 m = TAILQ_NEXT(m, listq);
4639 * this code makes some *MAJOR* assumptions:
4640 * 1. Current pmap & pmap exists.
4643 * 4. No page table pages.
4644 * but is *MUCH* faster than pmap_enter...
4648 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
4650 struct rwlock *lock;
4654 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
4661 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
4662 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
4664 struct spglist free;
4665 pt_entry_t *pte, PG_V;
4668 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
4669 (m->oflags & VPO_UNMANAGED) != 0,
4670 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
4671 PG_V = pmap_valid_bit(pmap);
4672 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4675 * In the case that a page table page is not
4676 * resident, we are creating it here.
4678 if (va < VM_MAXUSER_ADDRESS) {
4679 vm_pindex_t ptepindex;
4683 * Calculate pagetable page index
4685 ptepindex = pmap_pde_pindex(va);
4686 if (mpte && (mpte->pindex == ptepindex)) {
4690 * Get the page directory entry
4692 ptepa = pmap_pde(pmap, va);
4695 * If the page table page is mapped, we just increment
4696 * the hold count, and activate it. Otherwise, we
4697 * attempt to allocate a page table page. If this
4698 * attempt fails, we don't retry. Instead, we give up.
4700 if (ptepa && (*ptepa & PG_V) != 0) {
4703 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
4707 * Pass NULL instead of the PV list lock
4708 * pointer, because we don't intend to sleep.
4710 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
4715 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
4716 pte = &pte[pmap_pte_index(va)];
4730 * Enter on the PV list if part of our managed memory.
4732 if ((m->oflags & VPO_UNMANAGED) == 0 &&
4733 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
4736 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
4738 * Although "va" is not mapped, paging-
4739 * structure caches could nonetheless have
4740 * entries that refer to the freed page table
4741 * pages. Invalidate those entries.
4743 pmap_invalidate_page(pmap, va);
4744 pmap_free_zero_pages(&free);
4752 * Increment counters
4754 pmap_resident_count_inc(pmap, 1);
4756 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
4757 if ((prot & VM_PROT_EXECUTE) == 0)
4761 * Now validate mapping with RO protection
4763 if ((m->oflags & VPO_UNMANAGED) != 0)
4764 pte_store(pte, pa | PG_V | PG_U);
4766 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
4771 * Make a temporary mapping for a physical address. This is only intended
4772 * to be used for panic dumps.
4775 pmap_kenter_temporary(vm_paddr_t pa, int i)
4779 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
4780 pmap_kenter(va, pa);
4782 return ((void *)crashdumpmap);
4786 * This code maps large physical mmap regions into the
4787 * processor address space. Note that some shortcuts
4788 * are taken, but the code works.
4791 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
4792 vm_pindex_t pindex, vm_size_t size)
4795 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
4796 vm_paddr_t pa, ptepa;
4800 PG_A = pmap_accessed_bit(pmap);
4801 PG_M = pmap_modified_bit(pmap);
4802 PG_V = pmap_valid_bit(pmap);
4803 PG_RW = pmap_rw_bit(pmap);
4805 VM_OBJECT_ASSERT_WLOCKED(object);
4806 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
4807 ("pmap_object_init_pt: non-device object"));
4808 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
4809 if (!pmap_ps_enabled(pmap))
4811 if (!vm_object_populate(object, pindex, pindex + atop(size)))
4813 p = vm_page_lookup(object, pindex);
4814 KASSERT(p->valid == VM_PAGE_BITS_ALL,
4815 ("pmap_object_init_pt: invalid page %p", p));
4816 pat_mode = p->md.pat_mode;
4819 * Abort the mapping if the first page is not physically
4820 * aligned to a 2MB page boundary.
4822 ptepa = VM_PAGE_TO_PHYS(p);
4823 if (ptepa & (NBPDR - 1))
4827 * Skip the first page. Abort the mapping if the rest of
4828 * the pages are not physically contiguous or have differing
4829 * memory attributes.
4831 p = TAILQ_NEXT(p, listq);
4832 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
4834 KASSERT(p->valid == VM_PAGE_BITS_ALL,
4835 ("pmap_object_init_pt: invalid page %p", p));
4836 if (pa != VM_PAGE_TO_PHYS(p) ||
4837 pat_mode != p->md.pat_mode)
4839 p = TAILQ_NEXT(p, listq);
4843 * Map using 2MB pages. Since "ptepa" is 2M aligned and
4844 * "size" is a multiple of 2M, adding the PAT setting to "pa"
4845 * will not affect the termination of this loop.
4848 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
4849 pa < ptepa + size; pa += NBPDR) {
4850 pdpg = pmap_allocpde(pmap, addr, NULL);
4853 * The creation of mappings below is only an
4854 * optimization. If a page directory page
4855 * cannot be allocated without blocking,
4856 * continue on to the next mapping rather than
4862 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4863 pde = &pde[pmap_pde_index(addr)];
4864 if ((*pde & PG_V) == 0) {
4865 pde_store(pde, pa | PG_PS | PG_M | PG_A |
4866 PG_U | PG_RW | PG_V);
4867 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
4868 atomic_add_long(&pmap_pde_mappings, 1);
4870 /* Continue on if the PDE is already valid. */
4872 KASSERT(pdpg->wire_count > 0,
4873 ("pmap_object_init_pt: missing reference "
4874 "to page directory page, va: 0x%lx", addr));
4883 * Clear the wired attribute from the mappings for the specified range of
4884 * addresses in the given pmap. Every valid mapping within that range
4885 * must have the wired attribute set. In contrast, invalid mappings
4886 * cannot have the wired attribute set, so they are ignored.
4888 * The wired attribute of the page table entry is not a hardware
4889 * feature, so there is no need to invalidate any TLB entries.
4890 * Since pmap_demote_pde() for the wired entry must never fail,
4891 * pmap_delayed_invl_started()/finished() calls around the
4892 * function are not needed.
4895 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4897 vm_offset_t va_next;
4898 pml4_entry_t *pml4e;
4901 pt_entry_t *pte, PG_V;
4903 PG_V = pmap_valid_bit(pmap);
4905 for (; sva < eva; sva = va_next) {
4906 pml4e = pmap_pml4e(pmap, sva);
4907 if ((*pml4e & PG_V) == 0) {
4908 va_next = (sva + NBPML4) & ~PML4MASK;
4913 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4914 if ((*pdpe & PG_V) == 0) {
4915 va_next = (sva + NBPDP) & ~PDPMASK;
4920 va_next = (sva + NBPDR) & ~PDRMASK;
4923 pde = pmap_pdpe_to_pde(pdpe, sva);
4924 if ((*pde & PG_V) == 0)
4926 if ((*pde & PG_PS) != 0) {
4927 if ((*pde & PG_W) == 0)
4928 panic("pmap_unwire: pde %#jx is missing PG_W",
4932 * Are we unwiring the entire large page? If not,
4933 * demote the mapping and fall through.
4935 if (sva + NBPDR == va_next && eva >= va_next) {
4936 atomic_clear_long(pde, PG_W);
4937 pmap->pm_stats.wired_count -= NBPDR /
4940 } else if (!pmap_demote_pde(pmap, pde, sva))
4941 panic("pmap_unwire: demotion failed");
4945 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4947 if ((*pte & PG_V) == 0)
4949 if ((*pte & PG_W) == 0)
4950 panic("pmap_unwire: pte %#jx is missing PG_W",
4954 * PG_W must be cleared atomically. Although the pmap
4955 * lock synchronizes access to PG_W, another processor
4956 * could be setting PG_M and/or PG_A concurrently.
4958 atomic_clear_long(pte, PG_W);
4959 pmap->pm_stats.wired_count--;
4966 * Copy the range specified by src_addr/len
4967 * from the source map to the range dst_addr/len
4968 * in the destination map.
4970 * This routine is only advisory and need not do anything.
4974 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
4975 vm_offset_t src_addr)
4977 struct rwlock *lock;
4978 struct spglist free;
4980 vm_offset_t end_addr = src_addr + len;
4981 vm_offset_t va_next;
4982 pt_entry_t PG_A, PG_M, PG_V;
4984 if (dst_addr != src_addr)
4987 if (dst_pmap->pm_type != src_pmap->pm_type)
4991 * EPT page table entries that require emulation of A/D bits are
4992 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
4993 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
4994 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
4995 * implementations flag an EPT misconfiguration for exec-only
4996 * mappings we skip this function entirely for emulated pmaps.
4998 if (pmap_emulate_ad_bits(dst_pmap))
5002 if (dst_pmap < src_pmap) {
5003 PMAP_LOCK(dst_pmap);
5004 PMAP_LOCK(src_pmap);
5006 PMAP_LOCK(src_pmap);
5007 PMAP_LOCK(dst_pmap);
5010 PG_A = pmap_accessed_bit(dst_pmap);
5011 PG_M = pmap_modified_bit(dst_pmap);
5012 PG_V = pmap_valid_bit(dst_pmap);
5014 for (addr = src_addr; addr < end_addr; addr = va_next) {
5015 pt_entry_t *src_pte, *dst_pte;
5016 vm_page_t dstmpde, dstmpte, srcmpte;
5017 pml4_entry_t *pml4e;
5019 pd_entry_t srcptepaddr, *pde;
5021 KASSERT(addr < UPT_MIN_ADDRESS,
5022 ("pmap_copy: invalid to pmap_copy page tables"));
5024 pml4e = pmap_pml4e(src_pmap, addr);
5025 if ((*pml4e & PG_V) == 0) {
5026 va_next = (addr + NBPML4) & ~PML4MASK;
5032 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5033 if ((*pdpe & PG_V) == 0) {
5034 va_next = (addr + NBPDP) & ~PDPMASK;
5040 va_next = (addr + NBPDR) & ~PDRMASK;
5044 pde = pmap_pdpe_to_pde(pdpe, addr);
5046 if (srcptepaddr == 0)
5049 if (srcptepaddr & PG_PS) {
5050 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5052 dstmpde = pmap_allocpde(dst_pmap, addr, NULL);
5053 if (dstmpde == NULL)
5055 pde = (pd_entry_t *)
5056 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpde));
5057 pde = &pde[pmap_pde_index(addr)];
5058 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5059 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr &
5060 PG_PS_FRAME, &lock))) {
5061 *pde = srcptepaddr & ~PG_W;
5062 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5063 atomic_add_long(&pmap_pde_mappings, 1);
5065 dstmpde->wire_count--;
5069 srcptepaddr &= PG_FRAME;
5070 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5071 KASSERT(srcmpte->wire_count > 0,
5072 ("pmap_copy: source page table page is unused"));
5074 if (va_next > end_addr)
5077 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5078 src_pte = &src_pte[pmap_pte_index(addr)];
5080 while (addr < va_next) {
5084 * we only virtual copy managed pages
5086 if ((ptetemp & PG_MANAGED) != 0) {
5087 if (dstmpte != NULL &&
5088 dstmpte->pindex == pmap_pde_pindex(addr))
5089 dstmpte->wire_count++;
5090 else if ((dstmpte = pmap_allocpte(dst_pmap,
5091 addr, NULL)) == NULL)
5093 dst_pte = (pt_entry_t *)
5094 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5095 dst_pte = &dst_pte[pmap_pte_index(addr)];
5096 if (*dst_pte == 0 &&
5097 pmap_try_insert_pv_entry(dst_pmap, addr,
5098 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5101 * Clear the wired, modified, and
5102 * accessed (referenced) bits
5105 *dst_pte = ptetemp & ~(PG_W | PG_M |
5107 pmap_resident_count_inc(dst_pmap, 1);
5110 if (pmap_unwire_ptp(dst_pmap, addr,
5113 * Although "addr" is not
5114 * mapped, paging-structure
5115 * caches could nonetheless
5116 * have entries that refer to
5117 * the freed page table pages.
5118 * Invalidate those entries.
5120 pmap_invalidate_page(dst_pmap,
5122 pmap_free_zero_pages(&free);
5126 if (dstmpte->wire_count >= srcmpte->wire_count)
5136 PMAP_UNLOCK(src_pmap);
5137 PMAP_UNLOCK(dst_pmap);
5141 * pmap_zero_page zeros the specified hardware page by mapping
5142 * the page into KVM and using bzero to clear its contents.
5145 pmap_zero_page(vm_page_t m)
5147 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5149 pagezero((void *)va);
5153 * pmap_zero_page_area zeros the specified hardware page by mapping
5154 * the page into KVM and using bzero to clear its contents.
5156 * off and size may not cover an area beyond a single hardware page.
5159 pmap_zero_page_area(vm_page_t m, int off, int size)
5161 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5163 if (off == 0 && size == PAGE_SIZE)
5164 pagezero((void *)va);
5166 bzero((char *)va + off, size);
5170 * pmap_zero_page_idle zeros the specified hardware page by mapping
5171 * the page into KVM and using bzero to clear its contents. This
5172 * is intended to be called from the vm_pagezero process only and
5176 pmap_zero_page_idle(vm_page_t m)
5178 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5180 pagezero((void *)va);
5184 * pmap_copy_page copies the specified (machine independent)
5185 * page by mapping the page into virtual memory and using
5186 * bcopy to copy the page, one machine dependent page at a
5190 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5192 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5193 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5195 pagecopy((void *)src, (void *)dst);
5198 int unmapped_buf_allowed = 1;
5201 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5202 vm_offset_t b_offset, int xfersize)
5206 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5210 while (xfersize > 0) {
5211 a_pg_offset = a_offset & PAGE_MASK;
5212 pages[0] = ma[a_offset >> PAGE_SHIFT];
5213 b_pg_offset = b_offset & PAGE_MASK;
5214 pages[1] = mb[b_offset >> PAGE_SHIFT];
5215 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5216 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5217 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5218 a_cp = (char *)vaddr[0] + a_pg_offset;
5219 b_cp = (char *)vaddr[1] + b_pg_offset;
5220 bcopy(a_cp, b_cp, cnt);
5221 if (__predict_false(mapped))
5222 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5230 * Returns true if the pmap's pv is one of the first
5231 * 16 pvs linked to from this page. This count may
5232 * be changed upwards or downwards in the future; it
5233 * is only necessary that true be returned for a small
5234 * subset of pmaps for proper page aging.
5237 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5239 struct md_page *pvh;
5240 struct rwlock *lock;
5245 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5246 ("pmap_page_exists_quick: page %p is not managed", m));
5248 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5250 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5251 if (PV_PMAP(pv) == pmap) {
5259 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5260 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5261 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5262 if (PV_PMAP(pv) == pmap) {
5276 * pmap_page_wired_mappings:
5278 * Return the number of managed mappings to the given physical page
5282 pmap_page_wired_mappings(vm_page_t m)
5284 struct rwlock *lock;
5285 struct md_page *pvh;
5289 int count, md_gen, pvh_gen;
5291 if ((m->oflags & VPO_UNMANAGED) != 0)
5293 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5297 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5299 if (!PMAP_TRYLOCK(pmap)) {
5300 md_gen = m->md.pv_gen;
5304 if (md_gen != m->md.pv_gen) {
5309 pte = pmap_pte(pmap, pv->pv_va);
5310 if ((*pte & PG_W) != 0)
5314 if ((m->flags & PG_FICTITIOUS) == 0) {
5315 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5316 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5318 if (!PMAP_TRYLOCK(pmap)) {
5319 md_gen = m->md.pv_gen;
5320 pvh_gen = pvh->pv_gen;
5324 if (md_gen != m->md.pv_gen ||
5325 pvh_gen != pvh->pv_gen) {
5330 pte = pmap_pde(pmap, pv->pv_va);
5331 if ((*pte & PG_W) != 0)
5341 * Returns TRUE if the given page is mapped individually or as part of
5342 * a 2mpage. Otherwise, returns FALSE.
5345 pmap_page_is_mapped(vm_page_t m)
5347 struct rwlock *lock;
5350 if ((m->oflags & VPO_UNMANAGED) != 0)
5352 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5354 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5355 ((m->flags & PG_FICTITIOUS) == 0 &&
5356 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5362 * Destroy all managed, non-wired mappings in the given user-space
5363 * pmap. This pmap cannot be active on any processor besides the
5366 * This function cannot be applied to the kernel pmap. Moreover, it
5367 * is not intended for general use. It is only to be used during
5368 * process termination. Consequently, it can be implemented in ways
5369 * that make it faster than pmap_remove(). First, it can more quickly
5370 * destroy mappings by iterating over the pmap's collection of PV
5371 * entries, rather than searching the page table. Second, it doesn't
5372 * have to test and clear the page table entries atomically, because
5373 * no processor is currently accessing the user address space. In
5374 * particular, a page table entry's dirty bit won't change state once
5375 * this function starts.
5378 pmap_remove_pages(pmap_t pmap)
5381 pt_entry_t *pte, tpte;
5382 pt_entry_t PG_M, PG_RW, PG_V;
5383 struct spglist free;
5384 vm_page_t m, mpte, mt;
5386 struct md_page *pvh;
5387 struct pv_chunk *pc, *npc;
5388 struct rwlock *lock;
5390 uint64_t inuse, bitmask;
5391 int allfree, field, freed, idx;
5392 boolean_t superpage;
5396 * Assert that the given pmap is only active on the current
5397 * CPU. Unfortunately, we cannot block another CPU from
5398 * activating the pmap while this function is executing.
5400 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5403 cpuset_t other_cpus;
5405 other_cpus = all_cpus;
5407 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5408 CPU_AND(&other_cpus, &pmap->pm_active);
5410 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5415 PG_M = pmap_modified_bit(pmap);
5416 PG_V = pmap_valid_bit(pmap);
5417 PG_RW = pmap_rw_bit(pmap);
5421 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5424 for (field = 0; field < _NPCM; field++) {
5425 inuse = ~pc->pc_map[field] & pc_freemask[field];
5426 while (inuse != 0) {
5428 bitmask = 1UL << bit;
5429 idx = field * 64 + bit;
5430 pv = &pc->pc_pventry[idx];
5433 pte = pmap_pdpe(pmap, pv->pv_va);
5435 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5437 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5440 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5442 pte = &pte[pmap_pte_index(pv->pv_va)];
5446 * Keep track whether 'tpte' is a
5447 * superpage explicitly instead of
5448 * relying on PG_PS being set.
5450 * This is because PG_PS is numerically
5451 * identical to PG_PTE_PAT and thus a
5452 * regular page could be mistaken for
5458 if ((tpte & PG_V) == 0) {
5459 panic("bad pte va %lx pte %lx",
5464 * We cannot remove wired pages from a process' mapping at this time
5472 pa = tpte & PG_PS_FRAME;
5474 pa = tpte & PG_FRAME;
5476 m = PHYS_TO_VM_PAGE(pa);
5477 KASSERT(m->phys_addr == pa,
5478 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5479 m, (uintmax_t)m->phys_addr,
5482 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5483 m < &vm_page_array[vm_page_array_size],
5484 ("pmap_remove_pages: bad tpte %#jx",
5490 * Update the vm_page_t clean/reference bits.
5492 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5494 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5500 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5503 pc->pc_map[field] |= bitmask;
5505 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
5506 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
5507 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5509 if (TAILQ_EMPTY(&pvh->pv_list)) {
5510 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5511 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
5512 TAILQ_EMPTY(&mt->md.pv_list))
5513 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5515 mpte = pmap_lookup_pt_page(pmap, pv->pv_va);
5517 pmap_remove_pt_page(pmap, mpte);
5518 pmap_resident_count_dec(pmap, 1);
5519 KASSERT(mpte->wire_count == NPTEPG,
5520 ("pmap_remove_pages: pte page wire count error"));
5521 mpte->wire_count = 0;
5522 pmap_add_delayed_free_list(mpte, &free, FALSE);
5523 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
5526 pmap_resident_count_dec(pmap, 1);
5527 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5529 if ((m->aflags & PGA_WRITEABLE) != 0 &&
5530 TAILQ_EMPTY(&m->md.pv_list) &&
5531 (m->flags & PG_FICTITIOUS) == 0) {
5532 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5533 if (TAILQ_EMPTY(&pvh->pv_list))
5534 vm_page_aflag_clear(m, PGA_WRITEABLE);
5537 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
5541 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5542 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5543 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5545 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5551 pmap_invalidate_all(pmap);
5553 pmap_free_zero_pages(&free);
5557 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
5559 struct rwlock *lock;
5561 struct md_page *pvh;
5562 pt_entry_t *pte, mask;
5563 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5565 int md_gen, pvh_gen;
5569 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5572 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5574 if (!PMAP_TRYLOCK(pmap)) {
5575 md_gen = m->md.pv_gen;
5579 if (md_gen != m->md.pv_gen) {
5584 pte = pmap_pte(pmap, pv->pv_va);
5587 PG_M = pmap_modified_bit(pmap);
5588 PG_RW = pmap_rw_bit(pmap);
5589 mask |= PG_RW | PG_M;
5592 PG_A = pmap_accessed_bit(pmap);
5593 PG_V = pmap_valid_bit(pmap);
5594 mask |= PG_V | PG_A;
5596 rv = (*pte & mask) == mask;
5601 if ((m->flags & PG_FICTITIOUS) == 0) {
5602 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5603 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5605 if (!PMAP_TRYLOCK(pmap)) {
5606 md_gen = m->md.pv_gen;
5607 pvh_gen = pvh->pv_gen;
5611 if (md_gen != m->md.pv_gen ||
5612 pvh_gen != pvh->pv_gen) {
5617 pte = pmap_pde(pmap, pv->pv_va);
5620 PG_M = pmap_modified_bit(pmap);
5621 PG_RW = pmap_rw_bit(pmap);
5622 mask |= PG_RW | PG_M;
5625 PG_A = pmap_accessed_bit(pmap);
5626 PG_V = pmap_valid_bit(pmap);
5627 mask |= PG_V | PG_A;
5629 rv = (*pte & mask) == mask;
5643 * Return whether or not the specified physical page was modified
5644 * in any physical maps.
5647 pmap_is_modified(vm_page_t m)
5650 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5651 ("pmap_is_modified: page %p is not managed", m));
5654 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5655 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
5656 * is clear, no PTEs can have PG_M set.
5658 VM_OBJECT_ASSERT_WLOCKED(m->object);
5659 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
5661 return (pmap_page_test_mappings(m, FALSE, TRUE));
5665 * pmap_is_prefaultable:
5667 * Return whether or not the specified virtual address is eligible
5671 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
5674 pt_entry_t *pte, PG_V;
5677 PG_V = pmap_valid_bit(pmap);
5680 pde = pmap_pde(pmap, addr);
5681 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
5682 pte = pmap_pde_to_pte(pde, addr);
5683 rv = (*pte & PG_V) == 0;
5690 * pmap_is_referenced:
5692 * Return whether or not the specified physical page was referenced
5693 * in any physical maps.
5696 pmap_is_referenced(vm_page_t m)
5699 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5700 ("pmap_is_referenced: page %p is not managed", m));
5701 return (pmap_page_test_mappings(m, TRUE, FALSE));
5705 * Clear the write and modified bits in each of the given page's mappings.
5708 pmap_remove_write(vm_page_t m)
5710 struct md_page *pvh;
5712 struct rwlock *lock;
5713 pv_entry_t next_pv, pv;
5715 pt_entry_t oldpte, *pte, PG_M, PG_RW;
5717 int pvh_gen, md_gen;
5719 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5720 ("pmap_remove_write: page %p is not managed", m));
5723 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5724 * set by another thread while the object is locked. Thus,
5725 * if PGA_WRITEABLE is clear, no page table entries need updating.
5727 VM_OBJECT_ASSERT_WLOCKED(m->object);
5728 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
5730 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5731 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
5732 pa_to_pvh(VM_PAGE_TO_PHYS(m));
5735 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
5737 if (!PMAP_TRYLOCK(pmap)) {
5738 pvh_gen = pvh->pv_gen;
5742 if (pvh_gen != pvh->pv_gen) {
5748 PG_RW = pmap_rw_bit(pmap);
5750 pde = pmap_pde(pmap, va);
5751 if ((*pde & PG_RW) != 0)
5752 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
5753 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
5754 ("inconsistent pv lock %p %p for page %p",
5755 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
5758 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5760 if (!PMAP_TRYLOCK(pmap)) {
5761 pvh_gen = pvh->pv_gen;
5762 md_gen = m->md.pv_gen;
5766 if (pvh_gen != pvh->pv_gen ||
5767 md_gen != m->md.pv_gen) {
5773 PG_M = pmap_modified_bit(pmap);
5774 PG_RW = pmap_rw_bit(pmap);
5775 pde = pmap_pde(pmap, pv->pv_va);
5776 KASSERT((*pde & PG_PS) == 0,
5777 ("pmap_remove_write: found a 2mpage in page %p's pv list",
5779 pte = pmap_pde_to_pte(pde, pv->pv_va);
5782 if (oldpte & PG_RW) {
5783 if (!atomic_cmpset_long(pte, oldpte, oldpte &
5786 if ((oldpte & PG_M) != 0)
5788 pmap_invalidate_page(pmap, pv->pv_va);
5793 vm_page_aflag_clear(m, PGA_WRITEABLE);
5794 pmap_delayed_invl_wait(m);
5797 static __inline boolean_t
5798 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
5801 if (!pmap_emulate_ad_bits(pmap))
5804 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
5807 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
5808 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
5809 * if the EPT_PG_WRITE bit is set.
5811 if ((pte & EPT_PG_WRITE) != 0)
5815 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
5817 if ((pte & EPT_PG_EXECUTE) == 0 ||
5818 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
5824 #define PMAP_TS_REFERENCED_MAX 5
5827 * pmap_ts_referenced:
5829 * Return a count of reference bits for a page, clearing those bits.
5830 * It is not necessary for every reference bit to be cleared, but it
5831 * is necessary that 0 only be returned when there are truly no
5832 * reference bits set.
5834 * XXX: The exact number of bits to check and clear is a matter that
5835 * should be tested and standardized at some point in the future for
5836 * optimal aging of shared pages.
5838 * As an optimization, update the page's dirty field if a modified bit is
5839 * found while counting reference bits. This opportunistic update can be
5840 * performed at low cost and can eliminate the need for some future calls
5841 * to pmap_is_modified(). However, since this function stops after
5842 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
5843 * dirty pages. Those dirty pages will only be detected by a future call
5844 * to pmap_is_modified().
5846 * A DI block is not needed within this function, because
5847 * invalidations are performed before the PV list lock is
5851 pmap_ts_referenced(vm_page_t m)
5853 struct md_page *pvh;
5856 struct rwlock *lock;
5857 pd_entry_t oldpde, *pde;
5858 pt_entry_t *pte, PG_A, PG_M, PG_RW;
5861 int cleared, md_gen, not_cleared, pvh_gen;
5862 struct spglist free;
5865 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5866 ("pmap_ts_referenced: page %p is not managed", m));
5869 pa = VM_PAGE_TO_PHYS(m);
5870 lock = PHYS_TO_PV_LIST_LOCK(pa);
5871 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
5875 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
5876 goto small_mappings;
5882 if (!PMAP_TRYLOCK(pmap)) {
5883 pvh_gen = pvh->pv_gen;
5887 if (pvh_gen != pvh->pv_gen) {
5892 PG_A = pmap_accessed_bit(pmap);
5893 PG_M = pmap_modified_bit(pmap);
5894 PG_RW = pmap_rw_bit(pmap);
5896 pde = pmap_pde(pmap, pv->pv_va);
5898 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5900 * Although "oldpde" is mapping a 2MB page, because
5901 * this function is called at a 4KB page granularity,
5902 * we only update the 4KB page under test.
5906 if ((*pde & PG_A) != 0) {
5908 * Since this reference bit is shared by 512 4KB
5909 * pages, it should not be cleared every time it is
5910 * tested. Apply a simple "hash" function on the
5911 * physical page number, the virtual superpage number,
5912 * and the pmap address to select one 4KB page out of
5913 * the 512 on which testing the reference bit will
5914 * result in clearing that reference bit. This
5915 * function is designed to avoid the selection of the
5916 * same 4KB page for every 2MB page mapping.
5918 * On demotion, a mapping that hasn't been referenced
5919 * is simply destroyed. To avoid the possibility of a
5920 * subsequent page fault on a demoted wired mapping,
5921 * always leave its reference bit set. Moreover,
5922 * since the superpage is wired, the current state of
5923 * its reference bit won't affect page replacement.
5925 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
5926 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
5927 (*pde & PG_W) == 0) {
5928 if (safe_to_clear_referenced(pmap, oldpde)) {
5929 atomic_clear_long(pde, PG_A);
5930 pmap_invalidate_page(pmap, pv->pv_va);
5932 } else if (pmap_demote_pde_locked(pmap, pde,
5933 pv->pv_va, &lock)) {
5935 * Remove the mapping to a single page
5936 * so that a subsequent access may
5937 * repromote. Since the underlying
5938 * page table page is fully populated,
5939 * this removal never frees a page
5943 va += VM_PAGE_TO_PHYS(m) - (oldpde &
5945 pte = pmap_pde_to_pte(pde, va);
5946 pmap_remove_pte(pmap, pte, va, *pde,
5948 pmap_invalidate_page(pmap, va);
5954 * The superpage mapping was removed
5955 * entirely and therefore 'pv' is no
5963 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
5964 ("inconsistent pv lock %p %p for page %p",
5965 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
5970 /* Rotate the PV list if it has more than one entry. */
5971 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
5972 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5973 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5976 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
5978 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
5980 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
5987 if (!PMAP_TRYLOCK(pmap)) {
5988 pvh_gen = pvh->pv_gen;
5989 md_gen = m->md.pv_gen;
5993 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
5998 PG_A = pmap_accessed_bit(pmap);
5999 PG_M = pmap_modified_bit(pmap);
6000 PG_RW = pmap_rw_bit(pmap);
6001 pde = pmap_pde(pmap, pv->pv_va);
6002 KASSERT((*pde & PG_PS) == 0,
6003 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6005 pte = pmap_pde_to_pte(pde, pv->pv_va);
6006 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6008 if ((*pte & PG_A) != 0) {
6009 if (safe_to_clear_referenced(pmap, *pte)) {
6010 atomic_clear_long(pte, PG_A);
6011 pmap_invalidate_page(pmap, pv->pv_va);
6013 } else if ((*pte & PG_W) == 0) {
6015 * Wired pages cannot be paged out so
6016 * doing accessed bit emulation for
6017 * them is wasted effort. We do the
6018 * hard work for unwired pages only.
6020 pmap_remove_pte(pmap, pte, pv->pv_va,
6021 *pde, &free, &lock);
6022 pmap_invalidate_page(pmap, pv->pv_va);
6027 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6028 ("inconsistent pv lock %p %p for page %p",
6029 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6034 /* Rotate the PV list if it has more than one entry. */
6035 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6036 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6037 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6040 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6041 not_cleared < PMAP_TS_REFERENCED_MAX);
6044 pmap_free_zero_pages(&free);
6045 return (cleared + not_cleared);
6049 * Apply the given advice to the specified range of addresses within the
6050 * given pmap. Depending on the advice, clear the referenced and/or
6051 * modified flags in each mapping and set the mapped page's dirty field.
6054 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6056 struct rwlock *lock;
6057 pml4_entry_t *pml4e;
6059 pd_entry_t oldpde, *pde;
6060 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6061 vm_offset_t va, va_next;
6063 boolean_t anychanged;
6065 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6069 * A/D bit emulation requires an alternate code path when clearing
6070 * the modified and accessed bits below. Since this function is
6071 * advisory in nature we skip it entirely for pmaps that require
6072 * A/D bit emulation.
6074 if (pmap_emulate_ad_bits(pmap))
6077 PG_A = pmap_accessed_bit(pmap);
6078 PG_G = pmap_global_bit(pmap);
6079 PG_M = pmap_modified_bit(pmap);
6080 PG_V = pmap_valid_bit(pmap);
6081 PG_RW = pmap_rw_bit(pmap);
6083 pmap_delayed_invl_started();
6085 for (; sva < eva; sva = va_next) {
6086 pml4e = pmap_pml4e(pmap, sva);
6087 if ((*pml4e & PG_V) == 0) {
6088 va_next = (sva + NBPML4) & ~PML4MASK;
6093 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6094 if ((*pdpe & PG_V) == 0) {
6095 va_next = (sva + NBPDP) & ~PDPMASK;
6100 va_next = (sva + NBPDR) & ~PDRMASK;
6103 pde = pmap_pdpe_to_pde(pdpe, sva);
6105 if ((oldpde & PG_V) == 0)
6107 else if ((oldpde & PG_PS) != 0) {
6108 if ((oldpde & PG_MANAGED) == 0)
6111 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6116 * The large page mapping was destroyed.
6122 * Unless the page mappings are wired, remove the
6123 * mapping to a single page so that a subsequent
6124 * access may repromote. Since the underlying page
6125 * table page is fully populated, this removal never
6126 * frees a page table page.
6128 if ((oldpde & PG_W) == 0) {
6129 pte = pmap_pde_to_pte(pde, sva);
6130 KASSERT((*pte & PG_V) != 0,
6131 ("pmap_advise: invalid PTE"));
6132 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6142 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6144 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6146 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6147 if (advice == MADV_DONTNEED) {
6149 * Future calls to pmap_is_modified()
6150 * can be avoided by making the page
6153 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6156 atomic_clear_long(pte, PG_M | PG_A);
6157 } else if ((*pte & PG_A) != 0)
6158 atomic_clear_long(pte, PG_A);
6162 if ((*pte & PG_G) != 0) {
6169 if (va != va_next) {
6170 pmap_invalidate_range(pmap, va, sva);
6175 pmap_invalidate_range(pmap, va, sva);
6178 pmap_invalidate_all(pmap);
6180 pmap_delayed_invl_finished();
6184 * Clear the modify bits on the specified physical page.
6187 pmap_clear_modify(vm_page_t m)
6189 struct md_page *pvh;
6191 pv_entry_t next_pv, pv;
6192 pd_entry_t oldpde, *pde;
6193 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6194 struct rwlock *lock;
6196 int md_gen, pvh_gen;
6198 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6199 ("pmap_clear_modify: page %p is not managed", m));
6200 VM_OBJECT_ASSERT_WLOCKED(m->object);
6201 KASSERT(!vm_page_xbusied(m),
6202 ("pmap_clear_modify: page %p is exclusive busied", m));
6205 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6206 * If the object containing the page is locked and the page is not
6207 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6209 if ((m->aflags & PGA_WRITEABLE) == 0)
6211 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6212 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6213 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6216 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6218 if (!PMAP_TRYLOCK(pmap)) {
6219 pvh_gen = pvh->pv_gen;
6223 if (pvh_gen != pvh->pv_gen) {
6228 PG_M = pmap_modified_bit(pmap);
6229 PG_V = pmap_valid_bit(pmap);
6230 PG_RW = pmap_rw_bit(pmap);
6232 pde = pmap_pde(pmap, va);
6234 if ((oldpde & PG_RW) != 0) {
6235 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6236 if ((oldpde & PG_W) == 0) {
6238 * Write protect the mapping to a
6239 * single page so that a subsequent
6240 * write access may repromote.
6242 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6244 pte = pmap_pde_to_pte(pde, va);
6246 if ((oldpte & PG_V) != 0) {
6247 while (!atomic_cmpset_long(pte,
6249 oldpte & ~(PG_M | PG_RW)))
6252 pmap_invalidate_page(pmap, va);
6259 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6261 if (!PMAP_TRYLOCK(pmap)) {
6262 md_gen = m->md.pv_gen;
6263 pvh_gen = pvh->pv_gen;
6267 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6272 PG_M = pmap_modified_bit(pmap);
6273 PG_RW = pmap_rw_bit(pmap);
6274 pde = pmap_pde(pmap, pv->pv_va);
6275 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6276 " a 2mpage in page %p's pv list", m));
6277 pte = pmap_pde_to_pte(pde, pv->pv_va);
6278 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6279 atomic_clear_long(pte, PG_M);
6280 pmap_invalidate_page(pmap, pv->pv_va);
6288 * Miscellaneous support routines follow
6291 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6292 static __inline void
6293 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6298 * The cache mode bits are all in the low 32-bits of the
6299 * PTE, so we can just spin on updating the low 32-bits.
6302 opte = *(u_int *)pte;
6303 npte = opte & ~mask;
6305 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6308 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6309 static __inline void
6310 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6315 * The cache mode bits are all in the low 32-bits of the
6316 * PDE, so we can just spin on updating the low 32-bits.
6319 opde = *(u_int *)pde;
6320 npde = opde & ~mask;
6322 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6326 * Map a set of physical memory pages into the kernel virtual
6327 * address space. Return a pointer to where it is mapped. This
6328 * routine is intended to be used for mapping device memory,
6332 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6334 struct pmap_preinit_mapping *ppim;
6335 vm_offset_t va, offset;
6339 offset = pa & PAGE_MASK;
6340 size = round_page(offset + size);
6341 pa = trunc_page(pa);
6343 if (!pmap_initialized) {
6345 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6346 ppim = pmap_preinit_mapping + i;
6347 if (ppim->va == 0) {
6351 ppim->va = virtual_avail;
6352 virtual_avail += size;
6358 panic("%s: too many preinit mappings", __func__);
6361 * If we have a preinit mapping, re-use it.
6363 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6364 ppim = pmap_preinit_mapping + i;
6365 if (ppim->pa == pa && ppim->sz == size &&
6367 return ((void *)(ppim->va + offset));
6370 * If the specified range of physical addresses fits within
6371 * the direct map window, use the direct map.
6373 if (pa < dmaplimit && pa + size < dmaplimit) {
6374 va = PHYS_TO_DMAP(pa);
6375 if (!pmap_change_attr(va, size, mode))
6376 return ((void *)(va + offset));
6378 va = kva_alloc(size);
6380 panic("%s: Couldn't allocate KVA", __func__);
6382 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6383 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6384 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6385 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6386 return ((void *)(va + offset));
6390 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6393 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6397 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6400 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6404 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6406 struct pmap_preinit_mapping *ppim;
6410 /* If we gave a direct map region in pmap_mapdev, do nothing */
6411 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6413 offset = va & PAGE_MASK;
6414 size = round_page(offset + size);
6415 va = trunc_page(va);
6416 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6417 ppim = pmap_preinit_mapping + i;
6418 if (ppim->va == va && ppim->sz == size) {
6419 if (pmap_initialized)
6425 if (va + size == virtual_avail)
6430 if (pmap_initialized)
6435 * Tries to demote a 1GB page mapping.
6438 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6440 pdp_entry_t newpdpe, oldpdpe;
6441 pd_entry_t *firstpde, newpde, *pde;
6442 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6446 PG_A = pmap_accessed_bit(pmap);
6447 PG_M = pmap_modified_bit(pmap);
6448 PG_V = pmap_valid_bit(pmap);
6449 PG_RW = pmap_rw_bit(pmap);
6451 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6453 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6454 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6455 if ((mpde = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6456 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6457 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6458 " in pmap %p", va, pmap);
6461 mpdepa = VM_PAGE_TO_PHYS(mpde);
6462 firstpde = (pd_entry_t *)PHYS_TO_DMAP(mpdepa);
6463 newpdpe = mpdepa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6464 KASSERT((oldpdpe & PG_A) != 0,
6465 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6466 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6467 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
6471 * Initialize the page directory page.
6473 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
6479 * Demote the mapping.
6484 * Invalidate a stale recursive mapping of the page directory page.
6486 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
6488 pmap_pdpe_demotions++;
6489 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
6490 " in pmap %p", va, pmap);
6495 * Sets the memory attribute for the specified page.
6498 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6501 m->md.pat_mode = ma;
6504 * If "m" is a normal page, update its direct mapping. This update
6505 * can be relied upon to perform any cache operations that are
6506 * required for data coherence.
6508 if ((m->flags & PG_FICTITIOUS) == 0 &&
6509 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6511 panic("memory attribute change on the direct map failed");
6515 * Changes the specified virtual address range's memory type to that given by
6516 * the parameter "mode". The specified virtual address range must be
6517 * completely contained within either the direct map or the kernel map. If
6518 * the virtual address range is contained within the kernel map, then the
6519 * memory type for each of the corresponding ranges of the direct map is also
6520 * changed. (The corresponding ranges of the direct map are those ranges that
6521 * map the same physical pages as the specified virtual address range.) These
6522 * changes to the direct map are necessary because Intel describes the
6523 * behavior of their processors as "undefined" if two or more mappings to the
6524 * same physical page have different memory types.
6526 * Returns zero if the change completed successfully, and either EINVAL or
6527 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6528 * of the virtual address range was not mapped, and ENOMEM is returned if
6529 * there was insufficient memory available to complete the change. In the
6530 * latter case, the memory type may have been changed on some part of the
6531 * virtual address range or the direct map.
6534 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6538 PMAP_LOCK(kernel_pmap);
6539 error = pmap_change_attr_locked(va, size, mode);
6540 PMAP_UNLOCK(kernel_pmap);
6545 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
6547 vm_offset_t base, offset, tmpva;
6548 vm_paddr_t pa_start, pa_end, pa_end1;
6552 int cache_bits_pte, cache_bits_pde, error;
6555 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6556 base = trunc_page(va);
6557 offset = va & PAGE_MASK;
6558 size = round_page(offset + size);
6561 * Only supported on kernel virtual addresses, including the direct
6562 * map but excluding the recursive map.
6564 if (base < DMAP_MIN_ADDRESS)
6567 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
6568 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
6572 * Pages that aren't mapped aren't supported. Also break down 2MB pages
6573 * into 4KB pages if required.
6575 for (tmpva = base; tmpva < base + size; ) {
6576 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6577 if (pdpe == NULL || *pdpe == 0)
6579 if (*pdpe & PG_PS) {
6581 * If the current 1GB page already has the required
6582 * memory type, then we need not demote this page. Just
6583 * increment tmpva to the next 1GB page frame.
6585 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
6586 tmpva = trunc_1gpage(tmpva) + NBPDP;
6591 * If the current offset aligns with a 1GB page frame
6592 * and there is at least 1GB left within the range, then
6593 * we need not break down this page into 2MB pages.
6595 if ((tmpva & PDPMASK) == 0 &&
6596 tmpva + PDPMASK < base + size) {
6600 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
6603 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6608 * If the current 2MB page already has the required
6609 * memory type, then we need not demote this page. Just
6610 * increment tmpva to the next 2MB page frame.
6612 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
6613 tmpva = trunc_2mpage(tmpva) + NBPDR;
6618 * If the current offset aligns with a 2MB page frame
6619 * and there is at least 2MB left within the range, then
6620 * we need not break down this page into 4KB pages.
6622 if ((tmpva & PDRMASK) == 0 &&
6623 tmpva + PDRMASK < base + size) {
6627 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
6630 pte = pmap_pde_to_pte(pde, tmpva);
6638 * Ok, all the pages exist, so run through them updating their
6639 * cache mode if required.
6641 pa_start = pa_end = 0;
6642 for (tmpva = base; tmpva < base + size; ) {
6643 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6644 if (*pdpe & PG_PS) {
6645 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
6646 pmap_pde_attr(pdpe, cache_bits_pde,
6650 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6651 (*pdpe & PG_PS_FRAME) < dmaplimit) {
6652 if (pa_start == pa_end) {
6653 /* Start physical address run. */
6654 pa_start = *pdpe & PG_PS_FRAME;
6655 pa_end = pa_start + NBPDP;
6656 } else if (pa_end == (*pdpe & PG_PS_FRAME))
6659 /* Run ended, update direct map. */
6660 error = pmap_change_attr_locked(
6661 PHYS_TO_DMAP(pa_start),
6662 pa_end - pa_start, mode);
6665 /* Start physical address run. */
6666 pa_start = *pdpe & PG_PS_FRAME;
6667 pa_end = pa_start + NBPDP;
6670 tmpva = trunc_1gpage(tmpva) + NBPDP;
6673 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6675 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
6676 pmap_pde_attr(pde, cache_bits_pde,
6680 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6681 (*pde & PG_PS_FRAME) < dmaplimit) {
6682 if (pa_start == pa_end) {
6683 /* Start physical address run. */
6684 pa_start = *pde & PG_PS_FRAME;
6685 pa_end = pa_start + NBPDR;
6686 } else if (pa_end == (*pde & PG_PS_FRAME))
6689 /* Run ended, update direct map. */
6690 error = pmap_change_attr_locked(
6691 PHYS_TO_DMAP(pa_start),
6692 pa_end - pa_start, mode);
6695 /* Start physical address run. */
6696 pa_start = *pde & PG_PS_FRAME;
6697 pa_end = pa_start + NBPDR;
6700 tmpva = trunc_2mpage(tmpva) + NBPDR;
6702 pte = pmap_pde_to_pte(pde, tmpva);
6703 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
6704 pmap_pte_attr(pte, cache_bits_pte,
6708 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6709 (*pte & PG_PS_FRAME) < dmaplimit) {
6710 if (pa_start == pa_end) {
6711 /* Start physical address run. */
6712 pa_start = *pte & PG_FRAME;
6713 pa_end = pa_start + PAGE_SIZE;
6714 } else if (pa_end == (*pte & PG_FRAME))
6715 pa_end += PAGE_SIZE;
6717 /* Run ended, update direct map. */
6718 error = pmap_change_attr_locked(
6719 PHYS_TO_DMAP(pa_start),
6720 pa_end - pa_start, mode);
6723 /* Start physical address run. */
6724 pa_start = *pte & PG_FRAME;
6725 pa_end = pa_start + PAGE_SIZE;
6731 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
6732 pa_end1 = MIN(pa_end, dmaplimit);
6733 if (pa_start != pa_end1)
6734 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
6735 pa_end1 - pa_start, mode);
6739 * Flush CPU caches if required to make sure any data isn't cached that
6740 * shouldn't be, etc.
6743 pmap_invalidate_range(kernel_pmap, base, tmpva);
6744 pmap_invalidate_cache_range(base, tmpva, FALSE);
6750 * Demotes any mapping within the direct map region that covers more than the
6751 * specified range of physical addresses. This range's size must be a power
6752 * of two and its starting address must be a multiple of its size. Since the
6753 * demotion does not change any attributes of the mapping, a TLB invalidation
6754 * is not mandatory. The caller may, however, request a TLB invalidation.
6757 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
6766 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
6767 KASSERT((base & (len - 1)) == 0,
6768 ("pmap_demote_DMAP: base is not a multiple of len"));
6769 if (len < NBPDP && base < dmaplimit) {
6770 va = PHYS_TO_DMAP(base);
6772 PMAP_LOCK(kernel_pmap);
6773 pdpe = pmap_pdpe(kernel_pmap, va);
6774 if ((*pdpe & X86_PG_V) == 0)
6775 panic("pmap_demote_DMAP: invalid PDPE");
6776 if ((*pdpe & PG_PS) != 0) {
6777 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
6778 panic("pmap_demote_DMAP: PDPE failed");
6782 pde = pmap_pdpe_to_pde(pdpe, va);
6783 if ((*pde & X86_PG_V) == 0)
6784 panic("pmap_demote_DMAP: invalid PDE");
6785 if ((*pde & PG_PS) != 0) {
6786 if (!pmap_demote_pde(kernel_pmap, pde, va))
6787 panic("pmap_demote_DMAP: PDE failed");
6791 if (changed && invalidate)
6792 pmap_invalidate_page(kernel_pmap, va);
6793 PMAP_UNLOCK(kernel_pmap);
6798 * perform the pmap work for mincore
6801 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
6804 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
6808 PG_A = pmap_accessed_bit(pmap);
6809 PG_M = pmap_modified_bit(pmap);
6810 PG_V = pmap_valid_bit(pmap);
6811 PG_RW = pmap_rw_bit(pmap);
6815 pdep = pmap_pde(pmap, addr);
6816 if (pdep != NULL && (*pdep & PG_V)) {
6817 if (*pdep & PG_PS) {
6819 /* Compute the physical address of the 4KB page. */
6820 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
6822 val = MINCORE_SUPER;
6824 pte = *pmap_pde_to_pte(pdep, addr);
6825 pa = pte & PG_FRAME;
6833 if ((pte & PG_V) != 0) {
6834 val |= MINCORE_INCORE;
6835 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6836 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
6837 if ((pte & PG_A) != 0)
6838 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
6840 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
6841 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
6842 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
6843 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
6844 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
6847 PA_UNLOCK_COND(*locked_pa);
6853 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
6855 uint32_t gen, new_gen, pcid_next;
6857 CRITICAL_ASSERT(curthread);
6858 gen = PCPU_GET(pcid_gen);
6859 if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN ||
6860 pmap->pm_pcids[cpuid].pm_gen == gen)
6861 return (CR3_PCID_SAVE);
6862 pcid_next = PCPU_GET(pcid_next);
6863 KASSERT(pcid_next <= PMAP_PCID_OVERMAX, ("cpu %d pcid_next %#x",
6865 if (pcid_next == PMAP_PCID_OVERMAX) {
6869 PCPU_SET(pcid_gen, new_gen);
6870 pcid_next = PMAP_PCID_KERN + 1;
6874 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
6875 pmap->pm_pcids[cpuid].pm_gen = new_gen;
6876 PCPU_SET(pcid_next, pcid_next + 1);
6881 pmap_activate_sw(struct thread *td)
6883 pmap_t oldpmap, pmap;
6884 uint64_t cached, cr3;
6888 oldpmap = PCPU_GET(curpmap);
6889 pmap = vmspace_pmap(td->td_proc->p_vmspace);
6890 if (oldpmap == pmap)
6892 cpuid = PCPU_GET(cpuid);
6894 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
6896 CPU_SET(cpuid, &pmap->pm_active);
6899 if (pmap_pcid_enabled) {
6900 cached = pmap_pcid_alloc(pmap, cpuid);
6901 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
6902 pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
6903 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
6904 pmap->pm_pcids[cpuid].pm_pcid));
6905 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
6906 pmap == kernel_pmap,
6907 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
6908 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
6911 * If the INVPCID instruction is not available,
6912 * invltlb_pcid_handler() is used for handle
6913 * invalidate_all IPI, which checks for curpmap ==
6914 * smp_tlb_pmap. Below operations sequence has a
6915 * window where %CR3 is loaded with the new pmap's
6916 * PML4 address, but curpmap value is not yet updated.
6917 * This causes invltlb IPI handler, called between the
6918 * updates, to execute as NOP, which leaves stale TLB
6921 * Note that the most typical use of
6922 * pmap_activate_sw(), from the context switch, is
6923 * immune to this race, because interrupts are
6924 * disabled (while the thread lock is owned), and IPI
6925 * happends after curpmap is updated. Protect other
6926 * callers in a similar way, by disabling interrupts
6927 * around the %cr3 register reload and curpmap
6931 rflags = intr_disable();
6933 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
6934 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
6937 PCPU_INC(pm_save_cnt);
6939 PCPU_SET(curpmap, pmap);
6941 intr_restore(rflags);
6942 } else if (cr3 != pmap->pm_cr3) {
6943 load_cr3(pmap->pm_cr3);
6944 PCPU_SET(curpmap, pmap);
6947 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
6949 CPU_CLR(cpuid, &oldpmap->pm_active);
6954 pmap_activate(struct thread *td)
6958 pmap_activate_sw(td);
6963 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
6968 * Increase the starting virtual address of the given mapping if a
6969 * different alignment might result in more superpage mappings.
6972 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
6973 vm_offset_t *addr, vm_size_t size)
6975 vm_offset_t superpage_offset;
6979 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
6980 offset += ptoa(object->pg_color);
6981 superpage_offset = offset & PDRMASK;
6982 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
6983 (*addr & PDRMASK) == superpage_offset)
6985 if ((*addr & PDRMASK) < superpage_offset)
6986 *addr = (*addr & ~PDRMASK) + superpage_offset;
6988 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
6992 static unsigned long num_dirty_emulations;
6993 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
6994 &num_dirty_emulations, 0, NULL);
6996 static unsigned long num_accessed_emulations;
6997 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
6998 &num_accessed_emulations, 0, NULL);
7000 static unsigned long num_superpage_accessed_emulations;
7001 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7002 &num_superpage_accessed_emulations, 0, NULL);
7004 static unsigned long ad_emulation_superpage_promotions;
7005 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7006 &ad_emulation_superpage_promotions, 0, NULL);
7007 #endif /* INVARIANTS */
7010 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7013 struct rwlock *lock;
7016 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7018 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7019 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7021 if (!pmap_emulate_ad_bits(pmap))
7024 PG_A = pmap_accessed_bit(pmap);
7025 PG_M = pmap_modified_bit(pmap);
7026 PG_V = pmap_valid_bit(pmap);
7027 PG_RW = pmap_rw_bit(pmap);
7033 pde = pmap_pde(pmap, va);
7034 if (pde == NULL || (*pde & PG_V) == 0)
7037 if ((*pde & PG_PS) != 0) {
7038 if (ftype == VM_PROT_READ) {
7040 atomic_add_long(&num_superpage_accessed_emulations, 1);
7048 pte = pmap_pde_to_pte(pde, va);
7049 if ((*pte & PG_V) == 0)
7052 if (ftype == VM_PROT_WRITE) {
7053 if ((*pte & PG_RW) == 0)
7056 * Set the modified and accessed bits simultaneously.
7058 * Intel EPT PTEs that do software emulation of A/D bits map
7059 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7060 * An EPT misconfiguration is triggered if the PTE is writable
7061 * but not readable (WR=10). This is avoided by setting PG_A
7062 * and PG_M simultaneously.
7064 *pte |= PG_M | PG_A;
7069 /* try to promote the mapping */
7070 if (va < VM_MAXUSER_ADDRESS)
7071 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7075 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7077 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7078 pmap_ps_enabled(pmap) &&
7079 (m->flags & PG_FICTITIOUS) == 0 &&
7080 vm_reserv_level_iffullpop(m) == 0) {
7081 pmap_promote_pde(pmap, pde, va, &lock);
7083 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7087 if (ftype == VM_PROT_WRITE)
7088 atomic_add_long(&num_dirty_emulations, 1);
7090 atomic_add_long(&num_accessed_emulations, 1);
7092 rv = 0; /* success */
7101 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7106 pt_entry_t *pte, PG_V;
7110 PG_V = pmap_valid_bit(pmap);
7113 pml4 = pmap_pml4e(pmap, va);
7115 if ((*pml4 & PG_V) == 0)
7118 pdp = pmap_pml4e_to_pdpe(pml4, va);
7120 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7123 pde = pmap_pdpe_to_pde(pdp, va);
7125 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7128 pte = pmap_pde_to_pte(pde, va);
7137 * Get the kernel virtual address of a set of physical pages. If there are
7138 * physical addresses not covered by the DMAP perform a transient mapping
7139 * that will be removed when calling pmap_unmap_io_transient.
7141 * \param page The pages the caller wishes to obtain the virtual
7142 * address on the kernel memory map.
7143 * \param vaddr On return contains the kernel virtual memory address
7144 * of the pages passed in the page parameter.
7145 * \param count Number of pages passed in.
7146 * \param can_fault TRUE if the thread using the mapped pages can take
7147 * page faults, FALSE otherwise.
7149 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7150 * finished or FALSE otherwise.
7154 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7155 boolean_t can_fault)
7158 boolean_t needs_mapping;
7160 int cache_bits, error, i;
7163 * Allocate any KVA space that we need, this is done in a separate
7164 * loop to prevent calling vmem_alloc while pinned.
7166 needs_mapping = FALSE;
7167 for (i = 0; i < count; i++) {
7168 paddr = VM_PAGE_TO_PHYS(page[i]);
7169 if (__predict_false(paddr >= dmaplimit)) {
7170 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7171 M_BESTFIT | M_WAITOK, &vaddr[i]);
7172 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7173 needs_mapping = TRUE;
7175 vaddr[i] = PHYS_TO_DMAP(paddr);
7179 /* Exit early if everything is covered by the DMAP */
7184 * NB: The sequence of updating a page table followed by accesses
7185 * to the corresponding pages used in the !DMAP case is subject to
7186 * the situation described in the "AMD64 Architecture Programmer's
7187 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7188 * Coherency Considerations". Therefore, issuing the INVLPG right
7189 * after modifying the PTE bits is crucial.
7193 for (i = 0; i < count; i++) {
7194 paddr = VM_PAGE_TO_PHYS(page[i]);
7195 if (paddr >= dmaplimit) {
7198 * Slow path, since we can get page faults
7199 * while mappings are active don't pin the
7200 * thread to the CPU and instead add a global
7201 * mapping visible to all CPUs.
7203 pmap_qenter(vaddr[i], &page[i], 1);
7205 pte = vtopte(vaddr[i]);
7206 cache_bits = pmap_cache_bits(kernel_pmap,
7207 page[i]->md.pat_mode, 0);
7208 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7215 return (needs_mapping);
7219 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7220 boolean_t can_fault)
7227 for (i = 0; i < count; i++) {
7228 paddr = VM_PAGE_TO_PHYS(page[i]);
7229 if (paddr >= dmaplimit) {
7231 pmap_qremove(vaddr[i], 1);
7232 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7238 pmap_quick_enter_page(vm_page_t m)
7242 paddr = VM_PAGE_TO_PHYS(m);
7243 if (paddr < dmaplimit)
7244 return (PHYS_TO_DMAP(paddr));
7245 mtx_lock_spin(&qframe_mtx);
7246 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7247 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7248 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7253 pmap_quick_remove_page(vm_offset_t addr)
7258 pte_store(vtopte(qframe), 0);
7260 mtx_unlock_spin(&qframe_mtx);
7263 #include "opt_ddb.h"
7265 #include <ddb/ddb.h>
7267 DB_SHOW_COMMAND(pte, pmap_print_pte)
7273 pt_entry_t *pte, PG_V;
7277 va = (vm_offset_t)addr;
7278 pmap = PCPU_GET(curpmap); /* XXX */
7280 db_printf("show pte addr\n");
7283 PG_V = pmap_valid_bit(pmap);
7284 pml4 = pmap_pml4e(pmap, va);
7285 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
7286 if ((*pml4 & PG_V) == 0) {
7290 pdp = pmap_pml4e_to_pdpe(pml4, va);
7291 db_printf(" pdpe %#016lx", *pdp);
7292 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
7296 pde = pmap_pdpe_to_pde(pdp, va);
7297 db_printf(" pde %#016lx", *pde);
7298 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
7302 pte = pmap_pde_to_pte(pde, va);
7303 db_printf(" pte %#016lx\n", *pte);
7306 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
7311 a = (vm_paddr_t)addr;
7312 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
7314 db_printf("show phys2dmap addr\n");