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 #if !defined(DIAGNOSTIC)
278 #ifdef __GNUC_GNU_INLINE__
279 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
281 #define PMAP_INLINE extern inline
288 #define PV_STAT(x) do { x ; } while (0)
290 #define PV_STAT(x) do { } while (0)
293 #define pa_index(pa) ((pa) >> PDRSHIFT)
294 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
296 #define NPV_LIST_LOCKS MAXCPU
298 #define PHYS_TO_PV_LIST_LOCK(pa) \
299 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
301 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
302 struct rwlock **_lockp = (lockp); \
303 struct rwlock *_new_lock; \
305 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
306 if (_new_lock != *_lockp) { \
307 if (*_lockp != NULL) \
308 rw_wunlock(*_lockp); \
309 *_lockp = _new_lock; \
314 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
315 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
317 #define RELEASE_PV_LIST_LOCK(lockp) do { \
318 struct rwlock **_lockp = (lockp); \
320 if (*_lockp != NULL) { \
321 rw_wunlock(*_lockp); \
326 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
327 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
329 struct pmap kernel_pmap_store;
331 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
332 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
335 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
336 "Number of kernel page table pages allocated on bootup");
339 vm_paddr_t dmaplimit;
340 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
343 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
345 static int pat_works = 1;
346 SYSCTL_INT(_vm_pmap, OID_AUTO, pat_works, CTLFLAG_RD, &pat_works, 1,
347 "Is page attribute table fully functional?");
349 static int pg_ps_enabled = 1;
350 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
351 &pg_ps_enabled, 0, "Are large page mappings enabled?");
353 #define PAT_INDEX_SIZE 8
354 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
356 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
357 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
358 u_int64_t KPDPphys; /* phys addr of kernel level 3 */
359 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
361 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
362 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
363 static int ndmpdpphys; /* number of DMPDPphys pages */
366 * pmap_mapdev support pre initialization (i.e. console)
368 #define PMAP_PREINIT_MAPPING_COUNT 8
369 static struct pmap_preinit_mapping {
374 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
375 static int pmap_initialized;
378 * Data for the pv entry allocation mechanism.
379 * Updates to pv_invl_gen are protected by the pv_list_locks[]
380 * elements, but reads are not.
382 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
383 static struct mtx pv_chunks_mutex;
384 static struct rwlock pv_list_locks[NPV_LIST_LOCKS];
385 static u_long pv_invl_gen[NPV_LIST_LOCKS];
386 static struct md_page *pv_table;
387 static struct md_page pv_dummy;
390 * All those kernel PT submaps that BSD is so fond of
392 pt_entry_t *CMAP1 = NULL;
394 static vm_offset_t qframe = 0;
395 static struct mtx qframe_mtx;
397 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
399 int pmap_pcid_enabled = 1;
400 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
401 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
402 int invpcid_works = 0;
403 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
404 "Is the invpcid instruction available ?");
407 pmap_pcid_save_cnt_proc(SYSCTL_HANDLER_ARGS)
414 res += cpuid_to_pcpu[i]->pc_pm_save_cnt;
416 return (sysctl_handle_64(oidp, &res, 0, req));
418 SYSCTL_PROC(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLTYPE_U64 | CTLFLAG_RW |
419 CTLFLAG_MPSAFE, NULL, 0, pmap_pcid_save_cnt_proc, "QU",
420 "Count of saved TLB context on switch");
422 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
423 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
424 static struct mtx invl_gen_mtx;
425 static u_long pmap_invl_gen = 0;
426 /* Fake lock object to satisfy turnstiles interface. */
427 static struct lock_object invl_gen_ts = {
435 return (curthread->td_md.md_invl_gen.gen == 0);
438 #define PMAP_ASSERT_NOT_IN_DI() \
439 KASSERT(pmap_not_in_di(), ("DI already started"))
442 * Start a new Delayed Invalidation (DI) block of code, executed by
443 * the current thread. Within a DI block, the current thread may
444 * destroy both the page table and PV list entries for a mapping and
445 * then release the corresponding PV list lock before ensuring that
446 * the mapping is flushed from the TLBs of any processors with the
450 pmap_delayed_invl_started(void)
452 struct pmap_invl_gen *invl_gen;
455 invl_gen = &curthread->td_md.md_invl_gen;
456 PMAP_ASSERT_NOT_IN_DI();
457 mtx_lock(&invl_gen_mtx);
458 if (LIST_EMPTY(&pmap_invl_gen_tracker))
459 currgen = pmap_invl_gen;
461 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
462 invl_gen->gen = currgen + 1;
463 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
464 mtx_unlock(&invl_gen_mtx);
468 * Finish the DI block, previously started by the current thread. All
469 * required TLB flushes for the pages marked by
470 * pmap_delayed_invl_page() must be finished before this function is
473 * This function works by bumping the global DI generation number to
474 * the generation number of the current thread's DI, unless there is a
475 * pending DI that started earlier. In the latter case, bumping the
476 * global DI generation number would incorrectly signal that the
477 * earlier DI had finished. Instead, this function bumps the earlier
478 * DI's generation number to match the generation number of the
479 * current thread's DI.
482 pmap_delayed_invl_finished(void)
484 struct pmap_invl_gen *invl_gen, *next;
485 struct turnstile *ts;
487 invl_gen = &curthread->td_md.md_invl_gen;
488 KASSERT(invl_gen->gen != 0, ("missed invl_started"));
489 mtx_lock(&invl_gen_mtx);
490 next = LIST_NEXT(invl_gen, link);
492 turnstile_chain_lock(&invl_gen_ts);
493 ts = turnstile_lookup(&invl_gen_ts);
494 pmap_invl_gen = invl_gen->gen;
496 turnstile_broadcast(ts, TS_SHARED_QUEUE);
497 turnstile_unpend(ts, TS_SHARED_LOCK);
499 turnstile_chain_unlock(&invl_gen_ts);
501 next->gen = invl_gen->gen;
503 LIST_REMOVE(invl_gen, link);
504 mtx_unlock(&invl_gen_mtx);
509 static long invl_wait;
510 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
511 "Number of times DI invalidation blocked pmap_remove_all/write");
515 pmap_delayed_invl_genp(vm_page_t m)
518 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
522 * Ensure that all currently executing DI blocks, that need to flush
523 * TLB for the given page m, actually flushed the TLB at the time the
524 * function returned. If the page m has an empty PV list and we call
525 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
526 * valid mapping for the page m in either its page table or TLB.
528 * This function works by blocking until the global DI generation
529 * number catches up with the generation number associated with the
530 * given page m and its PV list. Since this function's callers
531 * typically own an object lock and sometimes own a page lock, it
532 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
536 pmap_delayed_invl_wait(vm_page_t m)
538 struct turnstile *ts;
541 bool accounted = false;
544 m_gen = pmap_delayed_invl_genp(m);
545 while (*m_gen > pmap_invl_gen) {
548 atomic_add_long(&invl_wait, 1);
552 ts = turnstile_trywait(&invl_gen_ts);
553 if (*m_gen > pmap_invl_gen)
554 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
556 turnstile_cancel(ts);
561 * Mark the page m's PV list as participating in the current thread's
562 * DI block. Any threads concurrently using m's PV list to remove or
563 * restrict all mappings to m will wait for the current thread's DI
564 * block to complete before proceeding.
566 * The function works by setting the DI generation number for m's PV
567 * list to at least the DI generation number of the current thread.
568 * This forces a caller of pmap_delayed_invl_wait() to block until
569 * current thread calls pmap_delayed_invl_finished().
572 pmap_delayed_invl_page(vm_page_t m)
576 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
577 gen = curthread->td_md.md_invl_gen.gen;
580 m_gen = pmap_delayed_invl_genp(m);
588 static caddr_t crashdumpmap;
591 * Internal flags for pmap_enter()'s helper functions.
593 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
594 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
596 static void free_pv_chunk(struct pv_chunk *pc);
597 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
598 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
599 static int popcnt_pc_map_pq(uint64_t *map);
600 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
601 static void reserve_pv_entries(pmap_t pmap, int needed,
602 struct rwlock **lockp);
603 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
604 struct rwlock **lockp);
605 static bool pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
606 u_int flags, struct rwlock **lockp);
607 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
608 struct rwlock **lockp);
609 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
610 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
613 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode);
614 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
615 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
616 vm_offset_t va, struct rwlock **lockp);
617 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
619 static bool pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
620 vm_prot_t prot, struct rwlock **lockp);
621 static int pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
622 u_int flags, vm_page_t m, struct rwlock **lockp);
623 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
624 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
625 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
626 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
627 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
629 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
630 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask);
631 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
632 struct rwlock **lockp);
633 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
635 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
636 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
637 struct spglist *free, struct rwlock **lockp);
638 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
639 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
640 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
641 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
642 struct spglist *free);
643 static bool pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
644 pd_entry_t *pde, struct spglist *free,
645 struct rwlock **lockp);
646 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
647 vm_page_t m, struct rwlock **lockp);
648 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
650 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
652 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
653 struct rwlock **lockp);
654 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
655 struct rwlock **lockp);
656 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
657 struct rwlock **lockp);
659 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
660 struct spglist *free);
661 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
662 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
665 * Move the kernel virtual free pointer to the next
666 * 2MB. This is used to help improve performance
667 * by using a large (2MB) page for much of the kernel
668 * (.text, .data, .bss)
671 pmap_kmem_choose(vm_offset_t addr)
673 vm_offset_t newaddr = addr;
675 newaddr = roundup2(addr, NBPDR);
679 /********************/
680 /* Inline functions */
681 /********************/
683 /* Return a non-clipped PD index for a given VA */
684 static __inline vm_pindex_t
685 pmap_pde_pindex(vm_offset_t va)
687 return (va >> PDRSHIFT);
691 /* Return a pointer to the PML4 slot that corresponds to a VA */
692 static __inline pml4_entry_t *
693 pmap_pml4e(pmap_t pmap, vm_offset_t va)
696 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
699 /* Return a pointer to the PDP slot that corresponds to a VA */
700 static __inline pdp_entry_t *
701 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
705 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
706 return (&pdpe[pmap_pdpe_index(va)]);
709 /* Return a pointer to the PDP slot that corresponds to a VA */
710 static __inline pdp_entry_t *
711 pmap_pdpe(pmap_t pmap, vm_offset_t va)
716 PG_V = pmap_valid_bit(pmap);
717 pml4e = pmap_pml4e(pmap, va);
718 if ((*pml4e & PG_V) == 0)
720 return (pmap_pml4e_to_pdpe(pml4e, va));
723 /* Return a pointer to the PD slot that corresponds to a VA */
724 static __inline pd_entry_t *
725 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
729 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
730 return (&pde[pmap_pde_index(va)]);
733 /* Return a pointer to the PD slot that corresponds to a VA */
734 static __inline pd_entry_t *
735 pmap_pde(pmap_t pmap, vm_offset_t va)
740 PG_V = pmap_valid_bit(pmap);
741 pdpe = pmap_pdpe(pmap, va);
742 if (pdpe == NULL || (*pdpe & PG_V) == 0)
744 return (pmap_pdpe_to_pde(pdpe, va));
747 /* Return a pointer to the PT slot that corresponds to a VA */
748 static __inline pt_entry_t *
749 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
753 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
754 return (&pte[pmap_pte_index(va)]);
757 /* Return a pointer to the PT slot that corresponds to a VA */
758 static __inline pt_entry_t *
759 pmap_pte(pmap_t pmap, vm_offset_t va)
764 PG_V = pmap_valid_bit(pmap);
765 pde = pmap_pde(pmap, va);
766 if (pde == NULL || (*pde & PG_V) == 0)
768 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
769 return ((pt_entry_t *)pde);
770 return (pmap_pde_to_pte(pde, va));
774 pmap_resident_count_inc(pmap_t pmap, int count)
777 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
778 pmap->pm_stats.resident_count += count;
782 pmap_resident_count_dec(pmap_t pmap, int count)
785 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
786 KASSERT(pmap->pm_stats.resident_count >= count,
787 ("pmap %p resident count underflow %ld %d", pmap,
788 pmap->pm_stats.resident_count, count));
789 pmap->pm_stats.resident_count -= count;
792 PMAP_INLINE pt_entry_t *
793 vtopte(vm_offset_t va)
795 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
797 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
799 return (PTmap + ((va >> PAGE_SHIFT) & mask));
802 static __inline pd_entry_t *
803 vtopde(vm_offset_t va)
805 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
807 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
809 return (PDmap + ((va >> PDRSHIFT) & mask));
813 allocpages(vm_paddr_t *firstaddr, int n)
818 bzero((void *)ret, n * PAGE_SIZE);
819 *firstaddr += n * PAGE_SIZE;
823 CTASSERT(powerof2(NDMPML4E));
825 /* number of kernel PDP slots */
826 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
829 nkpt_init(vm_paddr_t addr)
836 pt_pages = howmany(addr, 1 << PDRSHIFT);
837 pt_pages += NKPDPE(pt_pages);
840 * Add some slop beyond the bare minimum required for bootstrapping
843 * This is quite important when allocating KVA for kernel modules.
844 * The modules are required to be linked in the negative 2GB of
845 * the address space. If we run out of KVA in this region then
846 * pmap_growkernel() will need to allocate page table pages to map
847 * the entire 512GB of KVA space which is an unnecessary tax on
850 * Secondly, device memory mapped as part of setting up the low-
851 * level console(s) is taken from KVA, starting at virtual_avail.
852 * This is because cninit() is called after pmap_bootstrap() but
853 * before vm_init() and pmap_init(). 20MB for a frame buffer is
856 pt_pages += 32; /* 64MB additional slop. */
862 create_pagetables(vm_paddr_t *firstaddr)
864 int i, j, ndm1g, nkpdpe;
870 /* Allocate page table pages for the direct map */
871 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
872 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
874 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
875 if (ndmpdpphys > NDMPML4E) {
877 * Each NDMPML4E allows 512 GB, so limit to that,
878 * and then readjust ndmpdp and ndmpdpphys.
880 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
881 Maxmem = atop(NDMPML4E * NBPML4);
882 ndmpdpphys = NDMPML4E;
883 ndmpdp = NDMPML4E * NPDEPG;
885 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
887 if ((amd_feature & AMDID_PAGE1GB) != 0)
888 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
890 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
891 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
894 KPML4phys = allocpages(firstaddr, 1);
895 KPDPphys = allocpages(firstaddr, NKPML4E);
898 * Allocate the initial number of kernel page table pages required to
899 * bootstrap. We defer this until after all memory-size dependent
900 * allocations are done (e.g. direct map), so that we don't have to
901 * build in too much slop in our estimate.
903 * Note that when NKPML4E > 1, we have an empty page underneath
904 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
905 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
907 nkpt_init(*firstaddr);
908 nkpdpe = NKPDPE(nkpt);
910 KPTphys = allocpages(firstaddr, nkpt);
911 KPDphys = allocpages(firstaddr, nkpdpe);
913 /* Fill in the underlying page table pages */
914 /* Nominally read-only (but really R/W) from zero to physfree */
915 /* XXX not fully used, underneath 2M pages */
916 pt_p = (pt_entry_t *)KPTphys;
917 for (i = 0; ptoa(i) < *firstaddr; i++)
918 pt_p[i] = ptoa(i) | X86_PG_RW | X86_PG_V | X86_PG_G;
920 /* Now map the page tables at their location within PTmap */
921 pd_p = (pd_entry_t *)KPDphys;
922 for (i = 0; i < nkpt; i++)
923 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
925 /* Map from zero to end of allocations under 2M pages */
926 /* This replaces some of the KPTphys entries above */
927 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
928 pd_p[i] = (i << PDRSHIFT) | X86_PG_RW | X86_PG_V | PG_PS |
931 /* And connect up the PD to the PDP (leaving room for L4 pages) */
932 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
933 for (i = 0; i < nkpdpe; i++)
934 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
938 * Now, set up the direct map region using 2MB and/or 1GB pages. If
939 * the end of physical memory is not aligned to a 1GB page boundary,
940 * then the residual physical memory is mapped with 2MB pages. Later,
941 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
942 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
943 * that are partially used.
945 pd_p = (pd_entry_t *)DMPDphys;
946 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
947 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
948 /* Preset PG_M and PG_A because demotion expects it. */
949 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | X86_PG_G |
950 X86_PG_M | X86_PG_A | pg_nx;
952 pdp_p = (pdp_entry_t *)DMPDPphys;
953 for (i = 0; i < ndm1g; i++) {
954 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
955 /* Preset PG_M and PG_A because demotion expects it. */
956 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | X86_PG_G |
957 X86_PG_M | X86_PG_A | pg_nx;
959 for (j = 0; i < ndmpdp; i++, j++) {
960 pdp_p[i] = DMPDphys + ptoa(j);
961 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_U;
964 /* And recursively map PML4 to itself in order to get PTmap */
965 p4_p = (pml4_entry_t *)KPML4phys;
966 p4_p[PML4PML4I] = KPML4phys;
967 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | PG_U;
969 /* Connect the Direct Map slot(s) up to the PML4. */
970 for (i = 0; i < ndmpdpphys; i++) {
971 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
972 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | PG_U;
975 /* Connect the KVA slots up to the PML4 */
976 for (i = 0; i < NKPML4E; i++) {
977 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
978 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V | PG_U;
983 * Bootstrap the system enough to run with virtual memory.
985 * On amd64 this is called after mapping has already been enabled
986 * and just syncs the pmap module with what has already been done.
987 * [We can't call it easily with mapping off since the kernel is not
988 * mapped with PA == VA, hence we would have to relocate every address
989 * from the linked base (virtual) address "KERNBASE" to the actual
990 * (physical) address starting relative to 0]
993 pmap_bootstrap(vm_paddr_t *firstaddr)
1000 * Create an initial set of page tables to run the kernel in.
1002 create_pagetables(firstaddr);
1005 * Add a physical memory segment (vm_phys_seg) corresponding to the
1006 * preallocated kernel page table pages so that vm_page structures
1007 * representing these pages will be created. The vm_page structures
1008 * are required for promotion of the corresponding kernel virtual
1009 * addresses to superpage mappings.
1011 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1013 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
1014 virtual_avail = pmap_kmem_choose(virtual_avail);
1016 virtual_end = VM_MAX_KERNEL_ADDRESS;
1019 /* XXX do %cr0 as well */
1020 load_cr4(rcr4() | CR4_PGE);
1021 load_cr3(KPML4phys);
1022 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1023 load_cr4(rcr4() | CR4_SMEP);
1026 * Initialize the kernel pmap (which is statically allocated).
1028 PMAP_LOCK_INIT(kernel_pmap);
1029 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1030 kernel_pmap->pm_cr3 = KPML4phys;
1031 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1032 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1033 kernel_pmap->pm_flags = pmap_flags;
1036 * Initialize the TLB invalidations generation number lock.
1038 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1041 * Reserve some special page table entries/VA space for temporary
1044 #define SYSMAP(c, p, v, n) \
1045 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1051 * Crashdump maps. The first page is reused as CMAP1 for the
1054 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1055 CADDR1 = crashdumpmap;
1060 * Initialize the PAT MSR.
1061 * pmap_init_pat() clears and sets CR4_PGE, which, as a
1062 * side-effect, invalidates stale PG_G TLB entries that might
1063 * have been created in our pre-boot environment.
1067 /* Initialize TLB Context Id. */
1068 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1069 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1070 /* Check for INVPCID support */
1071 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1073 for (i = 0; i < MAXCPU; i++) {
1074 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1075 kernel_pmap->pm_pcids[i].pm_gen = 1;
1077 PCPU_SET(pcid_next, PMAP_PCID_KERN + 1);
1078 PCPU_SET(pcid_gen, 1);
1080 * pcpu area for APs is zeroed during AP startup.
1081 * pc_pcid_next and pc_pcid_gen are initialized by AP
1082 * during pcpu setup.
1084 load_cr4(rcr4() | CR4_PCIDE);
1086 pmap_pcid_enabled = 0;
1091 * Setup the PAT MSR.
1096 int pat_table[PAT_INDEX_SIZE];
1101 /* Bail if this CPU doesn't implement PAT. */
1102 if ((cpu_feature & CPUID_PAT) == 0)
1105 /* Set default PAT index table. */
1106 for (i = 0; i < PAT_INDEX_SIZE; i++)
1108 pat_table[PAT_WRITE_BACK] = 0;
1109 pat_table[PAT_WRITE_THROUGH] = 1;
1110 pat_table[PAT_UNCACHEABLE] = 3;
1111 pat_table[PAT_WRITE_COMBINING] = 3;
1112 pat_table[PAT_WRITE_PROTECTED] = 3;
1113 pat_table[PAT_UNCACHED] = 3;
1115 /* Initialize default PAT entries. */
1116 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1117 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1118 PAT_VALUE(2, PAT_UNCACHED) |
1119 PAT_VALUE(3, PAT_UNCACHEABLE) |
1120 PAT_VALUE(4, PAT_WRITE_BACK) |
1121 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1122 PAT_VALUE(6, PAT_UNCACHED) |
1123 PAT_VALUE(7, PAT_UNCACHEABLE);
1127 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1128 * Program 5 and 6 as WP and WC.
1129 * Leave 4 and 7 as WB and UC.
1131 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1132 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1133 PAT_VALUE(6, PAT_WRITE_COMBINING);
1134 pat_table[PAT_UNCACHED] = 2;
1135 pat_table[PAT_WRITE_PROTECTED] = 5;
1136 pat_table[PAT_WRITE_COMBINING] = 6;
1139 * Just replace PAT Index 2 with WC instead of UC-.
1141 pat_msr &= ~PAT_MASK(2);
1142 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1143 pat_table[PAT_WRITE_COMBINING] = 2;
1148 load_cr4(cr4 & ~CR4_PGE);
1150 /* Disable caches (CD = 1, NW = 0). */
1152 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1154 /* Flushes caches and TLBs. */
1158 /* Update PAT and index table. */
1159 wrmsr(MSR_PAT, pat_msr);
1160 for (i = 0; i < PAT_INDEX_SIZE; i++)
1161 pat_index[i] = pat_table[i];
1163 /* Flush caches and TLBs again. */
1167 /* Restore caches and PGE. */
1173 * Initialize a vm_page's machine-dependent fields.
1176 pmap_page_init(vm_page_t m)
1179 TAILQ_INIT(&m->md.pv_list);
1180 m->md.pat_mode = PAT_WRITE_BACK;
1184 * Initialize the pmap module.
1185 * Called by vm_init, to initialize any structures that the pmap
1186 * system needs to map virtual memory.
1191 struct pmap_preinit_mapping *ppim;
1194 int error, i, pv_npg;
1197 * Initialize the vm page array entries for the kernel pmap's
1200 for (i = 0; i < nkpt; i++) {
1201 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1202 KASSERT(mpte >= vm_page_array &&
1203 mpte < &vm_page_array[vm_page_array_size],
1204 ("pmap_init: page table page is out of range"));
1205 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1206 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1210 * If the kernel is running on a virtual machine, then it must assume
1211 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1212 * be prepared for the hypervisor changing the vendor and family that
1213 * are reported by CPUID. Consequently, the workaround for AMD Family
1214 * 10h Erratum 383 is enabled if the processor's feature set does not
1215 * include at least one feature that is only supported by older Intel
1216 * or newer AMD processors.
1218 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1219 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1220 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1222 workaround_erratum383 = 1;
1225 * Are large page mappings enabled?
1227 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1228 if (pg_ps_enabled) {
1229 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1230 ("pmap_init: can't assign to pagesizes[1]"));
1231 pagesizes[1] = NBPDR;
1235 * Initialize the pv chunk list mutex.
1237 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1240 * Initialize the pool of pv list locks.
1242 for (i = 0; i < NPV_LIST_LOCKS; i++)
1243 rw_init(&pv_list_locks[i], "pmap pv list");
1246 * Calculate the size of the pv head table for superpages.
1248 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1251 * Allocate memory for the pv head table for superpages.
1253 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1255 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1257 for (i = 0; i < pv_npg; i++)
1258 TAILQ_INIT(&pv_table[i].pv_list);
1259 TAILQ_INIT(&pv_dummy.pv_list);
1261 pmap_initialized = 1;
1262 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1263 ppim = pmap_preinit_mapping + i;
1266 /* Make the direct map consistent */
1267 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1268 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1269 ppim->sz, ppim->mode);
1273 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1274 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1277 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1278 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1279 (vmem_addr_t *)&qframe);
1281 panic("qframe allocation failed");
1284 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1285 "2MB page mapping counters");
1287 static u_long pmap_pde_demotions;
1288 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1289 &pmap_pde_demotions, 0, "2MB page demotions");
1291 static u_long pmap_pde_mappings;
1292 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1293 &pmap_pde_mappings, 0, "2MB page mappings");
1295 static u_long pmap_pde_p_failures;
1296 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1297 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1299 static u_long pmap_pde_promotions;
1300 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1301 &pmap_pde_promotions, 0, "2MB page promotions");
1303 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1304 "1GB page mapping counters");
1306 static u_long pmap_pdpe_demotions;
1307 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1308 &pmap_pdpe_demotions, 0, "1GB page demotions");
1310 /***************************************************
1311 * Low level helper routines.....
1312 ***************************************************/
1315 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1317 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1319 switch (pmap->pm_type) {
1322 /* Verify that both PAT bits are not set at the same time */
1323 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1324 ("Invalid PAT bits in entry %#lx", entry));
1326 /* Swap the PAT bits if one of them is set */
1327 if ((entry & x86_pat_bits) != 0)
1328 entry ^= x86_pat_bits;
1332 * Nothing to do - the memory attributes are represented
1333 * the same way for regular pages and superpages.
1337 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1344 * Determine the appropriate bits to set in a PTE or PDE for a specified
1348 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1350 int cache_bits, pat_flag, pat_idx;
1352 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1353 panic("Unknown caching mode %d\n", mode);
1355 switch (pmap->pm_type) {
1358 /* The PAT bit is different for PTE's and PDE's. */
1359 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1361 /* Map the caching mode to a PAT index. */
1362 pat_idx = pat_index[mode];
1364 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1367 cache_bits |= pat_flag;
1369 cache_bits |= PG_NC_PCD;
1371 cache_bits |= PG_NC_PWT;
1375 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1379 panic("unsupported pmap type %d", pmap->pm_type);
1382 return (cache_bits);
1386 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1390 switch (pmap->pm_type) {
1393 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1396 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1399 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1406 pmap_ps_enabled(pmap_t pmap)
1409 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1413 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1416 switch (pmap->pm_type) {
1423 * This is a little bogus since the generation number is
1424 * supposed to be bumped up when a region of the address
1425 * space is invalidated in the page tables.
1427 * In this case the old PDE entry is valid but yet we want
1428 * to make sure that any mappings using the old entry are
1429 * invalidated in the TLB.
1431 * The reason this works as expected is because we rendezvous
1432 * "all" host cpus and force any vcpu context to exit as a
1435 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1438 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1440 pde_store(pde, newpde);
1444 * After changing the page size for the specified virtual address in the page
1445 * table, flush the corresponding entries from the processor's TLB. Only the
1446 * calling processor's TLB is affected.
1448 * The calling thread must be pinned to a processor.
1451 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1455 if (pmap_type_guest(pmap))
1458 KASSERT(pmap->pm_type == PT_X86,
1459 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1461 PG_G = pmap_global_bit(pmap);
1463 if ((newpde & PG_PS) == 0)
1464 /* Demotion: flush a specific 2MB page mapping. */
1466 else if ((newpde & PG_G) == 0)
1468 * Promotion: flush every 4KB page mapping from the TLB
1469 * because there are too many to flush individually.
1474 * Promotion: flush every 4KB page mapping from the TLB,
1475 * including any global (PG_G) mappings.
1483 * For SMP, these functions have to use the IPI mechanism for coherence.
1485 * N.B.: Before calling any of the following TLB invalidation functions,
1486 * the calling processor must ensure that all stores updating a non-
1487 * kernel page table are globally performed. Otherwise, another
1488 * processor could cache an old, pre-update entry without being
1489 * invalidated. This can happen one of two ways: (1) The pmap becomes
1490 * active on another processor after its pm_active field is checked by
1491 * one of the following functions but before a store updating the page
1492 * table is globally performed. (2) The pmap becomes active on another
1493 * processor before its pm_active field is checked but due to
1494 * speculative loads one of the following functions stills reads the
1495 * pmap as inactive on the other processor.
1497 * The kernel page table is exempt because its pm_active field is
1498 * immutable. The kernel page table is always active on every
1503 * Interrupt the cpus that are executing in the guest context.
1504 * This will force the vcpu to exit and the cached EPT mappings
1505 * will be invalidated by the host before the next vmresume.
1507 static __inline void
1508 pmap_invalidate_ept(pmap_t pmap)
1513 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1514 ("pmap_invalidate_ept: absurd pm_active"));
1517 * The TLB mappings associated with a vcpu context are not
1518 * flushed each time a different vcpu is chosen to execute.
1520 * This is in contrast with a process's vtop mappings that
1521 * are flushed from the TLB on each context switch.
1523 * Therefore we need to do more than just a TLB shootdown on
1524 * the active cpus in 'pmap->pm_active'. To do this we keep
1525 * track of the number of invalidations performed on this pmap.
1527 * Each vcpu keeps a cache of this counter and compares it
1528 * just before a vmresume. If the counter is out-of-date an
1529 * invept will be done to flush stale mappings from the TLB.
1531 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1534 * Force the vcpu to exit and trap back into the hypervisor.
1536 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1537 ipi_selected(pmap->pm_active, ipinum);
1542 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1547 if (pmap_type_guest(pmap)) {
1548 pmap_invalidate_ept(pmap);
1552 KASSERT(pmap->pm_type == PT_X86,
1553 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1556 if (pmap == kernel_pmap) {
1560 cpuid = PCPU_GET(cpuid);
1561 if (pmap == PCPU_GET(curpmap))
1563 else if (pmap_pcid_enabled)
1564 pmap->pm_pcids[cpuid].pm_gen = 0;
1565 if (pmap_pcid_enabled) {
1568 pmap->pm_pcids[i].pm_gen = 0;
1571 mask = &pmap->pm_active;
1573 smp_masked_invlpg(*mask, va);
1577 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1578 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1581 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1587 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1588 pmap_invalidate_all(pmap);
1592 if (pmap_type_guest(pmap)) {
1593 pmap_invalidate_ept(pmap);
1597 KASSERT(pmap->pm_type == PT_X86,
1598 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1601 cpuid = PCPU_GET(cpuid);
1602 if (pmap == kernel_pmap) {
1603 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1607 if (pmap == PCPU_GET(curpmap)) {
1608 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1610 } else if (pmap_pcid_enabled) {
1611 pmap->pm_pcids[cpuid].pm_gen = 0;
1613 if (pmap_pcid_enabled) {
1616 pmap->pm_pcids[i].pm_gen = 0;
1619 mask = &pmap->pm_active;
1621 smp_masked_invlpg_range(*mask, sva, eva);
1626 pmap_invalidate_all(pmap_t pmap)
1629 struct invpcid_descr d;
1632 if (pmap_type_guest(pmap)) {
1633 pmap_invalidate_ept(pmap);
1637 KASSERT(pmap->pm_type == PT_X86,
1638 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1641 if (pmap == kernel_pmap) {
1642 if (pmap_pcid_enabled && invpcid_works) {
1643 bzero(&d, sizeof(d));
1644 invpcid(&d, INVPCID_CTXGLOB);
1650 cpuid = PCPU_GET(cpuid);
1651 if (pmap == PCPU_GET(curpmap)) {
1652 if (pmap_pcid_enabled) {
1653 if (invpcid_works) {
1654 d.pcid = pmap->pm_pcids[cpuid].pm_pcid;
1657 invpcid(&d, INVPCID_CTX);
1659 load_cr3(pmap->pm_cr3 | pmap->pm_pcids
1660 [PCPU_GET(cpuid)].pm_pcid);
1665 } else if (pmap_pcid_enabled) {
1666 pmap->pm_pcids[cpuid].pm_gen = 0;
1668 if (pmap_pcid_enabled) {
1671 pmap->pm_pcids[i].pm_gen = 0;
1674 mask = &pmap->pm_active;
1676 smp_masked_invltlb(*mask, pmap);
1681 pmap_invalidate_cache(void)
1691 cpuset_t invalidate; /* processors that invalidate their TLB */
1696 u_int store; /* processor that updates the PDE */
1700 pmap_update_pde_action(void *arg)
1702 struct pde_action *act = arg;
1704 if (act->store == PCPU_GET(cpuid))
1705 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1709 pmap_update_pde_teardown(void *arg)
1711 struct pde_action *act = arg;
1713 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1714 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1718 * Change the page size for the specified virtual address in a way that
1719 * prevents any possibility of the TLB ever having two entries that map the
1720 * same virtual address using different page sizes. This is the recommended
1721 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1722 * machine check exception for a TLB state that is improperly diagnosed as a
1726 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1728 struct pde_action act;
1729 cpuset_t active, other_cpus;
1733 cpuid = PCPU_GET(cpuid);
1734 other_cpus = all_cpus;
1735 CPU_CLR(cpuid, &other_cpus);
1736 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1739 active = pmap->pm_active;
1741 if (CPU_OVERLAP(&active, &other_cpus)) {
1743 act.invalidate = active;
1747 act.newpde = newpde;
1748 CPU_SET(cpuid, &active);
1749 smp_rendezvous_cpus(active,
1750 smp_no_rendezvous_barrier, pmap_update_pde_action,
1751 pmap_update_pde_teardown, &act);
1753 pmap_update_pde_store(pmap, pde, newpde);
1754 if (CPU_ISSET(cpuid, &active))
1755 pmap_update_pde_invalidate(pmap, va, newpde);
1761 * Normal, non-SMP, invalidation functions.
1764 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1767 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1771 KASSERT(pmap->pm_type == PT_X86,
1772 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1774 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1776 else if (pmap_pcid_enabled)
1777 pmap->pm_pcids[0].pm_gen = 0;
1781 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1785 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1789 KASSERT(pmap->pm_type == PT_X86,
1790 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1792 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1793 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1795 } else if (pmap_pcid_enabled) {
1796 pmap->pm_pcids[0].pm_gen = 0;
1801 pmap_invalidate_all(pmap_t pmap)
1803 struct invpcid_descr d;
1805 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1809 KASSERT(pmap->pm_type == PT_X86,
1810 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
1812 if (pmap == kernel_pmap) {
1813 if (pmap_pcid_enabled && invpcid_works) {
1814 bzero(&d, sizeof(d));
1815 invpcid(&d, INVPCID_CTXGLOB);
1819 } else if (pmap == PCPU_GET(curpmap)) {
1820 if (pmap_pcid_enabled) {
1821 if (invpcid_works) {
1822 d.pcid = pmap->pm_pcids[0].pm_pcid;
1825 invpcid(&d, INVPCID_CTX);
1827 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[0].
1833 } else if (pmap_pcid_enabled) {
1834 pmap->pm_pcids[0].pm_gen = 0;
1839 pmap_invalidate_cache(void)
1846 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1849 pmap_update_pde_store(pmap, pde, newpde);
1850 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1851 pmap_update_pde_invalidate(pmap, va, newpde);
1853 pmap->pm_pcids[0].pm_gen = 0;
1858 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
1862 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
1863 * by a promotion that did not invalidate the 512 4KB page mappings
1864 * that might exist in the TLB. Consequently, at this point, the TLB
1865 * may hold both 4KB and 2MB page mappings for the address range [va,
1866 * va + NBPDR). Therefore, the entire range must be invalidated here.
1867 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
1868 * 4KB page mappings for the address range [va, va + NBPDR), and so a
1869 * single INVLPG suffices to invalidate the 2MB page mapping from the
1872 if ((pde & PG_PROMOTED) != 0)
1873 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
1875 pmap_invalidate_page(pmap, va);
1878 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
1881 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
1885 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
1887 KASSERT((sva & PAGE_MASK) == 0,
1888 ("pmap_invalidate_cache_range: sva not page-aligned"));
1889 KASSERT((eva & PAGE_MASK) == 0,
1890 ("pmap_invalidate_cache_range: eva not page-aligned"));
1893 if ((cpu_feature & CPUID_SS) != 0 && !force)
1894 ; /* If "Self Snoop" is supported and allowed, do nothing. */
1895 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
1896 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1898 * XXX: Some CPUs fault, hang, or trash the local APIC
1899 * registers if we use CLFLUSH on the local APIC
1900 * range. The local APIC is always uncached, so we
1901 * don't need to flush for that range anyway.
1903 if (pmap_kextract(sva) == lapic_paddr)
1907 * Otherwise, do per-cache line flush. Use the sfence
1908 * instruction to insure that previous stores are
1909 * included in the write-back. The processor
1910 * propagates flush to other processors in the cache
1914 for (; sva < eva; sva += cpu_clflush_line_size)
1917 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
1918 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1919 if (pmap_kextract(sva) == lapic_paddr)
1922 * Writes are ordered by CLFLUSH on Intel CPUs.
1924 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1926 for (; sva < eva; sva += cpu_clflush_line_size)
1928 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1933 * No targeted cache flush methods are supported by CPU,
1934 * or the supplied range is bigger than 2MB.
1935 * Globally invalidate cache.
1937 pmap_invalidate_cache();
1942 * Remove the specified set of pages from the data and instruction caches.
1944 * In contrast to pmap_invalidate_cache_range(), this function does not
1945 * rely on the CPU's self-snoop feature, because it is intended for use
1946 * when moving pages into a different cache domain.
1949 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1951 vm_offset_t daddr, eva;
1955 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
1956 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1957 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
1958 pmap_invalidate_cache();
1962 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
1964 for (i = 0; i < count; i++) {
1965 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
1966 eva = daddr + PAGE_SIZE;
1967 for (; daddr < eva; daddr += cpu_clflush_line_size) {
1976 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
1982 * Routine: pmap_extract
1984 * Extract the physical page address associated
1985 * with the given map/virtual_address pair.
1988 pmap_extract(pmap_t pmap, vm_offset_t va)
1992 pt_entry_t *pte, PG_V;
1996 PG_V = pmap_valid_bit(pmap);
1998 pdpe = pmap_pdpe(pmap, va);
1999 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2000 if ((*pdpe & PG_PS) != 0)
2001 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
2003 pde = pmap_pdpe_to_pde(pdpe, va);
2004 if ((*pde & PG_V) != 0) {
2005 if ((*pde & PG_PS) != 0) {
2006 pa = (*pde & PG_PS_FRAME) |
2009 pte = pmap_pde_to_pte(pde, va);
2010 pa = (*pte & PG_FRAME) |
2021 * Routine: pmap_extract_and_hold
2023 * Atomically extract and hold the physical page
2024 * with the given pmap and virtual address pair
2025 * if that mapping permits the given protection.
2028 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
2030 pd_entry_t pde, *pdep;
2031 pt_entry_t pte, PG_RW, PG_V;
2037 PG_RW = pmap_rw_bit(pmap);
2038 PG_V = pmap_valid_bit(pmap);
2041 pdep = pmap_pde(pmap, va);
2042 if (pdep != NULL && (pde = *pdep)) {
2044 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2045 if (vm_page_pa_tryrelock(pmap, (pde &
2046 PG_PS_FRAME) | (va & PDRMASK), &pa))
2048 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
2053 pte = *pmap_pde_to_pte(pdep, va);
2055 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2056 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2059 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
2070 pmap_kextract(vm_offset_t va)
2075 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2076 pa = DMAP_TO_PHYS(va);
2080 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2083 * Beware of a concurrent promotion that changes the
2084 * PDE at this point! For example, vtopte() must not
2085 * be used to access the PTE because it would use the
2086 * new PDE. It is, however, safe to use the old PDE
2087 * because the page table page is preserved by the
2090 pa = *pmap_pde_to_pte(&pde, va);
2091 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2097 /***************************************************
2098 * Low level mapping routines.....
2099 ***************************************************/
2102 * Add a wired page to the kva.
2103 * Note: not SMP coherent.
2106 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2111 pte_store(pte, pa | X86_PG_RW | X86_PG_V | X86_PG_G);
2114 static __inline void
2115 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2121 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2122 pte_store(pte, pa | X86_PG_RW | X86_PG_V | X86_PG_G | cache_bits);
2126 * Remove a page from the kernel pagetables.
2127 * Note: not SMP coherent.
2130 pmap_kremove(vm_offset_t va)
2139 * Used to map a range of physical addresses into kernel
2140 * virtual address space.
2142 * The value passed in '*virt' is a suggested virtual address for
2143 * the mapping. Architectures which can support a direct-mapped
2144 * physical to virtual region can return the appropriate address
2145 * within that region, leaving '*virt' unchanged. Other
2146 * architectures should map the pages starting at '*virt' and
2147 * update '*virt' with the first usable address after the mapped
2151 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2153 return PHYS_TO_DMAP(start);
2158 * Add a list of wired pages to the kva
2159 * this routine is only used for temporary
2160 * kernel mappings that do not need to have
2161 * page modification or references recorded.
2162 * Note that old mappings are simply written
2163 * over. The page *must* be wired.
2164 * Note: SMP coherent. Uses a ranged shootdown IPI.
2167 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2169 pt_entry_t *endpte, oldpte, pa, *pte;
2175 endpte = pte + count;
2176 while (pte < endpte) {
2178 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2179 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2180 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2182 pte_store(pte, pa | X86_PG_G | X86_PG_RW | X86_PG_V);
2186 if (__predict_false((oldpte & X86_PG_V) != 0))
2187 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2192 * This routine tears out page mappings from the
2193 * kernel -- it is meant only for temporary mappings.
2194 * Note: SMP coherent. Uses a ranged shootdown IPI.
2197 pmap_qremove(vm_offset_t sva, int count)
2202 while (count-- > 0) {
2203 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2207 pmap_invalidate_range(kernel_pmap, sva, va);
2210 /***************************************************
2211 * Page table page management routines.....
2212 ***************************************************/
2213 static __inline void
2214 pmap_free_zero_pages(struct spglist *free)
2219 for (count = 0; (m = SLIST_FIRST(free)) != NULL; count++) {
2220 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2221 /* Preserve the page's PG_ZERO setting. */
2222 vm_page_free_toq(m);
2224 atomic_subtract_int(&vm_cnt.v_wire_count, count);
2228 * Schedule the specified unused page table page to be freed. Specifically,
2229 * add the page to the specified list of pages that will be released to the
2230 * physical memory manager after the TLB has been updated.
2232 static __inline void
2233 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2234 boolean_t set_PG_ZERO)
2238 m->flags |= PG_ZERO;
2240 m->flags &= ~PG_ZERO;
2241 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2245 * Inserts the specified page table page into the specified pmap's collection
2246 * of idle page table pages. Each of a pmap's page table pages is responsible
2247 * for mapping a distinct range of virtual addresses. The pmap's collection is
2248 * ordered by this virtual address range.
2251 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2254 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2255 return (vm_radix_insert(&pmap->pm_root, mpte));
2259 * Removes the page table page mapping the specified virtual address from the
2260 * specified pmap's collection of idle page table pages, and returns it.
2261 * Otherwise, returns NULL if there is no page table page corresponding to the
2262 * specified virtual address.
2264 static __inline vm_page_t
2265 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
2268 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2269 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
2273 * Decrements a page table page's wire count, which is used to record the
2274 * number of valid page table entries within the page. If the wire count
2275 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2276 * page table page was unmapped and FALSE otherwise.
2278 static inline boolean_t
2279 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2283 if (m->wire_count == 0) {
2284 _pmap_unwire_ptp(pmap, va, m, free);
2291 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2294 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2296 * unmap the page table page
2298 if (m->pindex >= (NUPDE + NUPDPE)) {
2301 pml4 = pmap_pml4e(pmap, va);
2303 } else if (m->pindex >= NUPDE) {
2306 pdp = pmap_pdpe(pmap, va);
2311 pd = pmap_pde(pmap, va);
2314 pmap_resident_count_dec(pmap, 1);
2315 if (m->pindex < NUPDE) {
2316 /* We just released a PT, unhold the matching PD */
2319 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2320 pmap_unwire_ptp(pmap, va, pdpg, free);
2322 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2323 /* We just released a PD, unhold the matching PDP */
2326 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2327 pmap_unwire_ptp(pmap, va, pdppg, free);
2331 * Put page on a list so that it is released after
2332 * *ALL* TLB shootdown is done
2334 pmap_add_delayed_free_list(m, free, TRUE);
2338 * After removing a page table entry, this routine is used to
2339 * conditionally free the page, and manage the hold/wire counts.
2342 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2343 struct spglist *free)
2347 if (va >= VM_MAXUSER_ADDRESS)
2349 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2350 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2351 return (pmap_unwire_ptp(pmap, va, mpte, free));
2355 pmap_pinit0(pmap_t pmap)
2359 PMAP_LOCK_INIT(pmap);
2360 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2361 pmap->pm_cr3 = KPML4phys;
2362 pmap->pm_root.rt_root = 0;
2363 CPU_ZERO(&pmap->pm_active);
2364 TAILQ_INIT(&pmap->pm_pvchunk);
2365 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2366 pmap->pm_flags = pmap_flags;
2368 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2369 pmap->pm_pcids[i].pm_gen = 0;
2371 PCPU_SET(curpmap, kernel_pmap);
2372 pmap_activate(curthread);
2373 CPU_FILL(&kernel_pmap->pm_active);
2377 pmap_pinit_pml4(vm_page_t pml4pg)
2379 pml4_entry_t *pm_pml4;
2382 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2384 /* Wire in kernel global address entries. */
2385 for (i = 0; i < NKPML4E; i++) {
2386 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2389 for (i = 0; i < ndmpdpphys; i++) {
2390 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2394 /* install self-referential address mapping entry(s) */
2395 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2396 X86_PG_A | X86_PG_M;
2400 * Initialize a preallocated and zeroed pmap structure,
2401 * such as one in a vmspace structure.
2404 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2407 vm_paddr_t pml4phys;
2411 * allocate the page directory page
2413 while ((pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2414 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL)
2417 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2418 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2420 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2421 pmap->pm_pcids[i].pm_gen = 0;
2423 pmap->pm_cr3 = ~0; /* initialize to an invalid value */
2425 if ((pml4pg->flags & PG_ZERO) == 0)
2426 pagezero(pmap->pm_pml4);
2429 * Do not install the host kernel mappings in the nested page
2430 * tables. These mappings are meaningless in the guest physical
2433 if ((pmap->pm_type = pm_type) == PT_X86) {
2434 pmap->pm_cr3 = pml4phys;
2435 pmap_pinit_pml4(pml4pg);
2438 pmap->pm_root.rt_root = 0;
2439 CPU_ZERO(&pmap->pm_active);
2440 TAILQ_INIT(&pmap->pm_pvchunk);
2441 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2442 pmap->pm_flags = flags;
2443 pmap->pm_eptgen = 0;
2449 pmap_pinit(pmap_t pmap)
2452 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2456 * This routine is called if the desired page table page does not exist.
2458 * If page table page allocation fails, this routine may sleep before
2459 * returning NULL. It sleeps only if a lock pointer was given.
2461 * Note: If a page allocation fails at page table level two or three,
2462 * one or two pages may be held during the wait, only to be released
2463 * afterwards. This conservative approach is easily argued to avoid
2467 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2469 vm_page_t m, pdppg, pdpg;
2470 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2472 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2474 PG_A = pmap_accessed_bit(pmap);
2475 PG_M = pmap_modified_bit(pmap);
2476 PG_V = pmap_valid_bit(pmap);
2477 PG_RW = pmap_rw_bit(pmap);
2480 * Allocate a page table page.
2482 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2483 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2484 if (lockp != NULL) {
2485 RELEASE_PV_LIST_LOCK(lockp);
2487 PMAP_ASSERT_NOT_IN_DI();
2493 * Indicate the need to retry. While waiting, the page table
2494 * page may have been allocated.
2498 if ((m->flags & PG_ZERO) == 0)
2502 * Map the pagetable page into the process address space, if
2503 * it isn't already there.
2506 if (ptepindex >= (NUPDE + NUPDPE)) {
2508 vm_pindex_t pml4index;
2510 /* Wire up a new PDPE page */
2511 pml4index = ptepindex - (NUPDE + NUPDPE);
2512 pml4 = &pmap->pm_pml4[pml4index];
2513 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2515 } else if (ptepindex >= NUPDE) {
2516 vm_pindex_t pml4index;
2517 vm_pindex_t pdpindex;
2521 /* Wire up a new PDE page */
2522 pdpindex = ptepindex - NUPDE;
2523 pml4index = pdpindex >> NPML4EPGSHIFT;
2525 pml4 = &pmap->pm_pml4[pml4index];
2526 if ((*pml4 & PG_V) == 0) {
2527 /* Have to allocate a new pdp, recurse */
2528 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2531 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2532 vm_page_free_zero(m);
2536 /* Add reference to pdp page */
2537 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2538 pdppg->wire_count++;
2540 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2542 /* Now find the pdp page */
2543 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2544 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2547 vm_pindex_t pml4index;
2548 vm_pindex_t pdpindex;
2553 /* Wire up a new PTE page */
2554 pdpindex = ptepindex >> NPDPEPGSHIFT;
2555 pml4index = pdpindex >> NPML4EPGSHIFT;
2557 /* First, find the pdp and check that its valid. */
2558 pml4 = &pmap->pm_pml4[pml4index];
2559 if ((*pml4 & PG_V) == 0) {
2560 /* Have to allocate a new pd, recurse */
2561 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2564 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2565 vm_page_free_zero(m);
2568 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2569 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2571 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2572 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2573 if ((*pdp & PG_V) == 0) {
2574 /* Have to allocate a new pd, recurse */
2575 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2578 atomic_subtract_int(&vm_cnt.v_wire_count,
2580 vm_page_free_zero(m);
2584 /* Add reference to the pd page */
2585 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2589 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2591 /* Now we know where the page directory page is */
2592 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2593 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2596 pmap_resident_count_inc(pmap, 1);
2602 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2604 vm_pindex_t pdpindex, ptepindex;
2605 pdp_entry_t *pdpe, PG_V;
2608 PG_V = pmap_valid_bit(pmap);
2611 pdpe = pmap_pdpe(pmap, va);
2612 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2613 /* Add a reference to the pd page. */
2614 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2617 /* Allocate a pd page. */
2618 ptepindex = pmap_pde_pindex(va);
2619 pdpindex = ptepindex >> NPDPEPGSHIFT;
2620 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2621 if (pdpg == NULL && lockp != NULL)
2628 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2630 vm_pindex_t ptepindex;
2631 pd_entry_t *pd, PG_V;
2634 PG_V = pmap_valid_bit(pmap);
2637 * Calculate pagetable page index
2639 ptepindex = pmap_pde_pindex(va);
2642 * Get the page directory entry
2644 pd = pmap_pde(pmap, va);
2647 * This supports switching from a 2MB page to a
2650 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2651 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2653 * Invalidation of the 2MB page mapping may have caused
2654 * the deallocation of the underlying PD page.
2661 * If the page table page is mapped, we just increment the
2662 * hold count, and activate it.
2664 if (pd != NULL && (*pd & PG_V) != 0) {
2665 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2669 * Here if the pte page isn't mapped, or if it has been
2672 m = _pmap_allocpte(pmap, ptepindex, lockp);
2673 if (m == NULL && lockp != NULL)
2680 /***************************************************
2681 * Pmap allocation/deallocation routines.
2682 ***************************************************/
2685 * Release any resources held by the given physical map.
2686 * Called when a pmap initialized by pmap_pinit is being released.
2687 * Should only be called if the map contains no valid mappings.
2690 pmap_release(pmap_t pmap)
2695 KASSERT(pmap->pm_stats.resident_count == 0,
2696 ("pmap_release: pmap resident count %ld != 0",
2697 pmap->pm_stats.resident_count));
2698 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2699 ("pmap_release: pmap has reserved page table page(s)"));
2700 KASSERT(CPU_EMPTY(&pmap->pm_active),
2701 ("releasing active pmap %p", pmap));
2703 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2705 for (i = 0; i < NKPML4E; i++) /* KVA */
2706 pmap->pm_pml4[KPML4BASE + i] = 0;
2707 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
2708 pmap->pm_pml4[DMPML4I + i] = 0;
2709 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
2712 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2713 vm_page_free_zero(m);
2717 kvm_size(SYSCTL_HANDLER_ARGS)
2719 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2721 return sysctl_handle_long(oidp, &ksize, 0, req);
2723 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2724 0, 0, kvm_size, "LU", "Size of KVM");
2727 kvm_free(SYSCTL_HANDLER_ARGS)
2729 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2731 return sysctl_handle_long(oidp, &kfree, 0, req);
2733 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2734 0, 0, kvm_free, "LU", "Amount of KVM free");
2737 * grow the number of kernel page table entries, if needed
2740 pmap_growkernel(vm_offset_t addr)
2744 pd_entry_t *pde, newpdir;
2747 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2750 * Return if "addr" is within the range of kernel page table pages
2751 * that were preallocated during pmap bootstrap. Moreover, leave
2752 * "kernel_vm_end" and the kernel page table as they were.
2754 * The correctness of this action is based on the following
2755 * argument: vm_map_insert() allocates contiguous ranges of the
2756 * kernel virtual address space. It calls this function if a range
2757 * ends after "kernel_vm_end". If the kernel is mapped between
2758 * "kernel_vm_end" and "addr", then the range cannot begin at
2759 * "kernel_vm_end". In fact, its beginning address cannot be less
2760 * than the kernel. Thus, there is no immediate need to allocate
2761 * any new kernel page table pages between "kernel_vm_end" and
2764 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
2767 addr = roundup2(addr, NBPDR);
2768 if (addr - 1 >= kernel_map->max_offset)
2769 addr = kernel_map->max_offset;
2770 while (kernel_vm_end < addr) {
2771 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
2772 if ((*pdpe & X86_PG_V) == 0) {
2773 /* We need a new PDP entry */
2774 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
2775 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
2776 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2778 panic("pmap_growkernel: no memory to grow kernel");
2779 if ((nkpg->flags & PG_ZERO) == 0)
2780 pmap_zero_page(nkpg);
2781 paddr = VM_PAGE_TO_PHYS(nkpg);
2782 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
2783 X86_PG_A | X86_PG_M);
2784 continue; /* try again */
2786 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
2787 if ((*pde & X86_PG_V) != 0) {
2788 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2789 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2790 kernel_vm_end = kernel_map->max_offset;
2796 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
2797 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
2800 panic("pmap_growkernel: no memory to grow kernel");
2801 if ((nkpg->flags & PG_ZERO) == 0)
2802 pmap_zero_page(nkpg);
2803 paddr = VM_PAGE_TO_PHYS(nkpg);
2804 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
2805 pde_store(pde, newpdir);
2807 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2808 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2809 kernel_vm_end = kernel_map->max_offset;
2816 /***************************************************
2817 * page management routines.
2818 ***************************************************/
2820 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
2821 CTASSERT(_NPCM == 3);
2822 CTASSERT(_NPCPV == 168);
2824 static __inline struct pv_chunk *
2825 pv_to_chunk(pv_entry_t pv)
2828 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
2831 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
2833 #define PC_FREE0 0xfffffffffffffffful
2834 #define PC_FREE1 0xfffffffffffffffful
2835 #define PC_FREE2 0x000000fffffffffful
2837 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
2840 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2842 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2843 "Current number of pv entry chunks");
2844 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2845 "Current number of pv entry chunks allocated");
2846 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2847 "Current number of pv entry chunks frees");
2848 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
2849 "Number of times tried to get a chunk page but failed.");
2851 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
2852 static int pv_entry_spare;
2854 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2855 "Current number of pv entry frees");
2856 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
2857 "Current number of pv entry allocs");
2858 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2859 "Current number of pv entries");
2860 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2861 "Current number of spare pv entries");
2865 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
2870 pmap_invalidate_all(pmap);
2871 if (pmap != locked_pmap)
2874 pmap_delayed_invl_finished();
2878 * We are in a serious low memory condition. Resort to
2879 * drastic measures to free some pages so we can allocate
2880 * another pv entry chunk.
2882 * Returns NULL if PV entries were reclaimed from the specified pmap.
2884 * We do not, however, unmap 2mpages because subsequent accesses will
2885 * allocate per-page pv entries until repromotion occurs, thereby
2886 * exacerbating the shortage of free pv entries.
2889 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
2891 struct pch new_tail;
2892 struct pv_chunk *pc;
2893 struct md_page *pvh;
2896 pt_entry_t *pte, tpte;
2897 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
2901 struct spglist free;
2903 int bit, field, freed;
2906 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2907 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
2910 PG_G = PG_A = PG_M = PG_RW = 0;
2912 TAILQ_INIT(&new_tail);
2915 * A delayed invalidation block should already be active if
2916 * pmap_advise() or pmap_remove() called this function by way
2917 * of pmap_demote_pde_locked().
2919 start_di = pmap_not_in_di();
2921 mtx_lock(&pv_chunks_mutex);
2922 while ((pc = TAILQ_FIRST(&pv_chunks)) != NULL && SLIST_EMPTY(&free)) {
2923 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2924 mtx_unlock(&pv_chunks_mutex);
2925 if (pmap != pc->pc_pmap) {
2926 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
2929 /* Avoid deadlock and lock recursion. */
2930 if (pmap > locked_pmap) {
2931 RELEASE_PV_LIST_LOCK(lockp);
2933 } else if (pmap != locked_pmap &&
2934 !PMAP_TRYLOCK(pmap)) {
2936 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2937 mtx_lock(&pv_chunks_mutex);
2940 PG_G = pmap_global_bit(pmap);
2941 PG_A = pmap_accessed_bit(pmap);
2942 PG_M = pmap_modified_bit(pmap);
2943 PG_RW = pmap_rw_bit(pmap);
2945 pmap_delayed_invl_started();
2949 * Destroy every non-wired, 4 KB page mapping in the chunk.
2952 for (field = 0; field < _NPCM; field++) {
2953 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2954 inuse != 0; inuse &= ~(1UL << bit)) {
2956 pv = &pc->pc_pventry[field * 64 + bit];
2958 pde = pmap_pde(pmap, va);
2959 if ((*pde & PG_PS) != 0)
2961 pte = pmap_pde_to_pte(pde, va);
2962 if ((*pte & PG_W) != 0)
2964 tpte = pte_load_clear(pte);
2965 if ((tpte & PG_G) != 0)
2966 pmap_invalidate_page(pmap, va);
2967 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
2968 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
2970 if ((tpte & PG_A) != 0)
2971 vm_page_aflag_set(m, PGA_REFERENCED);
2972 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
2973 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
2975 if (TAILQ_EMPTY(&m->md.pv_list) &&
2976 (m->flags & PG_FICTITIOUS) == 0) {
2977 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
2978 if (TAILQ_EMPTY(&pvh->pv_list)) {
2979 vm_page_aflag_clear(m,
2983 pmap_delayed_invl_page(m);
2984 pc->pc_map[field] |= 1UL << bit;
2985 pmap_unuse_pt(pmap, va, *pde, &free);
2990 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2991 mtx_lock(&pv_chunks_mutex);
2994 /* Every freed mapping is for a 4 KB page. */
2995 pmap_resident_count_dec(pmap, freed);
2996 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
2997 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
2998 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
2999 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3000 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
3001 pc->pc_map[2] == PC_FREE2) {
3002 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3003 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3004 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3005 /* Entire chunk is free; return it. */
3006 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3007 dump_drop_page(m_pc->phys_addr);
3008 mtx_lock(&pv_chunks_mutex);
3011 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3012 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3013 mtx_lock(&pv_chunks_mutex);
3014 /* One freed pv entry in locked_pmap is sufficient. */
3015 if (pmap == locked_pmap)
3018 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3019 mtx_unlock(&pv_chunks_mutex);
3020 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
3021 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
3022 m_pc = SLIST_FIRST(&free);
3023 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3024 /* Recycle a freed page table page. */
3025 m_pc->wire_count = 1;
3027 pmap_free_zero_pages(&free);
3032 * free the pv_entry back to the free list
3035 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3037 struct pv_chunk *pc;
3038 int idx, field, bit;
3040 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3041 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3042 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3043 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3044 pc = pv_to_chunk(pv);
3045 idx = pv - &pc->pc_pventry[0];
3048 pc->pc_map[field] |= 1ul << bit;
3049 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3050 pc->pc_map[2] != PC_FREE2) {
3051 /* 98% of the time, pc is already at the head of the list. */
3052 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3053 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3054 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3058 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3063 free_pv_chunk(struct pv_chunk *pc)
3067 mtx_lock(&pv_chunks_mutex);
3068 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3069 mtx_unlock(&pv_chunks_mutex);
3070 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3071 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3072 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3073 /* entire chunk is free, return it */
3074 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3075 dump_drop_page(m->phys_addr);
3076 vm_page_unwire(m, PQ_NONE);
3081 * Returns a new PV entry, allocating a new PV chunk from the system when
3082 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3083 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3086 * The given PV list lock may be released.
3089 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3093 struct pv_chunk *pc;
3096 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3097 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3099 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3101 for (field = 0; field < _NPCM; field++) {
3102 if (pc->pc_map[field]) {
3103 bit = bsfq(pc->pc_map[field]);
3107 if (field < _NPCM) {
3108 pv = &pc->pc_pventry[field * 64 + bit];
3109 pc->pc_map[field] &= ~(1ul << bit);
3110 /* If this was the last item, move it to tail */
3111 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3112 pc->pc_map[2] == 0) {
3113 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3114 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3117 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3118 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3122 /* No free items, allocate another chunk */
3123 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3126 if (lockp == NULL) {
3127 PV_STAT(pc_chunk_tryfail++);
3130 m = reclaim_pv_chunk(pmap, lockp);
3134 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3135 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3136 dump_add_page(m->phys_addr);
3137 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3139 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3140 pc->pc_map[1] = PC_FREE1;
3141 pc->pc_map[2] = PC_FREE2;
3142 mtx_lock(&pv_chunks_mutex);
3143 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3144 mtx_unlock(&pv_chunks_mutex);
3145 pv = &pc->pc_pventry[0];
3146 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3147 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3148 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3153 * Returns the number of one bits within the given PV chunk map.
3155 * The erratas for Intel processors state that "POPCNT Instruction May
3156 * Take Longer to Execute Than Expected". It is believed that the
3157 * issue is the spurious dependency on the destination register.
3158 * Provide a hint to the register rename logic that the destination
3159 * value is overwritten, by clearing it, as suggested in the
3160 * optimization manual. It should be cheap for unaffected processors
3163 * Reference numbers for erratas are
3164 * 4th Gen Core: HSD146
3165 * 5th Gen Core: BDM85
3166 * 6th Gen Core: SKL029
3169 popcnt_pc_map_pq(uint64_t *map)
3173 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3174 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3175 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3176 : "=&r" (result), "=&r" (tmp)
3177 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3182 * Ensure that the number of spare PV entries in the specified pmap meets or
3183 * exceeds the given count, "needed".
3185 * The given PV list lock may be released.
3188 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3190 struct pch new_tail;
3191 struct pv_chunk *pc;
3195 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3196 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3199 * Newly allocated PV chunks must be stored in a private list until
3200 * the required number of PV chunks have been allocated. Otherwise,
3201 * reclaim_pv_chunk() could recycle one of these chunks. In
3202 * contrast, these chunks must be added to the pmap upon allocation.
3204 TAILQ_INIT(&new_tail);
3207 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3209 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3210 bit_count((bitstr_t *)pc->pc_map, 0,
3211 sizeof(pc->pc_map) * NBBY, &free);
3214 free = popcnt_pc_map_pq(pc->pc_map);
3218 if (avail >= needed)
3221 for (; avail < needed; avail += _NPCPV) {
3222 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3225 m = reclaim_pv_chunk(pmap, lockp);
3229 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3230 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3231 dump_add_page(m->phys_addr);
3232 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3234 pc->pc_map[0] = PC_FREE0;
3235 pc->pc_map[1] = PC_FREE1;
3236 pc->pc_map[2] = PC_FREE2;
3237 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3238 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3239 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3241 if (!TAILQ_EMPTY(&new_tail)) {
3242 mtx_lock(&pv_chunks_mutex);
3243 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3244 mtx_unlock(&pv_chunks_mutex);
3249 * First find and then remove the pv entry for the specified pmap and virtual
3250 * address from the specified pv list. Returns the pv entry if found and NULL
3251 * otherwise. This operation can be performed on pv lists for either 4KB or
3252 * 2MB page mappings.
3254 static __inline pv_entry_t
3255 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3259 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3260 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3261 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3270 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3271 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3272 * entries for each of the 4KB page mappings.
3275 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3276 struct rwlock **lockp)
3278 struct md_page *pvh;
3279 struct pv_chunk *pc;
3281 vm_offset_t va_last;
3285 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3286 KASSERT((pa & PDRMASK) == 0,
3287 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3288 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3291 * Transfer the 2mpage's pv entry for this mapping to the first
3292 * page's pv list. Once this transfer begins, the pv list lock
3293 * must not be released until the last pv entry is reinstantiated.
3295 pvh = pa_to_pvh(pa);
3296 va = trunc_2mpage(va);
3297 pv = pmap_pvh_remove(pvh, pmap, va);
3298 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3299 m = PHYS_TO_VM_PAGE(pa);
3300 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3302 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3303 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3304 va_last = va + NBPDR - PAGE_SIZE;
3306 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3307 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3308 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3309 for (field = 0; field < _NPCM; field++) {
3310 while (pc->pc_map[field]) {
3311 bit = bsfq(pc->pc_map[field]);
3312 pc->pc_map[field] &= ~(1ul << bit);
3313 pv = &pc->pc_pventry[field * 64 + bit];
3317 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3318 ("pmap_pv_demote_pde: page %p is not managed", m));
3319 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3325 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3326 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3329 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3330 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3331 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3333 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3334 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3338 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3339 * replace the many pv entries for the 4KB page mappings by a single pv entry
3340 * for the 2MB page mapping.
3343 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3344 struct rwlock **lockp)
3346 struct md_page *pvh;
3348 vm_offset_t va_last;
3351 KASSERT((pa & PDRMASK) == 0,
3352 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3353 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3356 * Transfer the first page's pv entry for this mapping to the 2mpage's
3357 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3358 * a transfer avoids the possibility that get_pv_entry() calls
3359 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3360 * mappings that is being promoted.
3362 m = PHYS_TO_VM_PAGE(pa);
3363 va = trunc_2mpage(va);
3364 pv = pmap_pvh_remove(&m->md, pmap, va);
3365 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3366 pvh = pa_to_pvh(pa);
3367 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3369 /* Free the remaining NPTEPG - 1 pv entries. */
3370 va_last = va + NBPDR - PAGE_SIZE;
3374 pmap_pvh_free(&m->md, pmap, va);
3375 } while (va < va_last);
3379 * First find and then destroy the pv entry for the specified pmap and virtual
3380 * address. This operation can be performed on pv lists for either 4KB or 2MB
3384 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3388 pv = pmap_pvh_remove(pvh, pmap, va);
3389 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3390 free_pv_entry(pmap, pv);
3394 * Conditionally create the PV entry for a 4KB page mapping if the required
3395 * memory can be allocated without resorting to reclamation.
3398 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3399 struct rwlock **lockp)
3403 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3404 /* Pass NULL instead of the lock pointer to disable reclamation. */
3405 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3407 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3408 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3416 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3417 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3418 * false if the PV entry cannot be allocated without resorting to reclamation.
3421 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
3422 struct rwlock **lockp)
3424 struct md_page *pvh;
3428 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3429 /* Pass NULL instead of the lock pointer to disable reclamation. */
3430 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3431 NULL : lockp)) == NULL)
3434 pa = pde & PG_PS_FRAME;
3435 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3436 pvh = pa_to_pvh(pa);
3437 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3443 * Fills a page table page with mappings to consecutive physical pages.
3446 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3450 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3452 newpte += PAGE_SIZE;
3457 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3458 * mapping is invalidated.
3461 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3463 struct rwlock *lock;
3467 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3474 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3475 struct rwlock **lockp)
3477 pd_entry_t newpde, oldpde;
3478 pt_entry_t *firstpte, newpte;
3479 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3482 struct spglist free;
3486 PG_G = pmap_global_bit(pmap);
3487 PG_A = pmap_accessed_bit(pmap);
3488 PG_M = pmap_modified_bit(pmap);
3489 PG_RW = pmap_rw_bit(pmap);
3490 PG_V = pmap_valid_bit(pmap);
3491 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3493 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3495 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3496 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3497 if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
3499 KASSERT((oldpde & PG_W) == 0,
3500 ("pmap_demote_pde: page table page for a wired mapping"
3504 * Invalidate the 2MB page mapping and return "failure" if the
3505 * mapping was never accessed or the allocation of the new
3506 * page table page fails. If the 2MB page mapping belongs to
3507 * the direct map region of the kernel's address space, then
3508 * the page allocation request specifies the highest possible
3509 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3510 * normal. Page table pages are preallocated for every other
3511 * part of the kernel address space, so the direct map region
3512 * is the only part of the kernel address space that must be
3515 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3516 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3517 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3518 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3520 sva = trunc_2mpage(va);
3521 pmap_remove_pde(pmap, pde, sva, &free, lockp);
3522 if ((oldpde & PG_G) == 0)
3523 pmap_invalidate_pde_page(pmap, sva, oldpde);
3524 pmap_free_zero_pages(&free);
3525 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3526 " in pmap %p", va, pmap);
3529 if (va < VM_MAXUSER_ADDRESS)
3530 pmap_resident_count_inc(pmap, 1);
3532 mptepa = VM_PAGE_TO_PHYS(mpte);
3533 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3534 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3535 KASSERT((oldpde & PG_A) != 0,
3536 ("pmap_demote_pde: oldpde is missing PG_A"));
3537 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3538 ("pmap_demote_pde: oldpde is missing PG_M"));
3539 newpte = oldpde & ~PG_PS;
3540 newpte = pmap_swap_pat(pmap, newpte);
3543 * If the page table page is new, initialize it.
3545 if (mpte->wire_count == 1) {
3546 mpte->wire_count = NPTEPG;
3547 pmap_fill_ptp(firstpte, newpte);
3549 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3550 ("pmap_demote_pde: firstpte and newpte map different physical"
3554 * If the mapping has changed attributes, update the page table
3557 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3558 pmap_fill_ptp(firstpte, newpte);
3561 * The spare PV entries must be reserved prior to demoting the
3562 * mapping, that is, prior to changing the PDE. Otherwise, the state
3563 * of the PDE and the PV lists will be inconsistent, which can result
3564 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3565 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3566 * PV entry for the 2MB page mapping that is being demoted.
3568 if ((oldpde & PG_MANAGED) != 0)
3569 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3572 * Demote the mapping. This pmap is locked. The old PDE has
3573 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3574 * set. Thus, there is no danger of a race with another
3575 * processor changing the setting of PG_A and/or PG_M between
3576 * the read above and the store below.
3578 if (workaround_erratum383)
3579 pmap_update_pde(pmap, va, pde, newpde);
3581 pde_store(pde, newpde);
3584 * Invalidate a stale recursive mapping of the page table page.
3586 if (va >= VM_MAXUSER_ADDRESS)
3587 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3590 * Demote the PV entry.
3592 if ((oldpde & PG_MANAGED) != 0)
3593 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3595 atomic_add_long(&pmap_pde_demotions, 1);
3596 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3597 " in pmap %p", va, pmap);
3602 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3605 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3611 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3612 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3613 mpte = pmap_remove_pt_page(pmap, va);
3615 panic("pmap_remove_kernel_pde: Missing pt page.");
3617 mptepa = VM_PAGE_TO_PHYS(mpte);
3618 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3621 * Initialize the page table page.
3623 pagezero((void *)PHYS_TO_DMAP(mptepa));
3626 * Demote the mapping.
3628 if (workaround_erratum383)
3629 pmap_update_pde(pmap, va, pde, newpde);
3631 pde_store(pde, newpde);
3634 * Invalidate a stale recursive mapping of the page table page.
3636 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3640 * pmap_remove_pde: do the things to unmap a superpage in a process
3643 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
3644 struct spglist *free, struct rwlock **lockp)
3646 struct md_page *pvh;
3648 vm_offset_t eva, va;
3650 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3652 PG_G = pmap_global_bit(pmap);
3653 PG_A = pmap_accessed_bit(pmap);
3654 PG_M = pmap_modified_bit(pmap);
3655 PG_RW = pmap_rw_bit(pmap);
3657 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3658 KASSERT((sva & PDRMASK) == 0,
3659 ("pmap_remove_pde: sva is not 2mpage aligned"));
3660 oldpde = pte_load_clear(pdq);
3662 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
3663 if ((oldpde & PG_G) != 0)
3664 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
3665 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
3666 if (oldpde & PG_MANAGED) {
3667 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
3668 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
3669 pmap_pvh_free(pvh, pmap, sva);
3671 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3672 va < eva; va += PAGE_SIZE, m++) {
3673 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3676 vm_page_aflag_set(m, PGA_REFERENCED);
3677 if (TAILQ_EMPTY(&m->md.pv_list) &&
3678 TAILQ_EMPTY(&pvh->pv_list))
3679 vm_page_aflag_clear(m, PGA_WRITEABLE);
3680 pmap_delayed_invl_page(m);
3683 if (pmap == kernel_pmap) {
3684 pmap_remove_kernel_pde(pmap, pdq, sva);
3686 mpte = pmap_remove_pt_page(pmap, sva);
3688 pmap_resident_count_dec(pmap, 1);
3689 KASSERT(mpte->wire_count == NPTEPG,
3690 ("pmap_remove_pde: pte page wire count error"));
3691 mpte->wire_count = 0;
3692 pmap_add_delayed_free_list(mpte, free, FALSE);
3695 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
3699 * pmap_remove_pte: do the things to unmap a page in a process
3702 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
3703 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
3705 struct md_page *pvh;
3706 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
3709 PG_A = pmap_accessed_bit(pmap);
3710 PG_M = pmap_modified_bit(pmap);
3711 PG_RW = pmap_rw_bit(pmap);
3713 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3714 oldpte = pte_load_clear(ptq);
3716 pmap->pm_stats.wired_count -= 1;
3717 pmap_resident_count_dec(pmap, 1);
3718 if (oldpte & PG_MANAGED) {
3719 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
3720 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3723 vm_page_aflag_set(m, PGA_REFERENCED);
3724 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3725 pmap_pvh_free(&m->md, pmap, va);
3726 if (TAILQ_EMPTY(&m->md.pv_list) &&
3727 (m->flags & PG_FICTITIOUS) == 0) {
3728 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3729 if (TAILQ_EMPTY(&pvh->pv_list))
3730 vm_page_aflag_clear(m, PGA_WRITEABLE);
3732 pmap_delayed_invl_page(m);
3734 return (pmap_unuse_pt(pmap, va, ptepde, free));
3738 * Remove a single page from a process address space
3741 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
3742 struct spglist *free)
3744 struct rwlock *lock;
3745 pt_entry_t *pte, PG_V;
3747 PG_V = pmap_valid_bit(pmap);
3748 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3749 if ((*pde & PG_V) == 0)
3751 pte = pmap_pde_to_pte(pde, va);
3752 if ((*pte & PG_V) == 0)
3755 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
3758 pmap_invalidate_page(pmap, va);
3762 * Removes the specified range of addresses from the page table page.
3765 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
3766 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
3768 pt_entry_t PG_G, *pte;
3772 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3773 PG_G = pmap_global_bit(pmap);
3776 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
3780 pmap_invalidate_range(pmap, va, sva);
3785 if ((*pte & PG_G) == 0)
3789 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
3795 pmap_invalidate_range(pmap, va, sva);
3800 * Remove the given range of addresses from the specified map.
3802 * It is assumed that the start and end are properly
3803 * rounded to the page size.
3806 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3808 struct rwlock *lock;
3809 vm_offset_t va_next;
3810 pml4_entry_t *pml4e;
3812 pd_entry_t ptpaddr, *pde;
3813 pt_entry_t PG_G, PG_V;
3814 struct spglist free;
3817 PG_G = pmap_global_bit(pmap);
3818 PG_V = pmap_valid_bit(pmap);
3821 * Perform an unsynchronized read. This is, however, safe.
3823 if (pmap->pm_stats.resident_count == 0)
3829 pmap_delayed_invl_started();
3833 * special handling of removing one page. a very
3834 * common operation and easy to short circuit some
3837 if (sva + PAGE_SIZE == eva) {
3838 pde = pmap_pde(pmap, sva);
3839 if (pde && (*pde & PG_PS) == 0) {
3840 pmap_remove_page(pmap, sva, pde, &free);
3846 for (; sva < eva; sva = va_next) {
3848 if (pmap->pm_stats.resident_count == 0)
3851 pml4e = pmap_pml4e(pmap, sva);
3852 if ((*pml4e & PG_V) == 0) {
3853 va_next = (sva + NBPML4) & ~PML4MASK;
3859 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
3860 if ((*pdpe & PG_V) == 0) {
3861 va_next = (sva + NBPDP) & ~PDPMASK;
3868 * Calculate index for next page table.
3870 va_next = (sva + NBPDR) & ~PDRMASK;
3874 pde = pmap_pdpe_to_pde(pdpe, sva);
3878 * Weed out invalid mappings.
3884 * Check for large page.
3886 if ((ptpaddr & PG_PS) != 0) {
3888 * Are we removing the entire large page? If not,
3889 * demote the mapping and fall through.
3891 if (sva + NBPDR == va_next && eva >= va_next) {
3893 * The TLB entry for a PG_G mapping is
3894 * invalidated by pmap_remove_pde().
3896 if ((ptpaddr & PG_G) == 0)
3898 pmap_remove_pde(pmap, pde, sva, &free, &lock);
3900 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
3902 /* The large page mapping was destroyed. */
3909 * Limit our scan to either the end of the va represented
3910 * by the current page table page, or to the end of the
3911 * range being removed.
3916 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
3923 pmap_invalidate_all(pmap);
3925 pmap_delayed_invl_finished();
3926 pmap_free_zero_pages(&free);
3930 * Routine: pmap_remove_all
3932 * Removes this physical page from
3933 * all physical maps in which it resides.
3934 * Reflects back modify bits to the pager.
3937 * Original versions of this routine were very
3938 * inefficient because they iteratively called
3939 * pmap_remove (slow...)
3943 pmap_remove_all(vm_page_t m)
3945 struct md_page *pvh;
3948 struct rwlock *lock;
3949 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
3952 struct spglist free;
3953 int pvh_gen, md_gen;
3955 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3956 ("pmap_remove_all: page %p is not managed", m));
3958 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3959 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
3960 pa_to_pvh(VM_PAGE_TO_PHYS(m));
3963 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
3965 if (!PMAP_TRYLOCK(pmap)) {
3966 pvh_gen = pvh->pv_gen;
3970 if (pvh_gen != pvh->pv_gen) {
3977 pde = pmap_pde(pmap, va);
3978 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
3981 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3983 if (!PMAP_TRYLOCK(pmap)) {
3984 pvh_gen = pvh->pv_gen;
3985 md_gen = m->md.pv_gen;
3989 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
3995 PG_A = pmap_accessed_bit(pmap);
3996 PG_M = pmap_modified_bit(pmap);
3997 PG_RW = pmap_rw_bit(pmap);
3998 pmap_resident_count_dec(pmap, 1);
3999 pde = pmap_pde(pmap, pv->pv_va);
4000 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
4001 " a 2mpage in page %p's pv list", m));
4002 pte = pmap_pde_to_pte(pde, pv->pv_va);
4003 tpte = pte_load_clear(pte);
4005 pmap->pm_stats.wired_count--;
4007 vm_page_aflag_set(m, PGA_REFERENCED);
4010 * Update the vm_page_t clean and reference bits.
4012 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4014 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
4015 pmap_invalidate_page(pmap, pv->pv_va);
4016 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4018 free_pv_entry(pmap, pv);
4021 vm_page_aflag_clear(m, PGA_WRITEABLE);
4023 pmap_delayed_invl_wait(m);
4024 pmap_free_zero_pages(&free);
4028 * pmap_protect_pde: do the things to protect a 2mpage in a process
4031 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
4033 pd_entry_t newpde, oldpde;
4034 vm_offset_t eva, va;
4036 boolean_t anychanged;
4037 pt_entry_t PG_G, PG_M, PG_RW;
4039 PG_G = pmap_global_bit(pmap);
4040 PG_M = pmap_modified_bit(pmap);
4041 PG_RW = pmap_rw_bit(pmap);
4043 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4044 KASSERT((sva & PDRMASK) == 0,
4045 ("pmap_protect_pde: sva is not 2mpage aligned"));
4048 oldpde = newpde = *pde;
4049 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4050 (PG_MANAGED | PG_M | PG_RW)) {
4052 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4053 va < eva; va += PAGE_SIZE, m++)
4056 if ((prot & VM_PROT_WRITE) == 0)
4057 newpde &= ~(PG_RW | PG_M);
4058 if ((prot & VM_PROT_EXECUTE) == 0)
4060 if (newpde != oldpde) {
4062 * As an optimization to future operations on this PDE, clear
4063 * PG_PROMOTED. The impending invalidation will remove any
4064 * lingering 4KB page mappings from the TLB.
4066 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
4068 if ((oldpde & PG_G) != 0)
4069 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4073 return (anychanged);
4077 * Set the physical protection on the
4078 * specified range of this map as requested.
4081 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4083 vm_offset_t va_next;
4084 pml4_entry_t *pml4e;
4086 pd_entry_t ptpaddr, *pde;
4087 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4088 boolean_t anychanged;
4090 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4091 if (prot == VM_PROT_NONE) {
4092 pmap_remove(pmap, sva, eva);
4096 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4097 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4100 PG_G = pmap_global_bit(pmap);
4101 PG_M = pmap_modified_bit(pmap);
4102 PG_V = pmap_valid_bit(pmap);
4103 PG_RW = pmap_rw_bit(pmap);
4107 * Although this function delays and batches the invalidation
4108 * of stale TLB entries, it does not need to call
4109 * pmap_delayed_invl_started() and
4110 * pmap_delayed_invl_finished(), because it does not
4111 * ordinarily destroy mappings. Stale TLB entries from
4112 * protection-only changes need only be invalidated before the
4113 * pmap lock is released, because protection-only changes do
4114 * not destroy PV entries. Even operations that iterate over
4115 * a physical page's PV list of mappings, like
4116 * pmap_remove_write(), acquire the pmap lock for each
4117 * mapping. Consequently, for protection-only changes, the
4118 * pmap lock suffices to synchronize both page table and TLB
4121 * This function only destroys a mapping if pmap_demote_pde()
4122 * fails. In that case, stale TLB entries are immediately
4127 for (; sva < eva; sva = va_next) {
4129 pml4e = pmap_pml4e(pmap, sva);
4130 if ((*pml4e & PG_V) == 0) {
4131 va_next = (sva + NBPML4) & ~PML4MASK;
4137 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4138 if ((*pdpe & PG_V) == 0) {
4139 va_next = (sva + NBPDP) & ~PDPMASK;
4145 va_next = (sva + NBPDR) & ~PDRMASK;
4149 pde = pmap_pdpe_to_pde(pdpe, sva);
4153 * Weed out invalid mappings.
4159 * Check for large page.
4161 if ((ptpaddr & PG_PS) != 0) {
4163 * Are we protecting the entire large page? If not,
4164 * demote the mapping and fall through.
4166 if (sva + NBPDR == va_next && eva >= va_next) {
4168 * The TLB entry for a PG_G mapping is
4169 * invalidated by pmap_protect_pde().
4171 if (pmap_protect_pde(pmap, pde, sva, prot))
4174 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4176 * The large page mapping was destroyed.
4185 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4187 pt_entry_t obits, pbits;
4191 obits = pbits = *pte;
4192 if ((pbits & PG_V) == 0)
4195 if ((prot & VM_PROT_WRITE) == 0) {
4196 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4197 (PG_MANAGED | PG_M | PG_RW)) {
4198 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4201 pbits &= ~(PG_RW | PG_M);
4203 if ((prot & VM_PROT_EXECUTE) == 0)
4206 if (pbits != obits) {
4207 if (!atomic_cmpset_long(pte, obits, pbits))
4210 pmap_invalidate_page(pmap, sva);
4217 pmap_invalidate_all(pmap);
4222 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4223 * single page table page (PTP) to a single 2MB page mapping. For promotion
4224 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4225 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4226 * identical characteristics.
4229 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4230 struct rwlock **lockp)
4233 pt_entry_t *firstpte, oldpte, pa, *pte;
4234 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4238 PG_A = pmap_accessed_bit(pmap);
4239 PG_G = pmap_global_bit(pmap);
4240 PG_M = pmap_modified_bit(pmap);
4241 PG_V = pmap_valid_bit(pmap);
4242 PG_RW = pmap_rw_bit(pmap);
4243 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4245 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4248 * Examine the first PTE in the specified PTP. Abort if this PTE is
4249 * either invalid, unused, or does not map the first 4KB physical page
4250 * within a 2MB page.
4252 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4255 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4256 atomic_add_long(&pmap_pde_p_failures, 1);
4257 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4258 " in pmap %p", va, pmap);
4261 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4263 * When PG_M is already clear, PG_RW can be cleared without
4264 * a TLB invalidation.
4266 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4272 * Examine each of the other PTEs in the specified PTP. Abort if this
4273 * PTE maps an unexpected 4KB physical page or does not have identical
4274 * characteristics to the first PTE.
4276 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4277 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4280 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4281 atomic_add_long(&pmap_pde_p_failures, 1);
4282 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4283 " in pmap %p", va, pmap);
4286 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4288 * When PG_M is already clear, PG_RW can be cleared
4289 * without a TLB invalidation.
4291 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4294 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4295 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4296 (va & ~PDRMASK), pmap);
4298 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4299 atomic_add_long(&pmap_pde_p_failures, 1);
4300 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4301 " in pmap %p", va, pmap);
4308 * Save the page table page in its current state until the PDE
4309 * mapping the superpage is demoted by pmap_demote_pde() or
4310 * destroyed by pmap_remove_pde().
4312 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4313 KASSERT(mpte >= vm_page_array &&
4314 mpte < &vm_page_array[vm_page_array_size],
4315 ("pmap_promote_pde: page table page is out of range"));
4316 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4317 ("pmap_promote_pde: page table page's pindex is wrong"));
4318 if (pmap_insert_pt_page(pmap, mpte)) {
4319 atomic_add_long(&pmap_pde_p_failures, 1);
4321 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4327 * Promote the pv entries.
4329 if ((newpde & PG_MANAGED) != 0)
4330 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4333 * Propagate the PAT index to its proper position.
4335 newpde = pmap_swap_pat(pmap, newpde);
4338 * Map the superpage.
4340 if (workaround_erratum383)
4341 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4343 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
4345 atomic_add_long(&pmap_pde_promotions, 1);
4346 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4347 " in pmap %p", va, pmap);
4351 * Insert the given physical page (p) at
4352 * the specified virtual address (v) in the
4353 * target physical map with the protection requested.
4355 * If specified, the page will be wired down, meaning
4356 * that the related pte can not be reclaimed.
4358 * NB: This is the only routine which MAY NOT lazy-evaluate
4359 * or lose information. That is, this routine must actually
4360 * insert this page into the given map NOW.
4362 * When destroying both a page table and PV entry, this function
4363 * performs the TLB invalidation before releasing the PV list
4364 * lock, so we do not need pmap_delayed_invl_page() calls here.
4367 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4368 u_int flags, int8_t psind)
4370 struct rwlock *lock;
4372 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4373 pt_entry_t newpte, origpte;
4380 PG_A = pmap_accessed_bit(pmap);
4381 PG_G = pmap_global_bit(pmap);
4382 PG_M = pmap_modified_bit(pmap);
4383 PG_V = pmap_valid_bit(pmap);
4384 PG_RW = pmap_rw_bit(pmap);
4386 va = trunc_page(va);
4387 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4388 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4389 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4391 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4392 va >= kmi.clean_eva,
4393 ("pmap_enter: managed mapping within the clean submap"));
4394 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4395 VM_OBJECT_ASSERT_LOCKED(m->object);
4396 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
4397 ("pmap_enter: flags %u has reserved bits set", flags));
4398 pa = VM_PAGE_TO_PHYS(m);
4399 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4400 if ((flags & VM_PROT_WRITE) != 0)
4402 if ((prot & VM_PROT_WRITE) != 0)
4404 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4405 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4406 if ((prot & VM_PROT_EXECUTE) == 0)
4408 if ((flags & PMAP_ENTER_WIRED) != 0)
4410 if (va < VM_MAXUSER_ADDRESS)
4412 if (pmap == kernel_pmap)
4414 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
4417 * Set modified bit gratuitously for writeable mappings if
4418 * the page is unmanaged. We do not want to take a fault
4419 * to do the dirty bit accounting for these mappings.
4421 if ((m->oflags & VPO_UNMANAGED) != 0) {
4422 if ((newpte & PG_RW) != 0)
4425 newpte |= PG_MANAGED;
4430 /* Assert the required virtual and physical alignment. */
4431 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
4432 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4433 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
4439 * In the case that a page table page is not
4440 * resident, we are creating it here.
4443 pde = pmap_pde(pmap, va);
4444 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4445 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4446 pte = pmap_pde_to_pte(pde, va);
4447 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4448 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4451 } else if (va < VM_MAXUSER_ADDRESS) {
4453 * Here if the pte page isn't mapped, or if it has been
4456 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4457 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4458 nosleep ? NULL : &lock);
4459 if (mpte == NULL && nosleep) {
4460 rv = KERN_RESOURCE_SHORTAGE;
4465 panic("pmap_enter: invalid page directory va=%#lx", va);
4470 * Is the specified virtual address already mapped?
4472 if ((origpte & PG_V) != 0) {
4474 * Wiring change, just update stats. We don't worry about
4475 * wiring PT pages as they remain resident as long as there
4476 * are valid mappings in them. Hence, if a user page is wired,
4477 * the PT page will be also.
4479 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4480 pmap->pm_stats.wired_count++;
4481 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4482 pmap->pm_stats.wired_count--;
4485 * Remove the extra PT page reference.
4489 KASSERT(mpte->wire_count > 0,
4490 ("pmap_enter: missing reference to page table page,"
4495 * Has the physical page changed?
4497 opa = origpte & PG_FRAME;
4500 * No, might be a protection or wiring change.
4502 if ((origpte & PG_MANAGED) != 0 &&
4503 (newpte & PG_RW) != 0)
4504 vm_page_aflag_set(m, PGA_WRITEABLE);
4505 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4511 * Increment the counters.
4513 if ((newpte & PG_W) != 0)
4514 pmap->pm_stats.wired_count++;
4515 pmap_resident_count_inc(pmap, 1);
4519 * Enter on the PV list if part of our managed memory.
4521 if ((newpte & PG_MANAGED) != 0) {
4522 pv = get_pv_entry(pmap, &lock);
4524 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4525 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4527 if ((newpte & PG_RW) != 0)
4528 vm_page_aflag_set(m, PGA_WRITEABLE);
4534 if ((origpte & PG_V) != 0) {
4536 origpte = pte_load_store(pte, newpte);
4537 opa = origpte & PG_FRAME;
4539 if ((origpte & PG_MANAGED) != 0) {
4540 om = PHYS_TO_VM_PAGE(opa);
4541 if ((origpte & (PG_M | PG_RW)) == (PG_M |
4544 if ((origpte & PG_A) != 0)
4545 vm_page_aflag_set(om, PGA_REFERENCED);
4546 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4547 pmap_pvh_free(&om->md, pmap, va);
4548 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4549 TAILQ_EMPTY(&om->md.pv_list) &&
4550 ((om->flags & PG_FICTITIOUS) != 0 ||
4551 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4552 vm_page_aflag_clear(om, PGA_WRITEABLE);
4554 } else if ((newpte & PG_M) == 0 && (origpte & (PG_M |
4555 PG_RW)) == (PG_M | PG_RW)) {
4556 if ((origpte & PG_MANAGED) != 0)
4560 * Although the PTE may still have PG_RW set, TLB
4561 * invalidation may nonetheless be required because
4562 * the PTE no longer has PG_M set.
4564 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4566 * This PTE change does not require TLB invalidation.
4570 if ((origpte & PG_A) != 0)
4571 pmap_invalidate_page(pmap, va);
4573 pte_store(pte, newpte);
4578 * If both the page table page and the reservation are fully
4579 * populated, then attempt promotion.
4581 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4582 pmap_ps_enabled(pmap) &&
4583 (m->flags & PG_FICTITIOUS) == 0 &&
4584 vm_reserv_level_iffullpop(m) == 0)
4585 pmap_promote_pde(pmap, pde, va, &lock);
4596 * Tries to create a read- and/or execute-only 2MB page mapping. Returns true
4597 * if successful. Returns false if (1) a page table page cannot be allocated
4598 * without sleeping, (2) a mapping already exists at the specified virtual
4599 * address, or (3) a PV entry cannot be allocated without reclaiming another
4603 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4604 struct rwlock **lockp)
4609 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4610 PG_V = pmap_valid_bit(pmap);
4611 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
4613 if ((m->oflags & VPO_UNMANAGED) == 0)
4614 newpde |= PG_MANAGED;
4615 if ((prot & VM_PROT_EXECUTE) == 0)
4617 if (va < VM_MAXUSER_ADDRESS)
4619 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
4620 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
4625 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
4626 * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
4627 * otherwise. Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
4628 * a mapping already exists at the specified virtual address. Returns
4629 * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
4630 * page allocation failed. Returns KERN_RESOURCE_SHORTAGE if
4631 * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
4633 * The parameter "m" is only used when creating a managed, writeable mapping.
4636 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
4637 vm_page_t m, struct rwlock **lockp)
4639 struct spglist free;
4640 pd_entry_t oldpde, *pde;
4641 pt_entry_t PG_G, PG_RW, PG_V;
4644 PG_G = pmap_global_bit(pmap);
4645 PG_RW = pmap_rw_bit(pmap);
4646 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
4647 ("pmap_enter_pde: newpde is missing PG_M"));
4648 PG_V = pmap_valid_bit(pmap);
4649 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4651 if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
4652 NULL : lockp)) == NULL) {
4653 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4654 " in pmap %p", va, pmap);
4655 return (KERN_RESOURCE_SHORTAGE);
4657 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4658 pde = &pde[pmap_pde_index(va)];
4660 if ((oldpde & PG_V) != 0) {
4661 KASSERT(pdpg->wire_count > 1,
4662 ("pmap_enter_pde: pdpg's wire count is too low"));
4663 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
4665 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4666 " in pmap %p", va, pmap);
4667 return (KERN_FAILURE);
4669 /* Break the existing mapping(s). */
4671 if ((oldpde & PG_PS) != 0) {
4673 * The reference to the PD page that was acquired by
4674 * pmap_allocpde() ensures that it won't be freed.
4675 * However, if the PDE resulted from a promotion, then
4676 * a reserved PT page could be freed.
4678 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
4679 if ((oldpde & PG_G) == 0)
4680 pmap_invalidate_pde_page(pmap, va, oldpde);
4682 pmap_delayed_invl_started();
4683 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
4685 pmap_invalidate_all(pmap);
4686 pmap_delayed_invl_finished();
4688 pmap_free_zero_pages(&free);
4689 if (va >= VM_MAXUSER_ADDRESS) {
4690 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4691 if (pmap_insert_pt_page(pmap, mt)) {
4693 * XXX Currently, this can't happen because
4694 * we do not perform pmap_enter(psind == 1)
4695 * on the kernel pmap.
4697 panic("pmap_enter_pde: trie insert failed");
4700 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
4703 if ((newpde & PG_MANAGED) != 0) {
4705 * Abort this mapping if its PV entry could not be created.
4707 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
4709 if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
4711 * Although "va" is not mapped, paging-
4712 * structure caches could nonetheless have
4713 * entries that refer to the freed page table
4714 * pages. Invalidate those entries.
4716 pmap_invalidate_page(pmap, va);
4717 pmap_free_zero_pages(&free);
4719 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4720 " in pmap %p", va, pmap);
4721 return (KERN_RESOURCE_SHORTAGE);
4723 if ((newpde & PG_RW) != 0) {
4724 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
4725 vm_page_aflag_set(mt, PGA_WRITEABLE);
4730 * Increment counters.
4732 if ((newpde & PG_W) != 0)
4733 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
4734 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
4737 * Map the superpage. (This is not a promoted mapping; there will not
4738 * be any lingering 4KB page mappings in the TLB.)
4740 pde_store(pde, newpde);
4742 atomic_add_long(&pmap_pde_mappings, 1);
4743 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
4744 " in pmap %p", va, pmap);
4745 return (KERN_SUCCESS);
4749 * Maps a sequence of resident pages belonging to the same object.
4750 * The sequence begins with the given page m_start. This page is
4751 * mapped at the given virtual address start. Each subsequent page is
4752 * mapped at a virtual address that is offset from start by the same
4753 * amount as the page is offset from m_start within the object. The
4754 * last page in the sequence is the page with the largest offset from
4755 * m_start that can be mapped at a virtual address less than the given
4756 * virtual address end. Not every virtual page between start and end
4757 * is mapped; only those for which a resident page exists with the
4758 * corresponding offset from m_start are mapped.
4761 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
4762 vm_page_t m_start, vm_prot_t prot)
4764 struct rwlock *lock;
4767 vm_pindex_t diff, psize;
4769 VM_OBJECT_ASSERT_LOCKED(m_start->object);
4771 psize = atop(end - start);
4776 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
4777 va = start + ptoa(diff);
4778 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
4779 m->psind == 1 && pmap_ps_enabled(pmap) &&
4780 pmap_enter_2mpage(pmap, va, m, prot, &lock))
4781 m = &m[NBPDR / PAGE_SIZE - 1];
4783 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
4785 m = TAILQ_NEXT(m, listq);
4793 * this code makes some *MAJOR* assumptions:
4794 * 1. Current pmap & pmap exists.
4797 * 4. No page table pages.
4798 * but is *MUCH* faster than pmap_enter...
4802 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
4804 struct rwlock *lock;
4808 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
4815 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
4816 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
4818 struct spglist free;
4819 pt_entry_t *pte, PG_V;
4822 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
4823 (m->oflags & VPO_UNMANAGED) != 0,
4824 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
4825 PG_V = pmap_valid_bit(pmap);
4826 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4829 * In the case that a page table page is not
4830 * resident, we are creating it here.
4832 if (va < VM_MAXUSER_ADDRESS) {
4833 vm_pindex_t ptepindex;
4837 * Calculate pagetable page index
4839 ptepindex = pmap_pde_pindex(va);
4840 if (mpte && (mpte->pindex == ptepindex)) {
4844 * Get the page directory entry
4846 ptepa = pmap_pde(pmap, va);
4849 * If the page table page is mapped, we just increment
4850 * the hold count, and activate it. Otherwise, we
4851 * attempt to allocate a page table page. If this
4852 * attempt fails, we don't retry. Instead, we give up.
4854 if (ptepa && (*ptepa & PG_V) != 0) {
4857 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
4861 * Pass NULL instead of the PV list lock
4862 * pointer, because we don't intend to sleep.
4864 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
4869 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
4870 pte = &pte[pmap_pte_index(va)];
4884 * Enter on the PV list if part of our managed memory.
4886 if ((m->oflags & VPO_UNMANAGED) == 0 &&
4887 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
4890 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
4892 * Although "va" is not mapped, paging-
4893 * structure caches could nonetheless have
4894 * entries that refer to the freed page table
4895 * pages. Invalidate those entries.
4897 pmap_invalidate_page(pmap, va);
4898 pmap_free_zero_pages(&free);
4906 * Increment counters
4908 pmap_resident_count_inc(pmap, 1);
4910 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
4911 if ((prot & VM_PROT_EXECUTE) == 0)
4915 * Now validate mapping with RO protection
4917 if ((m->oflags & VPO_UNMANAGED) != 0)
4918 pte_store(pte, pa | PG_V | PG_U);
4920 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
4925 * Make a temporary mapping for a physical address. This is only intended
4926 * to be used for panic dumps.
4929 pmap_kenter_temporary(vm_paddr_t pa, int i)
4933 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
4934 pmap_kenter(va, pa);
4936 return ((void *)crashdumpmap);
4940 * This code maps large physical mmap regions into the
4941 * processor address space. Note that some shortcuts
4942 * are taken, but the code works.
4945 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
4946 vm_pindex_t pindex, vm_size_t size)
4949 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
4950 vm_paddr_t pa, ptepa;
4954 PG_A = pmap_accessed_bit(pmap);
4955 PG_M = pmap_modified_bit(pmap);
4956 PG_V = pmap_valid_bit(pmap);
4957 PG_RW = pmap_rw_bit(pmap);
4959 VM_OBJECT_ASSERT_WLOCKED(object);
4960 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
4961 ("pmap_object_init_pt: non-device object"));
4962 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
4963 if (!pmap_ps_enabled(pmap))
4965 if (!vm_object_populate(object, pindex, pindex + atop(size)))
4967 p = vm_page_lookup(object, pindex);
4968 KASSERT(p->valid == VM_PAGE_BITS_ALL,
4969 ("pmap_object_init_pt: invalid page %p", p));
4970 pat_mode = p->md.pat_mode;
4973 * Abort the mapping if the first page is not physically
4974 * aligned to a 2MB page boundary.
4976 ptepa = VM_PAGE_TO_PHYS(p);
4977 if (ptepa & (NBPDR - 1))
4981 * Skip the first page. Abort the mapping if the rest of
4982 * the pages are not physically contiguous or have differing
4983 * memory attributes.
4985 p = TAILQ_NEXT(p, listq);
4986 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
4988 KASSERT(p->valid == VM_PAGE_BITS_ALL,
4989 ("pmap_object_init_pt: invalid page %p", p));
4990 if (pa != VM_PAGE_TO_PHYS(p) ||
4991 pat_mode != p->md.pat_mode)
4993 p = TAILQ_NEXT(p, listq);
4997 * Map using 2MB pages. Since "ptepa" is 2M aligned and
4998 * "size" is a multiple of 2M, adding the PAT setting to "pa"
4999 * will not affect the termination of this loop.
5002 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
5003 pa < ptepa + size; pa += NBPDR) {
5004 pdpg = pmap_allocpde(pmap, addr, NULL);
5007 * The creation of mappings below is only an
5008 * optimization. If a page directory page
5009 * cannot be allocated without blocking,
5010 * continue on to the next mapping rather than
5016 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5017 pde = &pde[pmap_pde_index(addr)];
5018 if ((*pde & PG_V) == 0) {
5019 pde_store(pde, pa | PG_PS | PG_M | PG_A |
5020 PG_U | PG_RW | PG_V);
5021 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5022 atomic_add_long(&pmap_pde_mappings, 1);
5024 /* Continue on if the PDE is already valid. */
5026 KASSERT(pdpg->wire_count > 0,
5027 ("pmap_object_init_pt: missing reference "
5028 "to page directory page, va: 0x%lx", addr));
5037 * Clear the wired attribute from the mappings for the specified range of
5038 * addresses in the given pmap. Every valid mapping within that range
5039 * must have the wired attribute set. In contrast, invalid mappings
5040 * cannot have the wired attribute set, so they are ignored.
5042 * The wired attribute of the page table entry is not a hardware
5043 * feature, so there is no need to invalidate any TLB entries.
5044 * Since pmap_demote_pde() for the wired entry must never fail,
5045 * pmap_delayed_invl_started()/finished() calls around the
5046 * function are not needed.
5049 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5051 vm_offset_t va_next;
5052 pml4_entry_t *pml4e;
5055 pt_entry_t *pte, PG_V;
5057 PG_V = pmap_valid_bit(pmap);
5059 for (; sva < eva; sva = va_next) {
5060 pml4e = pmap_pml4e(pmap, sva);
5061 if ((*pml4e & PG_V) == 0) {
5062 va_next = (sva + NBPML4) & ~PML4MASK;
5067 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5068 if ((*pdpe & PG_V) == 0) {
5069 va_next = (sva + NBPDP) & ~PDPMASK;
5074 va_next = (sva + NBPDR) & ~PDRMASK;
5077 pde = pmap_pdpe_to_pde(pdpe, sva);
5078 if ((*pde & PG_V) == 0)
5080 if ((*pde & PG_PS) != 0) {
5081 if ((*pde & PG_W) == 0)
5082 panic("pmap_unwire: pde %#jx is missing PG_W",
5086 * Are we unwiring the entire large page? If not,
5087 * demote the mapping and fall through.
5089 if (sva + NBPDR == va_next && eva >= va_next) {
5090 atomic_clear_long(pde, PG_W);
5091 pmap->pm_stats.wired_count -= NBPDR /
5094 } else if (!pmap_demote_pde(pmap, pde, sva))
5095 panic("pmap_unwire: demotion failed");
5099 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
5101 if ((*pte & PG_V) == 0)
5103 if ((*pte & PG_W) == 0)
5104 panic("pmap_unwire: pte %#jx is missing PG_W",
5108 * PG_W must be cleared atomically. Although the pmap
5109 * lock synchronizes access to PG_W, another processor
5110 * could be setting PG_M and/or PG_A concurrently.
5112 atomic_clear_long(pte, PG_W);
5113 pmap->pm_stats.wired_count--;
5120 * Copy the range specified by src_addr/len
5121 * from the source map to the range dst_addr/len
5122 * in the destination map.
5124 * This routine is only advisory and need not do anything.
5128 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5129 vm_offset_t src_addr)
5131 struct rwlock *lock;
5132 struct spglist free;
5134 vm_offset_t end_addr = src_addr + len;
5135 vm_offset_t va_next;
5136 vm_page_t dst_pdpg, dstmpte, srcmpte;
5137 pt_entry_t PG_A, PG_M, PG_V;
5139 if (dst_addr != src_addr)
5142 if (dst_pmap->pm_type != src_pmap->pm_type)
5146 * EPT page table entries that require emulation of A/D bits are
5147 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5148 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5149 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5150 * implementations flag an EPT misconfiguration for exec-only
5151 * mappings we skip this function entirely for emulated pmaps.
5153 if (pmap_emulate_ad_bits(dst_pmap))
5157 if (dst_pmap < src_pmap) {
5158 PMAP_LOCK(dst_pmap);
5159 PMAP_LOCK(src_pmap);
5161 PMAP_LOCK(src_pmap);
5162 PMAP_LOCK(dst_pmap);
5165 PG_A = pmap_accessed_bit(dst_pmap);
5166 PG_M = pmap_modified_bit(dst_pmap);
5167 PG_V = pmap_valid_bit(dst_pmap);
5169 for (addr = src_addr; addr < end_addr; addr = va_next) {
5170 pt_entry_t *src_pte, *dst_pte;
5171 pml4_entry_t *pml4e;
5173 pd_entry_t srcptepaddr, *pde;
5175 KASSERT(addr < UPT_MIN_ADDRESS,
5176 ("pmap_copy: invalid to pmap_copy page tables"));
5178 pml4e = pmap_pml4e(src_pmap, addr);
5179 if ((*pml4e & PG_V) == 0) {
5180 va_next = (addr + NBPML4) & ~PML4MASK;
5186 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5187 if ((*pdpe & PG_V) == 0) {
5188 va_next = (addr + NBPDP) & ~PDPMASK;
5194 va_next = (addr + NBPDR) & ~PDRMASK;
5198 pde = pmap_pdpe_to_pde(pdpe, addr);
5200 if (srcptepaddr == 0)
5203 if (srcptepaddr & PG_PS) {
5204 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5206 dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
5207 if (dst_pdpg == NULL)
5209 pde = (pd_entry_t *)
5210 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
5211 pde = &pde[pmap_pde_index(addr)];
5212 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5213 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
5214 PMAP_ENTER_NORECLAIM, &lock))) {
5215 *pde = srcptepaddr & ~PG_W;
5216 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5217 atomic_add_long(&pmap_pde_mappings, 1);
5219 dst_pdpg->wire_count--;
5223 srcptepaddr &= PG_FRAME;
5224 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5225 KASSERT(srcmpte->wire_count > 0,
5226 ("pmap_copy: source page table page is unused"));
5228 if (va_next > end_addr)
5231 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5232 src_pte = &src_pte[pmap_pte_index(addr)];
5234 while (addr < va_next) {
5238 * we only virtual copy managed pages
5240 if ((ptetemp & PG_MANAGED) != 0) {
5241 if (dstmpte != NULL &&
5242 dstmpte->pindex == pmap_pde_pindex(addr))
5243 dstmpte->wire_count++;
5244 else if ((dstmpte = pmap_allocpte(dst_pmap,
5245 addr, NULL)) == NULL)
5247 dst_pte = (pt_entry_t *)
5248 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5249 dst_pte = &dst_pte[pmap_pte_index(addr)];
5250 if (*dst_pte == 0 &&
5251 pmap_try_insert_pv_entry(dst_pmap, addr,
5252 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5255 * Clear the wired, modified, and
5256 * accessed (referenced) bits
5259 *dst_pte = ptetemp & ~(PG_W | PG_M |
5261 pmap_resident_count_inc(dst_pmap, 1);
5264 if (pmap_unwire_ptp(dst_pmap, addr,
5267 * Although "addr" is not
5268 * mapped, paging-structure
5269 * caches could nonetheless
5270 * have entries that refer to
5271 * the freed page table pages.
5272 * Invalidate those entries.
5274 pmap_invalidate_page(dst_pmap,
5276 pmap_free_zero_pages(&free);
5280 if (dstmpte->wire_count >= srcmpte->wire_count)
5290 PMAP_UNLOCK(src_pmap);
5291 PMAP_UNLOCK(dst_pmap);
5295 * Zero the specified hardware page.
5298 pmap_zero_page(vm_page_t m)
5300 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5302 pagezero((void *)va);
5306 * Zero an an area within a single hardware page. off and size must not
5307 * cover an area beyond a single hardware page.
5310 pmap_zero_page_area(vm_page_t m, int off, int size)
5312 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5314 if (off == 0 && size == PAGE_SIZE)
5315 pagezero((void *)va);
5317 bzero((char *)va + off, size);
5321 * Copy 1 specified hardware page to another.
5324 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5326 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5327 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5329 pagecopy((void *)src, (void *)dst);
5332 int unmapped_buf_allowed = 1;
5335 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5336 vm_offset_t b_offset, int xfersize)
5340 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5344 while (xfersize > 0) {
5345 a_pg_offset = a_offset & PAGE_MASK;
5346 pages[0] = ma[a_offset >> PAGE_SHIFT];
5347 b_pg_offset = b_offset & PAGE_MASK;
5348 pages[1] = mb[b_offset >> PAGE_SHIFT];
5349 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5350 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5351 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5352 a_cp = (char *)vaddr[0] + a_pg_offset;
5353 b_cp = (char *)vaddr[1] + b_pg_offset;
5354 bcopy(a_cp, b_cp, cnt);
5355 if (__predict_false(mapped))
5356 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5364 * Returns true if the pmap's pv is one of the first
5365 * 16 pvs linked to from this page. This count may
5366 * be changed upwards or downwards in the future; it
5367 * is only necessary that true be returned for a small
5368 * subset of pmaps for proper page aging.
5371 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5373 struct md_page *pvh;
5374 struct rwlock *lock;
5379 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5380 ("pmap_page_exists_quick: page %p is not managed", m));
5382 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5384 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5385 if (PV_PMAP(pv) == pmap) {
5393 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5394 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5395 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5396 if (PV_PMAP(pv) == pmap) {
5410 * pmap_page_wired_mappings:
5412 * Return the number of managed mappings to the given physical page
5416 pmap_page_wired_mappings(vm_page_t m)
5418 struct rwlock *lock;
5419 struct md_page *pvh;
5423 int count, md_gen, pvh_gen;
5425 if ((m->oflags & VPO_UNMANAGED) != 0)
5427 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5431 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5433 if (!PMAP_TRYLOCK(pmap)) {
5434 md_gen = m->md.pv_gen;
5438 if (md_gen != m->md.pv_gen) {
5443 pte = pmap_pte(pmap, pv->pv_va);
5444 if ((*pte & PG_W) != 0)
5448 if ((m->flags & PG_FICTITIOUS) == 0) {
5449 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5450 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5452 if (!PMAP_TRYLOCK(pmap)) {
5453 md_gen = m->md.pv_gen;
5454 pvh_gen = pvh->pv_gen;
5458 if (md_gen != m->md.pv_gen ||
5459 pvh_gen != pvh->pv_gen) {
5464 pte = pmap_pde(pmap, pv->pv_va);
5465 if ((*pte & PG_W) != 0)
5475 * Returns TRUE if the given page is mapped individually or as part of
5476 * a 2mpage. Otherwise, returns FALSE.
5479 pmap_page_is_mapped(vm_page_t m)
5481 struct rwlock *lock;
5484 if ((m->oflags & VPO_UNMANAGED) != 0)
5486 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5488 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5489 ((m->flags & PG_FICTITIOUS) == 0 &&
5490 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5496 * Destroy all managed, non-wired mappings in the given user-space
5497 * pmap. This pmap cannot be active on any processor besides the
5500 * This function cannot be applied to the kernel pmap. Moreover, it
5501 * is not intended for general use. It is only to be used during
5502 * process termination. Consequently, it can be implemented in ways
5503 * that make it faster than pmap_remove(). First, it can more quickly
5504 * destroy mappings by iterating over the pmap's collection of PV
5505 * entries, rather than searching the page table. Second, it doesn't
5506 * have to test and clear the page table entries atomically, because
5507 * no processor is currently accessing the user address space. In
5508 * particular, a page table entry's dirty bit won't change state once
5509 * this function starts.
5511 * Although this function destroys all of the pmap's managed,
5512 * non-wired mappings, it can delay and batch the invalidation of TLB
5513 * entries without calling pmap_delayed_invl_started() and
5514 * pmap_delayed_invl_finished(). Because the pmap is not active on
5515 * any other processor, none of these TLB entries will ever be used
5516 * before their eventual invalidation. Consequently, there is no need
5517 * for either pmap_remove_all() or pmap_remove_write() to wait for
5518 * that eventual TLB invalidation.
5521 pmap_remove_pages(pmap_t pmap)
5524 pt_entry_t *pte, tpte;
5525 pt_entry_t PG_M, PG_RW, PG_V;
5526 struct spglist free;
5527 vm_page_t m, mpte, mt;
5529 struct md_page *pvh;
5530 struct pv_chunk *pc, *npc;
5531 struct rwlock *lock;
5533 uint64_t inuse, bitmask;
5534 int allfree, field, freed, idx;
5535 boolean_t superpage;
5539 * Assert that the given pmap is only active on the current
5540 * CPU. Unfortunately, we cannot block another CPU from
5541 * activating the pmap while this function is executing.
5543 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5546 cpuset_t other_cpus;
5548 other_cpus = all_cpus;
5550 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5551 CPU_AND(&other_cpus, &pmap->pm_active);
5553 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5558 PG_M = pmap_modified_bit(pmap);
5559 PG_V = pmap_valid_bit(pmap);
5560 PG_RW = pmap_rw_bit(pmap);
5564 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5567 for (field = 0; field < _NPCM; field++) {
5568 inuse = ~pc->pc_map[field] & pc_freemask[field];
5569 while (inuse != 0) {
5571 bitmask = 1UL << bit;
5572 idx = field * 64 + bit;
5573 pv = &pc->pc_pventry[idx];
5576 pte = pmap_pdpe(pmap, pv->pv_va);
5578 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5580 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5583 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5585 pte = &pte[pmap_pte_index(pv->pv_va)];
5589 * Keep track whether 'tpte' is a
5590 * superpage explicitly instead of
5591 * relying on PG_PS being set.
5593 * This is because PG_PS is numerically
5594 * identical to PG_PTE_PAT and thus a
5595 * regular page could be mistaken for
5601 if ((tpte & PG_V) == 0) {
5602 panic("bad pte va %lx pte %lx",
5607 * We cannot remove wired pages from a process' mapping at this time
5615 pa = tpte & PG_PS_FRAME;
5617 pa = tpte & PG_FRAME;
5619 m = PHYS_TO_VM_PAGE(pa);
5620 KASSERT(m->phys_addr == pa,
5621 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5622 m, (uintmax_t)m->phys_addr,
5625 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5626 m < &vm_page_array[vm_page_array_size],
5627 ("pmap_remove_pages: bad tpte %#jx",
5633 * Update the vm_page_t clean/reference bits.
5635 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5637 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5643 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5646 pc->pc_map[field] |= bitmask;
5648 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
5649 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
5650 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5652 if (TAILQ_EMPTY(&pvh->pv_list)) {
5653 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5654 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
5655 TAILQ_EMPTY(&mt->md.pv_list))
5656 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5658 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
5660 pmap_resident_count_dec(pmap, 1);
5661 KASSERT(mpte->wire_count == NPTEPG,
5662 ("pmap_remove_pages: pte page wire count error"));
5663 mpte->wire_count = 0;
5664 pmap_add_delayed_free_list(mpte, &free, FALSE);
5667 pmap_resident_count_dec(pmap, 1);
5668 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5670 if ((m->aflags & PGA_WRITEABLE) != 0 &&
5671 TAILQ_EMPTY(&m->md.pv_list) &&
5672 (m->flags & PG_FICTITIOUS) == 0) {
5673 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5674 if (TAILQ_EMPTY(&pvh->pv_list))
5675 vm_page_aflag_clear(m, PGA_WRITEABLE);
5678 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
5682 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5683 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5684 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5686 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5692 pmap_invalidate_all(pmap);
5694 pmap_free_zero_pages(&free);
5698 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
5700 struct rwlock *lock;
5702 struct md_page *pvh;
5703 pt_entry_t *pte, mask;
5704 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5706 int md_gen, pvh_gen;
5710 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5713 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5715 if (!PMAP_TRYLOCK(pmap)) {
5716 md_gen = m->md.pv_gen;
5720 if (md_gen != m->md.pv_gen) {
5725 pte = pmap_pte(pmap, pv->pv_va);
5728 PG_M = pmap_modified_bit(pmap);
5729 PG_RW = pmap_rw_bit(pmap);
5730 mask |= PG_RW | PG_M;
5733 PG_A = pmap_accessed_bit(pmap);
5734 PG_V = pmap_valid_bit(pmap);
5735 mask |= PG_V | PG_A;
5737 rv = (*pte & mask) == mask;
5742 if ((m->flags & PG_FICTITIOUS) == 0) {
5743 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5744 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5746 if (!PMAP_TRYLOCK(pmap)) {
5747 md_gen = m->md.pv_gen;
5748 pvh_gen = pvh->pv_gen;
5752 if (md_gen != m->md.pv_gen ||
5753 pvh_gen != pvh->pv_gen) {
5758 pte = pmap_pde(pmap, pv->pv_va);
5761 PG_M = pmap_modified_bit(pmap);
5762 PG_RW = pmap_rw_bit(pmap);
5763 mask |= PG_RW | PG_M;
5766 PG_A = pmap_accessed_bit(pmap);
5767 PG_V = pmap_valid_bit(pmap);
5768 mask |= PG_V | PG_A;
5770 rv = (*pte & mask) == mask;
5784 * Return whether or not the specified physical page was modified
5785 * in any physical maps.
5788 pmap_is_modified(vm_page_t m)
5791 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5792 ("pmap_is_modified: page %p is not managed", m));
5795 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5796 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
5797 * is clear, no PTEs can have PG_M set.
5799 VM_OBJECT_ASSERT_WLOCKED(m->object);
5800 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
5802 return (pmap_page_test_mappings(m, FALSE, TRUE));
5806 * pmap_is_prefaultable:
5808 * Return whether or not the specified virtual address is eligible
5812 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
5815 pt_entry_t *pte, PG_V;
5818 PG_V = pmap_valid_bit(pmap);
5821 pde = pmap_pde(pmap, addr);
5822 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
5823 pte = pmap_pde_to_pte(pde, addr);
5824 rv = (*pte & PG_V) == 0;
5831 * pmap_is_referenced:
5833 * Return whether or not the specified physical page was referenced
5834 * in any physical maps.
5837 pmap_is_referenced(vm_page_t m)
5840 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5841 ("pmap_is_referenced: page %p is not managed", m));
5842 return (pmap_page_test_mappings(m, TRUE, FALSE));
5846 * Clear the write and modified bits in each of the given page's mappings.
5849 pmap_remove_write(vm_page_t m)
5851 struct md_page *pvh;
5853 struct rwlock *lock;
5854 pv_entry_t next_pv, pv;
5856 pt_entry_t oldpte, *pte, PG_M, PG_RW;
5858 int pvh_gen, md_gen;
5860 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5861 ("pmap_remove_write: page %p is not managed", m));
5864 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5865 * set by another thread while the object is locked. Thus,
5866 * if PGA_WRITEABLE is clear, no page table entries need updating.
5868 VM_OBJECT_ASSERT_WLOCKED(m->object);
5869 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
5871 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5872 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
5873 pa_to_pvh(VM_PAGE_TO_PHYS(m));
5876 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
5878 if (!PMAP_TRYLOCK(pmap)) {
5879 pvh_gen = pvh->pv_gen;
5883 if (pvh_gen != pvh->pv_gen) {
5889 PG_RW = pmap_rw_bit(pmap);
5891 pde = pmap_pde(pmap, va);
5892 if ((*pde & PG_RW) != 0)
5893 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
5894 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
5895 ("inconsistent pv lock %p %p for page %p",
5896 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
5899 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5901 if (!PMAP_TRYLOCK(pmap)) {
5902 pvh_gen = pvh->pv_gen;
5903 md_gen = m->md.pv_gen;
5907 if (pvh_gen != pvh->pv_gen ||
5908 md_gen != m->md.pv_gen) {
5914 PG_M = pmap_modified_bit(pmap);
5915 PG_RW = pmap_rw_bit(pmap);
5916 pde = pmap_pde(pmap, pv->pv_va);
5917 KASSERT((*pde & PG_PS) == 0,
5918 ("pmap_remove_write: found a 2mpage in page %p's pv list",
5920 pte = pmap_pde_to_pte(pde, pv->pv_va);
5923 if (oldpte & PG_RW) {
5924 if (!atomic_cmpset_long(pte, oldpte, oldpte &
5927 if ((oldpte & PG_M) != 0)
5929 pmap_invalidate_page(pmap, pv->pv_va);
5934 vm_page_aflag_clear(m, PGA_WRITEABLE);
5935 pmap_delayed_invl_wait(m);
5938 static __inline boolean_t
5939 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
5942 if (!pmap_emulate_ad_bits(pmap))
5945 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
5948 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
5949 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
5950 * if the EPT_PG_WRITE bit is set.
5952 if ((pte & EPT_PG_WRITE) != 0)
5956 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
5958 if ((pte & EPT_PG_EXECUTE) == 0 ||
5959 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
5966 * pmap_ts_referenced:
5968 * Return a count of reference bits for a page, clearing those bits.
5969 * It is not necessary for every reference bit to be cleared, but it
5970 * is necessary that 0 only be returned when there are truly no
5971 * reference bits set.
5973 * As an optimization, update the page's dirty field if a modified bit is
5974 * found while counting reference bits. This opportunistic update can be
5975 * performed at low cost and can eliminate the need for some future calls
5976 * to pmap_is_modified(). However, since this function stops after
5977 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
5978 * dirty pages. Those dirty pages will only be detected by a future call
5979 * to pmap_is_modified().
5981 * A DI block is not needed within this function, because
5982 * invalidations are performed before the PV list lock is
5986 pmap_ts_referenced(vm_page_t m)
5988 struct md_page *pvh;
5991 struct rwlock *lock;
5992 pd_entry_t oldpde, *pde;
5993 pt_entry_t *pte, PG_A, PG_M, PG_RW;
5996 int cleared, md_gen, not_cleared, pvh_gen;
5997 struct spglist free;
6000 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6001 ("pmap_ts_referenced: page %p is not managed", m));
6004 pa = VM_PAGE_TO_PHYS(m);
6005 lock = PHYS_TO_PV_LIST_LOCK(pa);
6006 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
6010 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6011 goto small_mappings;
6017 if (!PMAP_TRYLOCK(pmap)) {
6018 pvh_gen = pvh->pv_gen;
6022 if (pvh_gen != pvh->pv_gen) {
6027 PG_A = pmap_accessed_bit(pmap);
6028 PG_M = pmap_modified_bit(pmap);
6029 PG_RW = pmap_rw_bit(pmap);
6031 pde = pmap_pde(pmap, pv->pv_va);
6033 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6035 * Although "oldpde" is mapping a 2MB page, because
6036 * this function is called at a 4KB page granularity,
6037 * we only update the 4KB page under test.
6041 if ((oldpde & PG_A) != 0) {
6043 * Since this reference bit is shared by 512 4KB
6044 * pages, it should not be cleared every time it is
6045 * tested. Apply a simple "hash" function on the
6046 * physical page number, the virtual superpage number,
6047 * and the pmap address to select one 4KB page out of
6048 * the 512 on which testing the reference bit will
6049 * result in clearing that reference bit. This
6050 * function is designed to avoid the selection of the
6051 * same 4KB page for every 2MB page mapping.
6053 * On demotion, a mapping that hasn't been referenced
6054 * is simply destroyed. To avoid the possibility of a
6055 * subsequent page fault on a demoted wired mapping,
6056 * always leave its reference bit set. Moreover,
6057 * since the superpage is wired, the current state of
6058 * its reference bit won't affect page replacement.
6060 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
6061 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
6062 (oldpde & PG_W) == 0) {
6063 if (safe_to_clear_referenced(pmap, oldpde)) {
6064 atomic_clear_long(pde, PG_A);
6065 pmap_invalidate_page(pmap, pv->pv_va);
6067 } else if (pmap_demote_pde_locked(pmap, pde,
6068 pv->pv_va, &lock)) {
6070 * Remove the mapping to a single page
6071 * so that a subsequent access may
6072 * repromote. Since the underlying
6073 * page table page is fully populated,
6074 * this removal never frees a page
6078 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6080 pte = pmap_pde_to_pte(pde, va);
6081 pmap_remove_pte(pmap, pte, va, *pde,
6083 pmap_invalidate_page(pmap, va);
6089 * The superpage mapping was removed
6090 * entirely and therefore 'pv' is no
6098 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6099 ("inconsistent pv lock %p %p for page %p",
6100 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6105 /* Rotate the PV list if it has more than one entry. */
6106 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6107 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6108 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6111 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6113 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6115 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6122 if (!PMAP_TRYLOCK(pmap)) {
6123 pvh_gen = pvh->pv_gen;
6124 md_gen = m->md.pv_gen;
6128 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6133 PG_A = pmap_accessed_bit(pmap);
6134 PG_M = pmap_modified_bit(pmap);
6135 PG_RW = pmap_rw_bit(pmap);
6136 pde = pmap_pde(pmap, pv->pv_va);
6137 KASSERT((*pde & PG_PS) == 0,
6138 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6140 pte = pmap_pde_to_pte(pde, pv->pv_va);
6141 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6143 if ((*pte & PG_A) != 0) {
6144 if (safe_to_clear_referenced(pmap, *pte)) {
6145 atomic_clear_long(pte, PG_A);
6146 pmap_invalidate_page(pmap, pv->pv_va);
6148 } else if ((*pte & PG_W) == 0) {
6150 * Wired pages cannot be paged out so
6151 * doing accessed bit emulation for
6152 * them is wasted effort. We do the
6153 * hard work for unwired pages only.
6155 pmap_remove_pte(pmap, pte, pv->pv_va,
6156 *pde, &free, &lock);
6157 pmap_invalidate_page(pmap, pv->pv_va);
6162 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6163 ("inconsistent pv lock %p %p for page %p",
6164 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6169 /* Rotate the PV list if it has more than one entry. */
6170 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6171 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6172 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6175 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6176 not_cleared < PMAP_TS_REFERENCED_MAX);
6179 pmap_free_zero_pages(&free);
6180 return (cleared + not_cleared);
6184 * Apply the given advice to the specified range of addresses within the
6185 * given pmap. Depending on the advice, clear the referenced and/or
6186 * modified flags in each mapping and set the mapped page's dirty field.
6189 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6191 struct rwlock *lock;
6192 pml4_entry_t *pml4e;
6194 pd_entry_t oldpde, *pde;
6195 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6196 vm_offset_t va, va_next;
6198 boolean_t anychanged;
6200 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6204 * A/D bit emulation requires an alternate code path when clearing
6205 * the modified and accessed bits below. Since this function is
6206 * advisory in nature we skip it entirely for pmaps that require
6207 * A/D bit emulation.
6209 if (pmap_emulate_ad_bits(pmap))
6212 PG_A = pmap_accessed_bit(pmap);
6213 PG_G = pmap_global_bit(pmap);
6214 PG_M = pmap_modified_bit(pmap);
6215 PG_V = pmap_valid_bit(pmap);
6216 PG_RW = pmap_rw_bit(pmap);
6218 pmap_delayed_invl_started();
6220 for (; sva < eva; sva = va_next) {
6221 pml4e = pmap_pml4e(pmap, sva);
6222 if ((*pml4e & PG_V) == 0) {
6223 va_next = (sva + NBPML4) & ~PML4MASK;
6228 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6229 if ((*pdpe & PG_V) == 0) {
6230 va_next = (sva + NBPDP) & ~PDPMASK;
6235 va_next = (sva + NBPDR) & ~PDRMASK;
6238 pde = pmap_pdpe_to_pde(pdpe, sva);
6240 if ((oldpde & PG_V) == 0)
6242 else if ((oldpde & PG_PS) != 0) {
6243 if ((oldpde & PG_MANAGED) == 0)
6246 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6251 * The large page mapping was destroyed.
6257 * Unless the page mappings are wired, remove the
6258 * mapping to a single page so that a subsequent
6259 * access may repromote. Since the underlying page
6260 * table page is fully populated, this removal never
6261 * frees a page table page.
6263 if ((oldpde & PG_W) == 0) {
6264 pte = pmap_pde_to_pte(pde, sva);
6265 KASSERT((*pte & PG_V) != 0,
6266 ("pmap_advise: invalid PTE"));
6267 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6277 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6279 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6281 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6282 if (advice == MADV_DONTNEED) {
6284 * Future calls to pmap_is_modified()
6285 * can be avoided by making the page
6288 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6291 atomic_clear_long(pte, PG_M | PG_A);
6292 } else if ((*pte & PG_A) != 0)
6293 atomic_clear_long(pte, PG_A);
6297 if ((*pte & PG_G) != 0) {
6304 if (va != va_next) {
6305 pmap_invalidate_range(pmap, va, sva);
6310 pmap_invalidate_range(pmap, va, sva);
6313 pmap_invalidate_all(pmap);
6315 pmap_delayed_invl_finished();
6319 * Clear the modify bits on the specified physical page.
6322 pmap_clear_modify(vm_page_t m)
6324 struct md_page *pvh;
6326 pv_entry_t next_pv, pv;
6327 pd_entry_t oldpde, *pde;
6328 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6329 struct rwlock *lock;
6331 int md_gen, pvh_gen;
6333 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6334 ("pmap_clear_modify: page %p is not managed", m));
6335 VM_OBJECT_ASSERT_WLOCKED(m->object);
6336 KASSERT(!vm_page_xbusied(m),
6337 ("pmap_clear_modify: page %p is exclusive busied", m));
6340 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6341 * If the object containing the page is locked and the page is not
6342 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6344 if ((m->aflags & PGA_WRITEABLE) == 0)
6346 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6347 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6348 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6351 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6353 if (!PMAP_TRYLOCK(pmap)) {
6354 pvh_gen = pvh->pv_gen;
6358 if (pvh_gen != pvh->pv_gen) {
6363 PG_M = pmap_modified_bit(pmap);
6364 PG_V = pmap_valid_bit(pmap);
6365 PG_RW = pmap_rw_bit(pmap);
6367 pde = pmap_pde(pmap, va);
6369 if ((oldpde & PG_RW) != 0) {
6370 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6371 if ((oldpde & PG_W) == 0) {
6373 * Write protect the mapping to a
6374 * single page so that a subsequent
6375 * write access may repromote.
6377 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6379 pte = pmap_pde_to_pte(pde, va);
6381 if ((oldpte & PG_V) != 0) {
6382 while (!atomic_cmpset_long(pte,
6384 oldpte & ~(PG_M | PG_RW)))
6387 pmap_invalidate_page(pmap, va);
6394 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6396 if (!PMAP_TRYLOCK(pmap)) {
6397 md_gen = m->md.pv_gen;
6398 pvh_gen = pvh->pv_gen;
6402 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6407 PG_M = pmap_modified_bit(pmap);
6408 PG_RW = pmap_rw_bit(pmap);
6409 pde = pmap_pde(pmap, pv->pv_va);
6410 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6411 " a 2mpage in page %p's pv list", m));
6412 pte = pmap_pde_to_pte(pde, pv->pv_va);
6413 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6414 atomic_clear_long(pte, PG_M);
6415 pmap_invalidate_page(pmap, pv->pv_va);
6423 * Miscellaneous support routines follow
6426 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6427 static __inline void
6428 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6433 * The cache mode bits are all in the low 32-bits of the
6434 * PTE, so we can just spin on updating the low 32-bits.
6437 opte = *(u_int *)pte;
6438 npte = opte & ~mask;
6440 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6443 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6444 static __inline void
6445 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6450 * The cache mode bits are all in the low 32-bits of the
6451 * PDE, so we can just spin on updating the low 32-bits.
6454 opde = *(u_int *)pde;
6455 npde = opde & ~mask;
6457 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6461 * Map a set of physical memory pages into the kernel virtual
6462 * address space. Return a pointer to where it is mapped. This
6463 * routine is intended to be used for mapping device memory,
6467 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6469 struct pmap_preinit_mapping *ppim;
6470 vm_offset_t va, offset;
6474 offset = pa & PAGE_MASK;
6475 size = round_page(offset + size);
6476 pa = trunc_page(pa);
6478 if (!pmap_initialized) {
6480 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6481 ppim = pmap_preinit_mapping + i;
6482 if (ppim->va == 0) {
6486 ppim->va = virtual_avail;
6487 virtual_avail += size;
6493 panic("%s: too many preinit mappings", __func__);
6496 * If we have a preinit mapping, re-use it.
6498 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6499 ppim = pmap_preinit_mapping + i;
6500 if (ppim->pa == pa && ppim->sz == size &&
6502 return ((void *)(ppim->va + offset));
6505 * If the specified range of physical addresses fits within
6506 * the direct map window, use the direct map.
6508 if (pa < dmaplimit && pa + size < dmaplimit) {
6509 va = PHYS_TO_DMAP(pa);
6510 if (!pmap_change_attr(va, size, mode))
6511 return ((void *)(va + offset));
6513 va = kva_alloc(size);
6515 panic("%s: Couldn't allocate KVA", __func__);
6517 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6518 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6519 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6520 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6521 return ((void *)(va + offset));
6525 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6528 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6532 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6535 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6539 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6541 struct pmap_preinit_mapping *ppim;
6545 /* If we gave a direct map region in pmap_mapdev, do nothing */
6546 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6548 offset = va & PAGE_MASK;
6549 size = round_page(offset + size);
6550 va = trunc_page(va);
6551 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6552 ppim = pmap_preinit_mapping + i;
6553 if (ppim->va == va && ppim->sz == size) {
6554 if (pmap_initialized)
6560 if (va + size == virtual_avail)
6565 if (pmap_initialized)
6570 * Tries to demote a 1GB page mapping.
6573 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6575 pdp_entry_t newpdpe, oldpdpe;
6576 pd_entry_t *firstpde, newpde, *pde;
6577 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6581 PG_A = pmap_accessed_bit(pmap);
6582 PG_M = pmap_modified_bit(pmap);
6583 PG_V = pmap_valid_bit(pmap);
6584 PG_RW = pmap_rw_bit(pmap);
6586 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6588 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6589 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6590 if ((pdpg = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6591 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6592 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6593 " in pmap %p", va, pmap);
6596 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
6597 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
6598 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6599 KASSERT((oldpdpe & PG_A) != 0,
6600 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6601 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6602 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
6606 * Initialize the page directory page.
6608 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
6614 * Demote the mapping.
6619 * Invalidate a stale recursive mapping of the page directory page.
6621 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
6623 pmap_pdpe_demotions++;
6624 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
6625 " in pmap %p", va, pmap);
6630 * Sets the memory attribute for the specified page.
6633 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6636 m->md.pat_mode = ma;
6639 * If "m" is a normal page, update its direct mapping. This update
6640 * can be relied upon to perform any cache operations that are
6641 * required for data coherence.
6643 if ((m->flags & PG_FICTITIOUS) == 0 &&
6644 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6646 panic("memory attribute change on the direct map failed");
6650 * Changes the specified virtual address range's memory type to that given by
6651 * the parameter "mode". The specified virtual address range must be
6652 * completely contained within either the direct map or the kernel map. If
6653 * the virtual address range is contained within the kernel map, then the
6654 * memory type for each of the corresponding ranges of the direct map is also
6655 * changed. (The corresponding ranges of the direct map are those ranges that
6656 * map the same physical pages as the specified virtual address range.) These
6657 * changes to the direct map are necessary because Intel describes the
6658 * behavior of their processors as "undefined" if two or more mappings to the
6659 * same physical page have different memory types.
6661 * Returns zero if the change completed successfully, and either EINVAL or
6662 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6663 * of the virtual address range was not mapped, and ENOMEM is returned if
6664 * there was insufficient memory available to complete the change. In the
6665 * latter case, the memory type may have been changed on some part of the
6666 * virtual address range or the direct map.
6669 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6673 PMAP_LOCK(kernel_pmap);
6674 error = pmap_change_attr_locked(va, size, mode);
6675 PMAP_UNLOCK(kernel_pmap);
6680 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
6682 vm_offset_t base, offset, tmpva;
6683 vm_paddr_t pa_start, pa_end, pa_end1;
6687 int cache_bits_pte, cache_bits_pde, error;
6690 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6691 base = trunc_page(va);
6692 offset = va & PAGE_MASK;
6693 size = round_page(offset + size);
6696 * Only supported on kernel virtual addresses, including the direct
6697 * map but excluding the recursive map.
6699 if (base < DMAP_MIN_ADDRESS)
6702 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
6703 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
6707 * Pages that aren't mapped aren't supported. Also break down 2MB pages
6708 * into 4KB pages if required.
6710 for (tmpva = base; tmpva < base + size; ) {
6711 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6712 if (pdpe == NULL || *pdpe == 0)
6714 if (*pdpe & PG_PS) {
6716 * If the current 1GB page already has the required
6717 * memory type, then we need not demote this page. Just
6718 * increment tmpva to the next 1GB page frame.
6720 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
6721 tmpva = trunc_1gpage(tmpva) + NBPDP;
6726 * If the current offset aligns with a 1GB page frame
6727 * and there is at least 1GB left within the range, then
6728 * we need not break down this page into 2MB pages.
6730 if ((tmpva & PDPMASK) == 0 &&
6731 tmpva + PDPMASK < base + size) {
6735 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
6738 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6743 * If the current 2MB page already has the required
6744 * memory type, then we need not demote this page. Just
6745 * increment tmpva to the next 2MB page frame.
6747 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
6748 tmpva = trunc_2mpage(tmpva) + NBPDR;
6753 * If the current offset aligns with a 2MB page frame
6754 * and there is at least 2MB left within the range, then
6755 * we need not break down this page into 4KB pages.
6757 if ((tmpva & PDRMASK) == 0 &&
6758 tmpva + PDRMASK < base + size) {
6762 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
6765 pte = pmap_pde_to_pte(pde, tmpva);
6773 * Ok, all the pages exist, so run through them updating their
6774 * cache mode if required.
6776 pa_start = pa_end = 0;
6777 for (tmpva = base; tmpva < base + size; ) {
6778 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6779 if (*pdpe & PG_PS) {
6780 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
6781 pmap_pde_attr(pdpe, cache_bits_pde,
6785 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6786 (*pdpe & PG_PS_FRAME) < dmaplimit) {
6787 if (pa_start == pa_end) {
6788 /* Start physical address run. */
6789 pa_start = *pdpe & PG_PS_FRAME;
6790 pa_end = pa_start + NBPDP;
6791 } else if (pa_end == (*pdpe & PG_PS_FRAME))
6794 /* Run ended, update direct map. */
6795 error = pmap_change_attr_locked(
6796 PHYS_TO_DMAP(pa_start),
6797 pa_end - pa_start, mode);
6800 /* Start physical address run. */
6801 pa_start = *pdpe & PG_PS_FRAME;
6802 pa_end = pa_start + NBPDP;
6805 tmpva = trunc_1gpage(tmpva) + NBPDP;
6808 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6810 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
6811 pmap_pde_attr(pde, cache_bits_pde,
6815 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6816 (*pde & PG_PS_FRAME) < dmaplimit) {
6817 if (pa_start == pa_end) {
6818 /* Start physical address run. */
6819 pa_start = *pde & PG_PS_FRAME;
6820 pa_end = pa_start + NBPDR;
6821 } else if (pa_end == (*pde & PG_PS_FRAME))
6824 /* Run ended, update direct map. */
6825 error = pmap_change_attr_locked(
6826 PHYS_TO_DMAP(pa_start),
6827 pa_end - pa_start, mode);
6830 /* Start physical address run. */
6831 pa_start = *pde & PG_PS_FRAME;
6832 pa_end = pa_start + NBPDR;
6835 tmpva = trunc_2mpage(tmpva) + NBPDR;
6837 pte = pmap_pde_to_pte(pde, tmpva);
6838 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
6839 pmap_pte_attr(pte, cache_bits_pte,
6843 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6844 (*pte & PG_FRAME) < dmaplimit) {
6845 if (pa_start == pa_end) {
6846 /* Start physical address run. */
6847 pa_start = *pte & PG_FRAME;
6848 pa_end = pa_start + PAGE_SIZE;
6849 } else if (pa_end == (*pte & PG_FRAME))
6850 pa_end += PAGE_SIZE;
6852 /* Run ended, update direct map. */
6853 error = pmap_change_attr_locked(
6854 PHYS_TO_DMAP(pa_start),
6855 pa_end - pa_start, mode);
6858 /* Start physical address run. */
6859 pa_start = *pte & PG_FRAME;
6860 pa_end = pa_start + PAGE_SIZE;
6866 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
6867 pa_end1 = MIN(pa_end, dmaplimit);
6868 if (pa_start != pa_end1)
6869 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
6870 pa_end1 - pa_start, mode);
6874 * Flush CPU caches if required to make sure any data isn't cached that
6875 * shouldn't be, etc.
6878 pmap_invalidate_range(kernel_pmap, base, tmpva);
6879 pmap_invalidate_cache_range(base, tmpva, FALSE);
6885 * Demotes any mapping within the direct map region that covers more than the
6886 * specified range of physical addresses. This range's size must be a power
6887 * of two and its starting address must be a multiple of its size. Since the
6888 * demotion does not change any attributes of the mapping, a TLB invalidation
6889 * is not mandatory. The caller may, however, request a TLB invalidation.
6892 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
6901 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
6902 KASSERT((base & (len - 1)) == 0,
6903 ("pmap_demote_DMAP: base is not a multiple of len"));
6904 if (len < NBPDP && base < dmaplimit) {
6905 va = PHYS_TO_DMAP(base);
6907 PMAP_LOCK(kernel_pmap);
6908 pdpe = pmap_pdpe(kernel_pmap, va);
6909 if ((*pdpe & X86_PG_V) == 0)
6910 panic("pmap_demote_DMAP: invalid PDPE");
6911 if ((*pdpe & PG_PS) != 0) {
6912 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
6913 panic("pmap_demote_DMAP: PDPE failed");
6917 pde = pmap_pdpe_to_pde(pdpe, va);
6918 if ((*pde & X86_PG_V) == 0)
6919 panic("pmap_demote_DMAP: invalid PDE");
6920 if ((*pde & PG_PS) != 0) {
6921 if (!pmap_demote_pde(kernel_pmap, pde, va))
6922 panic("pmap_demote_DMAP: PDE failed");
6926 if (changed && invalidate)
6927 pmap_invalidate_page(kernel_pmap, va);
6928 PMAP_UNLOCK(kernel_pmap);
6933 * perform the pmap work for mincore
6936 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
6939 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
6943 PG_A = pmap_accessed_bit(pmap);
6944 PG_M = pmap_modified_bit(pmap);
6945 PG_V = pmap_valid_bit(pmap);
6946 PG_RW = pmap_rw_bit(pmap);
6950 pdep = pmap_pde(pmap, addr);
6951 if (pdep != NULL && (*pdep & PG_V)) {
6952 if (*pdep & PG_PS) {
6954 /* Compute the physical address of the 4KB page. */
6955 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
6957 val = MINCORE_SUPER;
6959 pte = *pmap_pde_to_pte(pdep, addr);
6960 pa = pte & PG_FRAME;
6968 if ((pte & PG_V) != 0) {
6969 val |= MINCORE_INCORE;
6970 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6971 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
6972 if ((pte & PG_A) != 0)
6973 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
6975 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
6976 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
6977 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
6978 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
6979 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
6982 PA_UNLOCK_COND(*locked_pa);
6988 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
6990 uint32_t gen, new_gen, pcid_next;
6992 CRITICAL_ASSERT(curthread);
6993 gen = PCPU_GET(pcid_gen);
6994 if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN ||
6995 pmap->pm_pcids[cpuid].pm_gen == gen)
6996 return (CR3_PCID_SAVE);
6997 pcid_next = PCPU_GET(pcid_next);
6998 KASSERT(pcid_next <= PMAP_PCID_OVERMAX, ("cpu %d pcid_next %#x",
7000 if (pcid_next == PMAP_PCID_OVERMAX) {
7004 PCPU_SET(pcid_gen, new_gen);
7005 pcid_next = PMAP_PCID_KERN + 1;
7009 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
7010 pmap->pm_pcids[cpuid].pm_gen = new_gen;
7011 PCPU_SET(pcid_next, pcid_next + 1);
7016 pmap_activate_sw(struct thread *td)
7018 pmap_t oldpmap, pmap;
7019 uint64_t cached, cr3;
7023 oldpmap = PCPU_GET(curpmap);
7024 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7025 if (oldpmap == pmap)
7027 cpuid = PCPU_GET(cpuid);
7029 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7031 CPU_SET(cpuid, &pmap->pm_active);
7034 if (pmap_pcid_enabled) {
7035 cached = pmap_pcid_alloc(pmap, cpuid);
7036 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
7037 pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
7038 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
7039 pmap->pm_pcids[cpuid].pm_pcid));
7040 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
7041 pmap == kernel_pmap,
7042 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
7043 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
7046 * If the INVPCID instruction is not available,
7047 * invltlb_pcid_handler() is used for handle
7048 * invalidate_all IPI, which checks for curpmap ==
7049 * smp_tlb_pmap. Below operations sequence has a
7050 * window where %CR3 is loaded with the new pmap's
7051 * PML4 address, but curpmap value is not yet updated.
7052 * This causes invltlb IPI handler, called between the
7053 * updates, to execute as NOP, which leaves stale TLB
7056 * Note that the most typical use of
7057 * pmap_activate_sw(), from the context switch, is
7058 * immune to this race, because interrupts are
7059 * disabled (while the thread lock is owned), and IPI
7060 * happends after curpmap is updated. Protect other
7061 * callers in a similar way, by disabling interrupts
7062 * around the %cr3 register reload and curpmap
7066 rflags = intr_disable();
7068 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
7069 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
7072 PCPU_INC(pm_save_cnt);
7074 PCPU_SET(curpmap, pmap);
7076 intr_restore(rflags);
7077 } else if (cr3 != pmap->pm_cr3) {
7078 load_cr3(pmap->pm_cr3);
7079 PCPU_SET(curpmap, pmap);
7082 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
7084 CPU_CLR(cpuid, &oldpmap->pm_active);
7089 pmap_activate(struct thread *td)
7093 pmap_activate_sw(td);
7098 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
7103 * Increase the starting virtual address of the given mapping if a
7104 * different alignment might result in more superpage mappings.
7107 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7108 vm_offset_t *addr, vm_size_t size)
7110 vm_offset_t superpage_offset;
7114 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7115 offset += ptoa(object->pg_color);
7116 superpage_offset = offset & PDRMASK;
7117 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
7118 (*addr & PDRMASK) == superpage_offset)
7120 if ((*addr & PDRMASK) < superpage_offset)
7121 *addr = (*addr & ~PDRMASK) + superpage_offset;
7123 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
7127 static unsigned long num_dirty_emulations;
7128 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
7129 &num_dirty_emulations, 0, NULL);
7131 static unsigned long num_accessed_emulations;
7132 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
7133 &num_accessed_emulations, 0, NULL);
7135 static unsigned long num_superpage_accessed_emulations;
7136 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7137 &num_superpage_accessed_emulations, 0, NULL);
7139 static unsigned long ad_emulation_superpage_promotions;
7140 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7141 &ad_emulation_superpage_promotions, 0, NULL);
7142 #endif /* INVARIANTS */
7145 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7148 struct rwlock *lock;
7151 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7153 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7154 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7156 if (!pmap_emulate_ad_bits(pmap))
7159 PG_A = pmap_accessed_bit(pmap);
7160 PG_M = pmap_modified_bit(pmap);
7161 PG_V = pmap_valid_bit(pmap);
7162 PG_RW = pmap_rw_bit(pmap);
7168 pde = pmap_pde(pmap, va);
7169 if (pde == NULL || (*pde & PG_V) == 0)
7172 if ((*pde & PG_PS) != 0) {
7173 if (ftype == VM_PROT_READ) {
7175 atomic_add_long(&num_superpage_accessed_emulations, 1);
7183 pte = pmap_pde_to_pte(pde, va);
7184 if ((*pte & PG_V) == 0)
7187 if (ftype == VM_PROT_WRITE) {
7188 if ((*pte & PG_RW) == 0)
7191 * Set the modified and accessed bits simultaneously.
7193 * Intel EPT PTEs that do software emulation of A/D bits map
7194 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7195 * An EPT misconfiguration is triggered if the PTE is writable
7196 * but not readable (WR=10). This is avoided by setting PG_A
7197 * and PG_M simultaneously.
7199 *pte |= PG_M | PG_A;
7204 /* try to promote the mapping */
7205 if (va < VM_MAXUSER_ADDRESS)
7206 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7210 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7212 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7213 pmap_ps_enabled(pmap) &&
7214 (m->flags & PG_FICTITIOUS) == 0 &&
7215 vm_reserv_level_iffullpop(m) == 0) {
7216 pmap_promote_pde(pmap, pde, va, &lock);
7218 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7222 if (ftype == VM_PROT_WRITE)
7223 atomic_add_long(&num_dirty_emulations, 1);
7225 atomic_add_long(&num_accessed_emulations, 1);
7227 rv = 0; /* success */
7236 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7241 pt_entry_t *pte, PG_V;
7245 PG_V = pmap_valid_bit(pmap);
7248 pml4 = pmap_pml4e(pmap, va);
7250 if ((*pml4 & PG_V) == 0)
7253 pdp = pmap_pml4e_to_pdpe(pml4, va);
7255 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7258 pde = pmap_pdpe_to_pde(pdp, va);
7260 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7263 pte = pmap_pde_to_pte(pde, va);
7272 * Get the kernel virtual address of a set of physical pages. If there are
7273 * physical addresses not covered by the DMAP perform a transient mapping
7274 * that will be removed when calling pmap_unmap_io_transient.
7276 * \param page The pages the caller wishes to obtain the virtual
7277 * address on the kernel memory map.
7278 * \param vaddr On return contains the kernel virtual memory address
7279 * of the pages passed in the page parameter.
7280 * \param count Number of pages passed in.
7281 * \param can_fault TRUE if the thread using the mapped pages can take
7282 * page faults, FALSE otherwise.
7284 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7285 * finished or FALSE otherwise.
7289 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7290 boolean_t can_fault)
7293 boolean_t needs_mapping;
7295 int cache_bits, error, i;
7298 * Allocate any KVA space that we need, this is done in a separate
7299 * loop to prevent calling vmem_alloc while pinned.
7301 needs_mapping = FALSE;
7302 for (i = 0; i < count; i++) {
7303 paddr = VM_PAGE_TO_PHYS(page[i]);
7304 if (__predict_false(paddr >= dmaplimit)) {
7305 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7306 M_BESTFIT | M_WAITOK, &vaddr[i]);
7307 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7308 needs_mapping = TRUE;
7310 vaddr[i] = PHYS_TO_DMAP(paddr);
7314 /* Exit early if everything is covered by the DMAP */
7319 * NB: The sequence of updating a page table followed by accesses
7320 * to the corresponding pages used in the !DMAP case is subject to
7321 * the situation described in the "AMD64 Architecture Programmer's
7322 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7323 * Coherency Considerations". Therefore, issuing the INVLPG right
7324 * after modifying the PTE bits is crucial.
7328 for (i = 0; i < count; i++) {
7329 paddr = VM_PAGE_TO_PHYS(page[i]);
7330 if (paddr >= dmaplimit) {
7333 * Slow path, since we can get page faults
7334 * while mappings are active don't pin the
7335 * thread to the CPU and instead add a global
7336 * mapping visible to all CPUs.
7338 pmap_qenter(vaddr[i], &page[i], 1);
7340 pte = vtopte(vaddr[i]);
7341 cache_bits = pmap_cache_bits(kernel_pmap,
7342 page[i]->md.pat_mode, 0);
7343 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7350 return (needs_mapping);
7354 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7355 boolean_t can_fault)
7362 for (i = 0; i < count; i++) {
7363 paddr = VM_PAGE_TO_PHYS(page[i]);
7364 if (paddr >= dmaplimit) {
7366 pmap_qremove(vaddr[i], 1);
7367 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7373 pmap_quick_enter_page(vm_page_t m)
7377 paddr = VM_PAGE_TO_PHYS(m);
7378 if (paddr < dmaplimit)
7379 return (PHYS_TO_DMAP(paddr));
7380 mtx_lock_spin(&qframe_mtx);
7381 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7382 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7383 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7388 pmap_quick_remove_page(vm_offset_t addr)
7393 pte_store(vtopte(qframe), 0);
7395 mtx_unlock_spin(&qframe_mtx);
7398 #include "opt_ddb.h"
7400 #include <sys/kdb.h>
7401 #include <ddb/ddb.h>
7403 DB_SHOW_COMMAND(pte, pmap_print_pte)
7409 pt_entry_t *pte, PG_V;
7413 db_printf("show pte addr\n");
7416 va = (vm_offset_t)addr;
7418 if (kdb_thread != NULL)
7419 pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
7421 pmap = PCPU_GET(curpmap);
7423 PG_V = pmap_valid_bit(pmap);
7424 pml4 = pmap_pml4e(pmap, va);
7425 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
7426 if ((*pml4 & PG_V) == 0) {
7430 pdp = pmap_pml4e_to_pdpe(pml4, va);
7431 db_printf(" pdpe %#016lx", *pdp);
7432 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
7436 pde = pmap_pdpe_to_pde(pdp, va);
7437 db_printf(" pde %#016lx", *pde);
7438 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
7442 pte = pmap_pde_to_pte(pde, va);
7443 db_printf(" pte %#016lx\n", *pte);
7446 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
7451 a = (vm_paddr_t)addr;
7452 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
7454 db_printf("show phys2dmap addr\n");