2 * Copyright (c) 1991 Regents of the University of California.
4 * Copyright (c) 1994 John S. Dyson
6 * Copyright (c) 1994 David Greenman
8 * Copyright (c) 2003 Peter Wemm
10 * Copyright (c) 2005-2010 Alan L. Cox <alc@cs.rice.edu>
11 * All rights reserved.
13 * This code is derived from software contributed to Berkeley by
14 * the Systems Programming Group of the University of Utah Computer
15 * Science Department and William Jolitz of UUNET Technologies Inc.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
25 * 3. All advertising materials mentioning features or use of this software
26 * must display the following acknowledgement:
27 * This product includes software developed by the University of
28 * California, Berkeley and its contributors.
29 * 4. Neither the name of the University nor the names of its contributors
30 * may be used to endorse or promote products derived from this software
31 * without specific prior written permission.
33 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
34 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
35 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
36 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
37 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
38 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
39 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
40 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
41 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
42 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
45 * from: @(#)pmap.c 7.7 (Berkeley) 5/12/91
48 * Copyright (c) 2003 Networks Associates Technology, Inc.
49 * All rights reserved.
51 * This software was developed for the FreeBSD Project by Jake Burkholder,
52 * Safeport Network Services, and Network Associates Laboratories, the
53 * Security Research Division of Network Associates, Inc. under
54 * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
55 * CHATS research program.
57 * Redistribution and use in source and binary forms, with or without
58 * modification, are permitted provided that the following conditions
60 * 1. Redistributions of source code must retain the above copyright
61 * notice, this list of conditions and the following disclaimer.
62 * 2. Redistributions in binary form must reproduce the above copyright
63 * notice, this list of conditions and the following disclaimer in the
64 * documentation and/or other materials provided with the distribution.
66 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
67 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
68 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
69 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
70 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
71 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
72 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
73 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
74 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
75 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
79 #define AMD64_NPT_AWARE
81 #include <sys/cdefs.h>
82 __FBSDID("$FreeBSD$");
85 * Manages physical address maps.
87 * Since the information managed by this module is
88 * also stored by the logical address mapping module,
89 * this module may throw away valid virtual-to-physical
90 * mappings at almost any time. However, invalidations
91 * of virtual-to-physical mappings must be done as
94 * In order to cope with hardware architectures which
95 * make virtual-to-physical map invalidates expensive,
96 * this module may delay invalidate or reduced protection
97 * operations until such time as they are actually
98 * necessary. This module is given full information as
99 * to which processors are currently using which maps,
100 * and to when physical maps must be made correct.
103 #include "opt_pmap.h"
106 #include <sys/param.h>
107 #include <sys/bitstring.h>
109 #include <sys/systm.h>
110 #include <sys/kernel.h>
112 #include <sys/lock.h>
113 #include <sys/malloc.h>
114 #include <sys/mman.h>
115 #include <sys/mutex.h>
116 #include <sys/proc.h>
117 #include <sys/rwlock.h>
119 #include <sys/turnstile.h>
120 #include <sys/vmem.h>
121 #include <sys/vmmeter.h>
122 #include <sys/sched.h>
123 #include <sys/sysctl.h>
127 #include <vm/vm_param.h>
128 #include <vm/vm_kern.h>
129 #include <vm/vm_page.h>
130 #include <vm/vm_map.h>
131 #include <vm/vm_object.h>
132 #include <vm/vm_extern.h>
133 #include <vm/vm_pageout.h>
134 #include <vm/vm_pager.h>
135 #include <vm/vm_phys.h>
136 #include <vm/vm_radix.h>
137 #include <vm/vm_reserv.h>
140 #include <machine/intr_machdep.h>
141 #include <x86/apicvar.h>
142 #include <machine/cpu.h>
143 #include <machine/cputypes.h>
144 #include <machine/md_var.h>
145 #include <machine/pcb.h>
146 #include <machine/specialreg.h>
148 #include <machine/smp.h>
151 static __inline boolean_t
152 pmap_type_guest(pmap_t pmap)
155 return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
158 static __inline boolean_t
159 pmap_emulate_ad_bits(pmap_t pmap)
162 return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
165 static __inline pt_entry_t
166 pmap_valid_bit(pmap_t pmap)
170 switch (pmap->pm_type) {
176 if (pmap_emulate_ad_bits(pmap))
177 mask = EPT_PG_EMUL_V;
182 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
188 static __inline pt_entry_t
189 pmap_rw_bit(pmap_t pmap)
193 switch (pmap->pm_type) {
199 if (pmap_emulate_ad_bits(pmap))
200 mask = EPT_PG_EMUL_RW;
205 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
211 static __inline pt_entry_t
212 pmap_global_bit(pmap_t pmap)
216 switch (pmap->pm_type) {
225 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
231 static __inline pt_entry_t
232 pmap_accessed_bit(pmap_t pmap)
236 switch (pmap->pm_type) {
242 if (pmap_emulate_ad_bits(pmap))
248 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
254 static __inline pt_entry_t
255 pmap_modified_bit(pmap_t pmap)
259 switch (pmap->pm_type) {
265 if (pmap_emulate_ad_bits(pmap))
271 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
277 extern struct pcpu __pcpu[];
279 #if !defined(DIAGNOSTIC)
280 #ifdef __GNUC_GNU_INLINE__
281 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
283 #define PMAP_INLINE extern inline
290 #define PV_STAT(x) do { x ; } while (0)
292 #define PV_STAT(x) do { } while (0)
295 #define pa_index(pa) ((pa) >> PDRSHIFT)
296 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
298 #define NPV_LIST_LOCKS MAXCPU
300 #define PHYS_TO_PV_LIST_LOCK(pa) \
301 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
303 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
304 struct rwlock **_lockp = (lockp); \
305 struct rwlock *_new_lock; \
307 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
308 if (_new_lock != *_lockp) { \
309 if (*_lockp != NULL) \
310 rw_wunlock(*_lockp); \
311 *_lockp = _new_lock; \
316 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
317 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
319 #define RELEASE_PV_LIST_LOCK(lockp) do { \
320 struct rwlock **_lockp = (lockp); \
322 if (*_lockp != NULL) { \
323 rw_wunlock(*_lockp); \
328 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
329 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
331 struct pmap kernel_pmap_store;
333 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
334 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
337 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
338 "Number of kernel page table pages allocated on bootup");
341 vm_paddr_t dmaplimit;
342 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
345 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
347 static int pat_works = 1;
348 SYSCTL_INT(_vm_pmap, OID_AUTO, pat_works, CTLFLAG_RD, &pat_works, 1,
349 "Is page attribute table fully functional?");
351 static int pg_ps_enabled = 1;
352 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
353 &pg_ps_enabled, 0, "Are large page mappings enabled?");
355 #define PAT_INDEX_SIZE 8
356 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
358 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
359 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
360 u_int64_t KPDPphys; /* phys addr of kernel level 3 */
361 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
363 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
364 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
365 static int ndmpdpphys; /* number of DMPDPphys pages */
368 * pmap_mapdev support pre initialization (i.e. console)
370 #define PMAP_PREINIT_MAPPING_COUNT 8
371 static struct pmap_preinit_mapping {
376 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
377 static int pmap_initialized;
380 * Data for the pv entry allocation mechanism.
381 * Updates to pv_invl_gen are protected by the pv_list_locks[]
382 * elements, but reads are not.
384 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
385 static struct mtx pv_chunks_mutex;
386 static struct rwlock pv_list_locks[NPV_LIST_LOCKS];
387 static u_long pv_invl_gen[NPV_LIST_LOCKS];
388 static struct md_page *pv_table;
389 static struct md_page pv_dummy;
392 * All those kernel PT submaps that BSD is so fond of
394 pt_entry_t *CMAP1 = 0;
396 static vm_offset_t qframe = 0;
397 static struct mtx qframe_mtx;
399 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
401 int pmap_pcid_enabled = 1;
402 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
403 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
404 int invpcid_works = 0;
405 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
406 "Is the invpcid instruction available ?");
409 pmap_pcid_save_cnt_proc(SYSCTL_HANDLER_ARGS)
416 res += cpuid_to_pcpu[i]->pc_pm_save_cnt;
418 return (sysctl_handle_64(oidp, &res, 0, req));
420 SYSCTL_PROC(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLTYPE_U64 | CTLFLAG_RW |
421 CTLFLAG_MPSAFE, NULL, 0, pmap_pcid_save_cnt_proc, "QU",
422 "Count of saved TLB context on switch");
424 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
425 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
426 static struct mtx invl_gen_mtx;
427 static u_long pmap_invl_gen = 0;
428 /* Fake lock object to satisfy turnstiles interface. */
429 static struct lock_object invl_gen_ts = {
433 #define PMAP_ASSERT_NOT_IN_DI() \
434 KASSERT(curthread->td_md.md_invl_gen.gen == 0, ("DI already started"))
437 * Start a new Delayed Invalidation (DI) block of code, executed by
438 * the current thread. Within a DI block, the current thread may
439 * destroy both the page table and PV list entries for a mapping and
440 * then release the corresponding PV list lock before ensuring that
441 * the mapping is flushed from the TLBs of any processors with the
445 pmap_delayed_invl_started(void)
447 struct pmap_invl_gen *invl_gen;
450 invl_gen = &curthread->td_md.md_invl_gen;
451 PMAP_ASSERT_NOT_IN_DI();
452 mtx_lock(&invl_gen_mtx);
453 if (LIST_EMPTY(&pmap_invl_gen_tracker))
454 currgen = pmap_invl_gen;
456 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
457 invl_gen->gen = currgen + 1;
458 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
459 mtx_unlock(&invl_gen_mtx);
463 * Finish the DI block, previously started by the current thread. All
464 * required TLB flushes for the pages marked by
465 * pmap_delayed_invl_page() must be finished before this function is
468 * This function works by bumping the global DI generation number to
469 * the generation number of the current thread's DI, unless there is a
470 * pending DI that started earlier. In the latter case, bumping the
471 * global DI generation number would incorrectly signal that the
472 * earlier DI had finished. Instead, this function bumps the earlier
473 * DI's generation number to match the generation number of the
474 * current thread's DI.
477 pmap_delayed_invl_finished(void)
479 struct pmap_invl_gen *invl_gen, *next;
480 struct turnstile *ts;
482 invl_gen = &curthread->td_md.md_invl_gen;
483 KASSERT(invl_gen->gen != 0, ("missed invl_started"));
484 mtx_lock(&invl_gen_mtx);
485 next = LIST_NEXT(invl_gen, link);
487 turnstile_chain_lock(&invl_gen_ts);
488 ts = turnstile_lookup(&invl_gen_ts);
489 pmap_invl_gen = invl_gen->gen;
491 turnstile_broadcast(ts, TS_SHARED_QUEUE);
492 turnstile_unpend(ts, TS_SHARED_LOCK);
494 turnstile_chain_unlock(&invl_gen_ts);
496 next->gen = invl_gen->gen;
498 LIST_REMOVE(invl_gen, link);
499 mtx_unlock(&invl_gen_mtx);
504 static long invl_wait;
505 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
506 "Number of times DI invalidation blocked pmap_remove_all/write");
510 pmap_delayed_invl_genp(vm_page_t m)
513 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
517 * Ensure that all currently executing DI blocks, that need to flush
518 * TLB for the given page m, actually flushed the TLB at the time the
519 * function returned. If the page m has an empty PV list and we call
520 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
521 * valid mapping for the page m in either its page table or TLB.
523 * This function works by blocking until the global DI generation
524 * number catches up with the generation number associated with the
525 * given page m and its PV list. Since this function's callers
526 * typically own an object lock and sometimes own a page lock, it
527 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
531 pmap_delayed_invl_wait(vm_page_t m)
534 struct turnstile *ts;
537 bool accounted = false;
541 m_gen = pmap_delayed_invl_genp(m);
542 while (*m_gen > pmap_invl_gen) {
545 atomic_add_long(&invl_wait, 1);
549 ts = turnstile_trywait(&invl_gen_ts);
550 if (*m_gen > pmap_invl_gen)
551 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
553 turnstile_cancel(ts);
558 * Mark the page m's PV list as participating in the current thread's
559 * DI block. Any threads concurrently using m's PV list to remove or
560 * restrict all mappings to m will wait for the current thread's DI
561 * block to complete before proceeding.
563 * The function works by setting the DI generation number for m's PV
564 * list to at least the DI generation number of the current thread.
565 * This forces a caller of pmap_delayed_invl_wait() to block until
566 * current thread calls pmap_delayed_invl_finished().
569 pmap_delayed_invl_page(vm_page_t m)
573 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
574 gen = curthread->td_md.md_invl_gen.gen;
577 m_gen = pmap_delayed_invl_genp(m);
585 static caddr_t crashdumpmap;
587 static void free_pv_chunk(struct pv_chunk *pc);
588 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
589 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
590 static int popcnt_pc_map_pq(uint64_t *map);
591 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
592 static void reserve_pv_entries(pmap_t pmap, int needed,
593 struct rwlock **lockp);
594 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
595 struct rwlock **lockp);
596 static boolean_t pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
597 struct rwlock **lockp);
598 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
599 struct rwlock **lockp);
600 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
601 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
604 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode);
605 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
606 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
607 vm_offset_t va, struct rwlock **lockp);
608 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
610 static boolean_t pmap_enter_pde(pmap_t pmap, vm_offset_t va, vm_page_t m,
611 vm_prot_t prot, struct rwlock **lockp);
612 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
613 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
614 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
615 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
616 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
617 static vm_page_t pmap_lookup_pt_page(pmap_t pmap, vm_offset_t va);
618 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask);
619 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
620 struct rwlock **lockp);
621 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
623 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
624 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
625 struct spglist *free, struct rwlock **lockp);
626 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
627 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
628 static void pmap_remove_pt_page(pmap_t pmap, vm_page_t mpte);
629 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
630 struct spglist *free);
631 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
632 vm_page_t m, struct rwlock **lockp);
633 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
635 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
637 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
638 struct rwlock **lockp);
639 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
640 struct rwlock **lockp);
641 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
642 struct rwlock **lockp);
644 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
645 struct spglist *free);
646 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
647 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
650 * Move the kernel virtual free pointer to the next
651 * 2MB. This is used to help improve performance
652 * by using a large (2MB) page for much of the kernel
653 * (.text, .data, .bss)
656 pmap_kmem_choose(vm_offset_t addr)
658 vm_offset_t newaddr = addr;
660 newaddr = roundup2(addr, NBPDR);
664 /********************/
665 /* Inline functions */
666 /********************/
668 /* Return a non-clipped PD index for a given VA */
669 static __inline vm_pindex_t
670 pmap_pde_pindex(vm_offset_t va)
672 return (va >> PDRSHIFT);
676 /* Return a pointer to the PML4 slot that corresponds to a VA */
677 static __inline pml4_entry_t *
678 pmap_pml4e(pmap_t pmap, vm_offset_t va)
681 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
684 /* Return a pointer to the PDP slot that corresponds to a VA */
685 static __inline pdp_entry_t *
686 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
690 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
691 return (&pdpe[pmap_pdpe_index(va)]);
694 /* Return a pointer to the PDP slot that corresponds to a VA */
695 static __inline pdp_entry_t *
696 pmap_pdpe(pmap_t pmap, vm_offset_t va)
701 PG_V = pmap_valid_bit(pmap);
702 pml4e = pmap_pml4e(pmap, va);
703 if ((*pml4e & PG_V) == 0)
705 return (pmap_pml4e_to_pdpe(pml4e, va));
708 /* Return a pointer to the PD slot that corresponds to a VA */
709 static __inline pd_entry_t *
710 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
714 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
715 return (&pde[pmap_pde_index(va)]);
718 /* Return a pointer to the PD slot that corresponds to a VA */
719 static __inline pd_entry_t *
720 pmap_pde(pmap_t pmap, vm_offset_t va)
725 PG_V = pmap_valid_bit(pmap);
726 pdpe = pmap_pdpe(pmap, va);
727 if (pdpe == NULL || (*pdpe & PG_V) == 0)
729 return (pmap_pdpe_to_pde(pdpe, va));
732 /* Return a pointer to the PT slot that corresponds to a VA */
733 static __inline pt_entry_t *
734 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
738 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
739 return (&pte[pmap_pte_index(va)]);
742 /* Return a pointer to the PT slot that corresponds to a VA */
743 static __inline pt_entry_t *
744 pmap_pte(pmap_t pmap, vm_offset_t va)
749 PG_V = pmap_valid_bit(pmap);
750 pde = pmap_pde(pmap, va);
751 if (pde == NULL || (*pde & PG_V) == 0)
753 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
754 return ((pt_entry_t *)pde);
755 return (pmap_pde_to_pte(pde, va));
759 pmap_resident_count_inc(pmap_t pmap, int count)
762 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
763 pmap->pm_stats.resident_count += count;
767 pmap_resident_count_dec(pmap_t pmap, int count)
770 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
771 KASSERT(pmap->pm_stats.resident_count >= count,
772 ("pmap %p resident count underflow %ld %d", pmap,
773 pmap->pm_stats.resident_count, count));
774 pmap->pm_stats.resident_count -= count;
777 PMAP_INLINE pt_entry_t *
778 vtopte(vm_offset_t va)
780 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
782 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
784 return (PTmap + ((va >> PAGE_SHIFT) & mask));
787 static __inline pd_entry_t *
788 vtopde(vm_offset_t va)
790 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
792 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
794 return (PDmap + ((va >> PDRSHIFT) & mask));
798 allocpages(vm_paddr_t *firstaddr, int n)
803 bzero((void *)ret, n * PAGE_SIZE);
804 *firstaddr += n * PAGE_SIZE;
808 CTASSERT(powerof2(NDMPML4E));
810 /* number of kernel PDP slots */
811 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
814 nkpt_init(vm_paddr_t addr)
821 pt_pages = howmany(addr, 1 << PDRSHIFT);
822 pt_pages += NKPDPE(pt_pages);
825 * Add some slop beyond the bare minimum required for bootstrapping
828 * This is quite important when allocating KVA for kernel modules.
829 * The modules are required to be linked in the negative 2GB of
830 * the address space. If we run out of KVA in this region then
831 * pmap_growkernel() will need to allocate page table pages to map
832 * the entire 512GB of KVA space which is an unnecessary tax on
835 * Secondly, device memory mapped as part of setting up the low-
836 * level console(s) is taken from KVA, starting at virtual_avail.
837 * This is because cninit() is called after pmap_bootstrap() but
838 * before vm_init() and pmap_init(). 20MB for a frame buffer is
841 pt_pages += 32; /* 64MB additional slop. */
847 create_pagetables(vm_paddr_t *firstaddr)
849 int i, j, ndm1g, nkpdpe;
855 /* Allocate page table pages for the direct map */
856 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
857 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
859 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
860 if (ndmpdpphys > NDMPML4E) {
862 * Each NDMPML4E allows 512 GB, so limit to that,
863 * and then readjust ndmpdp and ndmpdpphys.
865 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
866 Maxmem = atop(NDMPML4E * NBPML4);
867 ndmpdpphys = NDMPML4E;
868 ndmpdp = NDMPML4E * NPDEPG;
870 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
872 if ((amd_feature & AMDID_PAGE1GB) != 0)
873 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
875 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
876 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
879 KPML4phys = allocpages(firstaddr, 1);
880 KPDPphys = allocpages(firstaddr, NKPML4E);
883 * Allocate the initial number of kernel page table pages required to
884 * bootstrap. We defer this until after all memory-size dependent
885 * allocations are done (e.g. direct map), so that we don't have to
886 * build in too much slop in our estimate.
888 * Note that when NKPML4E > 1, we have an empty page underneath
889 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
890 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
892 nkpt_init(*firstaddr);
893 nkpdpe = NKPDPE(nkpt);
895 KPTphys = allocpages(firstaddr, nkpt);
896 KPDphys = allocpages(firstaddr, nkpdpe);
898 /* Fill in the underlying page table pages */
899 /* Nominally read-only (but really R/W) from zero to physfree */
900 /* XXX not fully used, underneath 2M pages */
901 pt_p = (pt_entry_t *)KPTphys;
902 for (i = 0; ptoa(i) < *firstaddr; i++)
903 pt_p[i] = ptoa(i) | X86_PG_RW | X86_PG_V | X86_PG_G;
905 /* Now map the page tables at their location within PTmap */
906 pd_p = (pd_entry_t *)KPDphys;
907 for (i = 0; i < nkpt; i++)
908 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
910 /* Map from zero to end of allocations under 2M pages */
911 /* This replaces some of the KPTphys entries above */
912 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
913 pd_p[i] = (i << PDRSHIFT) | X86_PG_RW | X86_PG_V | PG_PS |
916 /* And connect up the PD to the PDP (leaving room for L4 pages) */
917 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
918 for (i = 0; i < nkpdpe; i++)
919 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
923 * Now, set up the direct map region using 2MB and/or 1GB pages. If
924 * the end of physical memory is not aligned to a 1GB page boundary,
925 * then the residual physical memory is mapped with 2MB pages. Later,
926 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
927 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
928 * that are partially used.
930 pd_p = (pd_entry_t *)DMPDphys;
931 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
932 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
933 /* Preset PG_M and PG_A because demotion expects it. */
934 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | X86_PG_G |
937 pdp_p = (pdp_entry_t *)DMPDPphys;
938 for (i = 0; i < ndm1g; i++) {
939 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
940 /* Preset PG_M and PG_A because demotion expects it. */
941 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | X86_PG_G |
944 for (j = 0; i < ndmpdp; i++, j++) {
945 pdp_p[i] = DMPDphys + ptoa(j);
946 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_U;
949 /* And recursively map PML4 to itself in order to get PTmap */
950 p4_p = (pml4_entry_t *)KPML4phys;
951 p4_p[PML4PML4I] = KPML4phys;
952 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | PG_U;
954 /* Connect the Direct Map slot(s) up to the PML4. */
955 for (i = 0; i < ndmpdpphys; i++) {
956 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
957 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | PG_U;
960 /* Connect the KVA slots up to the PML4 */
961 for (i = 0; i < NKPML4E; i++) {
962 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
963 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V | PG_U;
968 * Bootstrap the system enough to run with virtual memory.
970 * On amd64 this is called after mapping has already been enabled
971 * and just syncs the pmap module with what has already been done.
972 * [We can't call it easily with mapping off since the kernel is not
973 * mapped with PA == VA, hence we would have to relocate every address
974 * from the linked base (virtual) address "KERNBASE" to the actual
975 * (physical) address starting relative to 0]
978 pmap_bootstrap(vm_paddr_t *firstaddr)
985 * Create an initial set of page tables to run the kernel in.
987 create_pagetables(firstaddr);
990 * Add a physical memory segment (vm_phys_seg) corresponding to the
991 * preallocated kernel page table pages so that vm_page structures
992 * representing these pages will be created. The vm_page structures
993 * are required for promotion of the corresponding kernel virtual
994 * addresses to superpage mappings.
996 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
998 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
999 virtual_avail = pmap_kmem_choose(virtual_avail);
1001 virtual_end = VM_MAX_KERNEL_ADDRESS;
1004 /* XXX do %cr0 as well */
1005 load_cr4(rcr4() | CR4_PGE);
1006 load_cr3(KPML4phys);
1007 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1008 load_cr4(rcr4() | CR4_SMEP);
1011 * Initialize the kernel pmap (which is statically allocated).
1013 PMAP_LOCK_INIT(kernel_pmap);
1014 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1015 kernel_pmap->pm_cr3 = KPML4phys;
1016 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1017 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1018 kernel_pmap->pm_flags = pmap_flags;
1021 * Initialize the TLB invalidations generation number lock.
1023 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1026 * Reserve some special page table entries/VA space for temporary
1029 #define SYSMAP(c, p, v, n) \
1030 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1036 * Crashdump maps. The first page is reused as CMAP1 for the
1039 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1040 CADDR1 = crashdumpmap;
1044 /* Initialize the PAT MSR. */
1047 /* Initialize TLB Context Id. */
1048 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1049 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1050 /* Check for INVPCID support */
1051 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1053 for (i = 0; i < MAXCPU; i++) {
1054 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1055 kernel_pmap->pm_pcids[i].pm_gen = 1;
1057 __pcpu[0].pc_pcid_next = PMAP_PCID_KERN + 1;
1058 __pcpu[0].pc_pcid_gen = 1;
1060 * pcpu area for APs is zeroed during AP startup.
1061 * pc_pcid_next and pc_pcid_gen are initialized by AP
1062 * during pcpu setup.
1064 load_cr4(rcr4() | CR4_PCIDE);
1066 pmap_pcid_enabled = 0;
1071 * Setup the PAT MSR.
1076 int pat_table[PAT_INDEX_SIZE];
1081 /* Bail if this CPU doesn't implement PAT. */
1082 if ((cpu_feature & CPUID_PAT) == 0)
1085 /* Set default PAT index table. */
1086 for (i = 0; i < PAT_INDEX_SIZE; i++)
1088 pat_table[PAT_WRITE_BACK] = 0;
1089 pat_table[PAT_WRITE_THROUGH] = 1;
1090 pat_table[PAT_UNCACHEABLE] = 3;
1091 pat_table[PAT_WRITE_COMBINING] = 3;
1092 pat_table[PAT_WRITE_PROTECTED] = 3;
1093 pat_table[PAT_UNCACHED] = 3;
1095 /* Initialize default PAT entries. */
1096 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1097 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1098 PAT_VALUE(2, PAT_UNCACHED) |
1099 PAT_VALUE(3, PAT_UNCACHEABLE) |
1100 PAT_VALUE(4, PAT_WRITE_BACK) |
1101 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1102 PAT_VALUE(6, PAT_UNCACHED) |
1103 PAT_VALUE(7, PAT_UNCACHEABLE);
1107 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1108 * Program 5 and 6 as WP and WC.
1109 * Leave 4 and 7 as WB and UC.
1111 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1112 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1113 PAT_VALUE(6, PAT_WRITE_COMBINING);
1114 pat_table[PAT_UNCACHED] = 2;
1115 pat_table[PAT_WRITE_PROTECTED] = 5;
1116 pat_table[PAT_WRITE_COMBINING] = 6;
1119 * Just replace PAT Index 2 with WC instead of UC-.
1121 pat_msr &= ~PAT_MASK(2);
1122 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1123 pat_table[PAT_WRITE_COMBINING] = 2;
1128 load_cr4(cr4 & ~CR4_PGE);
1130 /* Disable caches (CD = 1, NW = 0). */
1132 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1134 /* Flushes caches and TLBs. */
1138 /* Update PAT and index table. */
1139 wrmsr(MSR_PAT, pat_msr);
1140 for (i = 0; i < PAT_INDEX_SIZE; i++)
1141 pat_index[i] = pat_table[i];
1143 /* Flush caches and TLBs again. */
1147 /* Restore caches and PGE. */
1153 * Initialize a vm_page's machine-dependent fields.
1156 pmap_page_init(vm_page_t m)
1159 TAILQ_INIT(&m->md.pv_list);
1160 m->md.pat_mode = PAT_WRITE_BACK;
1164 * Initialize the pmap module.
1165 * Called by vm_init, to initialize any structures that the pmap
1166 * system needs to map virtual memory.
1171 struct pmap_preinit_mapping *ppim;
1174 int error, i, pv_npg;
1177 * Initialize the vm page array entries for the kernel pmap's
1180 for (i = 0; i < nkpt; i++) {
1181 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1182 KASSERT(mpte >= vm_page_array &&
1183 mpte < &vm_page_array[vm_page_array_size],
1184 ("pmap_init: page table page is out of range"));
1185 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1186 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1190 * If the kernel is running on a virtual machine, then it must assume
1191 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1192 * be prepared for the hypervisor changing the vendor and family that
1193 * are reported by CPUID. Consequently, the workaround for AMD Family
1194 * 10h Erratum 383 is enabled if the processor's feature set does not
1195 * include at least one feature that is only supported by older Intel
1196 * or newer AMD processors.
1198 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1199 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1200 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1202 workaround_erratum383 = 1;
1205 * Are large page mappings enabled?
1207 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1208 if (pg_ps_enabled) {
1209 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1210 ("pmap_init: can't assign to pagesizes[1]"));
1211 pagesizes[1] = NBPDR;
1215 * Initialize the pv chunk list mutex.
1217 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1220 * Initialize the pool of pv list locks.
1222 for (i = 0; i < NPV_LIST_LOCKS; i++)
1223 rw_init(&pv_list_locks[i], "pmap pv list");
1226 * Calculate the size of the pv head table for superpages.
1228 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1231 * Allocate memory for the pv head table for superpages.
1233 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1235 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1237 for (i = 0; i < pv_npg; i++)
1238 TAILQ_INIT(&pv_table[i].pv_list);
1239 TAILQ_INIT(&pv_dummy.pv_list);
1241 pmap_initialized = 1;
1242 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1243 ppim = pmap_preinit_mapping + i;
1246 /* Make the direct map consistent */
1247 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz < dmaplimit) {
1248 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1249 ppim->sz, ppim->mode);
1253 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1254 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1257 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1258 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1259 (vmem_addr_t *)&qframe);
1261 panic("qframe allocation failed");
1264 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1265 "2MB page mapping counters");
1267 static u_long pmap_pde_demotions;
1268 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1269 &pmap_pde_demotions, 0, "2MB page demotions");
1271 static u_long pmap_pde_mappings;
1272 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1273 &pmap_pde_mappings, 0, "2MB page mappings");
1275 static u_long pmap_pde_p_failures;
1276 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1277 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1279 static u_long pmap_pde_promotions;
1280 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1281 &pmap_pde_promotions, 0, "2MB page promotions");
1283 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1284 "1GB page mapping counters");
1286 static u_long pmap_pdpe_demotions;
1287 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1288 &pmap_pdpe_demotions, 0, "1GB page demotions");
1290 /***************************************************
1291 * Low level helper routines.....
1292 ***************************************************/
1295 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1297 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1299 switch (pmap->pm_type) {
1302 /* Verify that both PAT bits are not set at the same time */
1303 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1304 ("Invalid PAT bits in entry %#lx", entry));
1306 /* Swap the PAT bits if one of them is set */
1307 if ((entry & x86_pat_bits) != 0)
1308 entry ^= x86_pat_bits;
1312 * Nothing to do - the memory attributes are represented
1313 * the same way for regular pages and superpages.
1317 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1324 * Determine the appropriate bits to set in a PTE or PDE for a specified
1328 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1330 int cache_bits, pat_flag, pat_idx;
1332 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1333 panic("Unknown caching mode %d\n", mode);
1335 switch (pmap->pm_type) {
1338 /* The PAT bit is different for PTE's and PDE's. */
1339 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1341 /* Map the caching mode to a PAT index. */
1342 pat_idx = pat_index[mode];
1344 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1347 cache_bits |= pat_flag;
1349 cache_bits |= PG_NC_PCD;
1351 cache_bits |= PG_NC_PWT;
1355 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1359 panic("unsupported pmap type %d", pmap->pm_type);
1362 return (cache_bits);
1366 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1370 switch (pmap->pm_type) {
1373 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1376 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1379 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1385 static __inline boolean_t
1386 pmap_ps_enabled(pmap_t pmap)
1389 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1393 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1396 switch (pmap->pm_type) {
1403 * This is a little bogus since the generation number is
1404 * supposed to be bumped up when a region of the address
1405 * space is invalidated in the page tables.
1407 * In this case the old PDE entry is valid but yet we want
1408 * to make sure that any mappings using the old entry are
1409 * invalidated in the TLB.
1411 * The reason this works as expected is because we rendezvous
1412 * "all" host cpus and force any vcpu context to exit as a
1415 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1418 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1420 pde_store(pde, newpde);
1424 * After changing the page size for the specified virtual address in the page
1425 * table, flush the corresponding entries from the processor's TLB. Only the
1426 * calling processor's TLB is affected.
1428 * The calling thread must be pinned to a processor.
1431 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1435 if (pmap_type_guest(pmap))
1438 KASSERT(pmap->pm_type == PT_X86,
1439 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1441 PG_G = pmap_global_bit(pmap);
1443 if ((newpde & PG_PS) == 0)
1444 /* Demotion: flush a specific 2MB page mapping. */
1446 else if ((newpde & PG_G) == 0)
1448 * Promotion: flush every 4KB page mapping from the TLB
1449 * because there are too many to flush individually.
1454 * Promotion: flush every 4KB page mapping from the TLB,
1455 * including any global (PG_G) mappings.
1463 * For SMP, these functions have to use the IPI mechanism for coherence.
1465 * N.B.: Before calling any of the following TLB invalidation functions,
1466 * the calling processor must ensure that all stores updating a non-
1467 * kernel page table are globally performed. Otherwise, another
1468 * processor could cache an old, pre-update entry without being
1469 * invalidated. This can happen one of two ways: (1) The pmap becomes
1470 * active on another processor after its pm_active field is checked by
1471 * one of the following functions but before a store updating the page
1472 * table is globally performed. (2) The pmap becomes active on another
1473 * processor before its pm_active field is checked but due to
1474 * speculative loads one of the following functions stills reads the
1475 * pmap as inactive on the other processor.
1477 * The kernel page table is exempt because its pm_active field is
1478 * immutable. The kernel page table is always active on every
1483 * Interrupt the cpus that are executing in the guest context.
1484 * This will force the vcpu to exit and the cached EPT mappings
1485 * will be invalidated by the host before the next vmresume.
1487 static __inline void
1488 pmap_invalidate_ept(pmap_t pmap)
1493 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1494 ("pmap_invalidate_ept: absurd pm_active"));
1497 * The TLB mappings associated with a vcpu context are not
1498 * flushed each time a different vcpu is chosen to execute.
1500 * This is in contrast with a process's vtop mappings that
1501 * are flushed from the TLB on each context switch.
1503 * Therefore we need to do more than just a TLB shootdown on
1504 * the active cpus in 'pmap->pm_active'. To do this we keep
1505 * track of the number of invalidations performed on this pmap.
1507 * Each vcpu keeps a cache of this counter and compares it
1508 * just before a vmresume. If the counter is out-of-date an
1509 * invept will be done to flush stale mappings from the TLB.
1511 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1514 * Force the vcpu to exit and trap back into the hypervisor.
1516 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1517 ipi_selected(pmap->pm_active, ipinum);
1522 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1527 if (pmap_type_guest(pmap)) {
1528 pmap_invalidate_ept(pmap);
1532 KASSERT(pmap->pm_type == PT_X86,
1533 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1536 if (pmap == kernel_pmap) {
1540 cpuid = PCPU_GET(cpuid);
1541 if (pmap == PCPU_GET(curpmap))
1543 else if (pmap_pcid_enabled)
1544 pmap->pm_pcids[cpuid].pm_gen = 0;
1545 if (pmap_pcid_enabled) {
1548 pmap->pm_pcids[i].pm_gen = 0;
1551 mask = &pmap->pm_active;
1553 smp_masked_invlpg(*mask, va);
1557 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1558 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1561 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1567 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1568 pmap_invalidate_all(pmap);
1572 if (pmap_type_guest(pmap)) {
1573 pmap_invalidate_ept(pmap);
1577 KASSERT(pmap->pm_type == PT_X86,
1578 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1581 cpuid = PCPU_GET(cpuid);
1582 if (pmap == kernel_pmap) {
1583 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1587 if (pmap == PCPU_GET(curpmap)) {
1588 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1590 } else if (pmap_pcid_enabled) {
1591 pmap->pm_pcids[cpuid].pm_gen = 0;
1593 if (pmap_pcid_enabled) {
1596 pmap->pm_pcids[i].pm_gen = 0;
1599 mask = &pmap->pm_active;
1601 smp_masked_invlpg_range(*mask, sva, eva);
1606 pmap_invalidate_all(pmap_t pmap)
1609 struct invpcid_descr d;
1612 if (pmap_type_guest(pmap)) {
1613 pmap_invalidate_ept(pmap);
1617 KASSERT(pmap->pm_type == PT_X86,
1618 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1621 if (pmap == kernel_pmap) {
1622 if (pmap_pcid_enabled && invpcid_works) {
1623 bzero(&d, sizeof(d));
1624 invpcid(&d, INVPCID_CTXGLOB);
1630 cpuid = PCPU_GET(cpuid);
1631 if (pmap == PCPU_GET(curpmap)) {
1632 if (pmap_pcid_enabled) {
1633 if (invpcid_works) {
1634 d.pcid = pmap->pm_pcids[cpuid].pm_pcid;
1637 invpcid(&d, INVPCID_CTX);
1639 load_cr3(pmap->pm_cr3 | pmap->pm_pcids
1640 [PCPU_GET(cpuid)].pm_pcid);
1645 } else if (pmap_pcid_enabled) {
1646 pmap->pm_pcids[cpuid].pm_gen = 0;
1648 if (pmap_pcid_enabled) {
1651 pmap->pm_pcids[i].pm_gen = 0;
1654 mask = &pmap->pm_active;
1656 smp_masked_invltlb(*mask, pmap);
1661 pmap_invalidate_cache(void)
1671 cpuset_t invalidate; /* processors that invalidate their TLB */
1676 u_int store; /* processor that updates the PDE */
1680 pmap_update_pde_action(void *arg)
1682 struct pde_action *act = arg;
1684 if (act->store == PCPU_GET(cpuid))
1685 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1689 pmap_update_pde_teardown(void *arg)
1691 struct pde_action *act = arg;
1693 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1694 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1698 * Change the page size for the specified virtual address in a way that
1699 * prevents any possibility of the TLB ever having two entries that map the
1700 * same virtual address using different page sizes. This is the recommended
1701 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1702 * machine check exception for a TLB state that is improperly diagnosed as a
1706 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1708 struct pde_action act;
1709 cpuset_t active, other_cpus;
1713 cpuid = PCPU_GET(cpuid);
1714 other_cpus = all_cpus;
1715 CPU_CLR(cpuid, &other_cpus);
1716 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1719 active = pmap->pm_active;
1721 if (CPU_OVERLAP(&active, &other_cpus)) {
1723 act.invalidate = active;
1727 act.newpde = newpde;
1728 CPU_SET(cpuid, &active);
1729 smp_rendezvous_cpus(active,
1730 smp_no_rendevous_barrier, pmap_update_pde_action,
1731 pmap_update_pde_teardown, &act);
1733 pmap_update_pde_store(pmap, pde, newpde);
1734 if (CPU_ISSET(cpuid, &active))
1735 pmap_update_pde_invalidate(pmap, va, newpde);
1741 * Normal, non-SMP, invalidation functions.
1744 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1747 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1751 KASSERT(pmap->pm_type == PT_X86,
1752 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1754 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1756 else if (pmap_pcid_enabled)
1757 pmap->pm_pcids[0].pm_gen = 0;
1761 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1765 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1769 KASSERT(pmap->pm_type == PT_X86,
1770 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1772 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1773 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1775 } else if (pmap_pcid_enabled) {
1776 pmap->pm_pcids[0].pm_gen = 0;
1781 pmap_invalidate_all(pmap_t pmap)
1783 struct invpcid_descr d;
1785 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1789 KASSERT(pmap->pm_type == PT_X86,
1790 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
1792 if (pmap == kernel_pmap) {
1793 if (pmap_pcid_enabled && invpcid_works) {
1794 bzero(&d, sizeof(d));
1795 invpcid(&d, INVPCID_CTXGLOB);
1799 } else if (pmap == PCPU_GET(curpmap)) {
1800 if (pmap_pcid_enabled) {
1801 if (invpcid_works) {
1802 d.pcid = pmap->pm_pcids[0].pm_pcid;
1805 invpcid(&d, INVPCID_CTX);
1807 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[0].
1813 } else if (pmap_pcid_enabled) {
1814 pmap->pm_pcids[0].pm_gen = 0;
1819 pmap_invalidate_cache(void)
1826 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1829 pmap_update_pde_store(pmap, pde, newpde);
1830 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
1831 pmap_update_pde_invalidate(pmap, va, newpde);
1833 pmap->pm_pcids[0].pm_gen = 0;
1837 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
1840 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
1844 sva &= ~(vm_offset_t)cpu_clflush_line_size;
1846 KASSERT((sva & PAGE_MASK) == 0,
1847 ("pmap_invalidate_cache_range: sva not page-aligned"));
1848 KASSERT((eva & PAGE_MASK) == 0,
1849 ("pmap_invalidate_cache_range: eva not page-aligned"));
1852 if ((cpu_feature & CPUID_SS) != 0 && !force)
1853 ; /* If "Self Snoop" is supported and allowed, do nothing. */
1854 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
1855 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1857 * XXX: Some CPUs fault, hang, or trash the local APIC
1858 * registers if we use CLFLUSH on the local APIC
1859 * range. The local APIC is always uncached, so we
1860 * don't need to flush for that range anyway.
1862 if (pmap_kextract(sva) == lapic_paddr)
1866 * Otherwise, do per-cache line flush. Use the mfence
1867 * instruction to insure that previous stores are
1868 * included in the write-back. The processor
1869 * propagates flush to other processors in the cache
1873 for (; sva < eva; sva += cpu_clflush_line_size)
1876 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
1877 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1878 if (pmap_kextract(sva) == lapic_paddr)
1881 * Writes are ordered by CLFLUSH on Intel CPUs.
1883 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1885 for (; sva < eva; sva += cpu_clflush_line_size)
1887 if (cpu_vendor_id != CPU_VENDOR_INTEL)
1892 * No targeted cache flush methods are supported by CPU,
1893 * or the supplied range is bigger than 2MB.
1894 * Globally invalidate cache.
1896 pmap_invalidate_cache();
1901 * Remove the specified set of pages from the data and instruction caches.
1903 * In contrast to pmap_invalidate_cache_range(), this function does not
1904 * rely on the CPU's self-snoop feature, because it is intended for use
1905 * when moving pages into a different cache domain.
1908 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1910 vm_offset_t daddr, eva;
1914 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
1915 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1916 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
1917 pmap_invalidate_cache();
1919 if (useclflushopt || cpu_vendor_id != CPU_VENDOR_INTEL)
1921 for (i = 0; i < count; i++) {
1922 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
1923 eva = daddr + PAGE_SIZE;
1924 for (; daddr < eva; daddr += cpu_clflush_line_size) {
1931 if (useclflushopt || cpu_vendor_id != CPU_VENDOR_INTEL)
1937 * Routine: pmap_extract
1939 * Extract the physical page address associated
1940 * with the given map/virtual_address pair.
1943 pmap_extract(pmap_t pmap, vm_offset_t va)
1947 pt_entry_t *pte, PG_V;
1951 PG_V = pmap_valid_bit(pmap);
1953 pdpe = pmap_pdpe(pmap, va);
1954 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
1955 if ((*pdpe & PG_PS) != 0)
1956 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
1958 pde = pmap_pdpe_to_pde(pdpe, va);
1959 if ((*pde & PG_V) != 0) {
1960 if ((*pde & PG_PS) != 0) {
1961 pa = (*pde & PG_PS_FRAME) |
1964 pte = pmap_pde_to_pte(pde, va);
1965 pa = (*pte & PG_FRAME) |
1976 * Routine: pmap_extract_and_hold
1978 * Atomically extract and hold the physical page
1979 * with the given pmap and virtual address pair
1980 * if that mapping permits the given protection.
1983 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1985 pd_entry_t pde, *pdep;
1986 pt_entry_t pte, PG_RW, PG_V;
1992 PG_RW = pmap_rw_bit(pmap);
1993 PG_V = pmap_valid_bit(pmap);
1996 pdep = pmap_pde(pmap, va);
1997 if (pdep != NULL && (pde = *pdep)) {
1999 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2000 if (vm_page_pa_tryrelock(pmap, (pde &
2001 PG_PS_FRAME) | (va & PDRMASK), &pa))
2003 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
2008 pte = *pmap_pde_to_pte(pdep, va);
2010 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2011 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2014 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
2025 pmap_kextract(vm_offset_t va)
2030 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2031 pa = DMAP_TO_PHYS(va);
2035 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2038 * Beware of a concurrent promotion that changes the
2039 * PDE at this point! For example, vtopte() must not
2040 * be used to access the PTE because it would use the
2041 * new PDE. It is, however, safe to use the old PDE
2042 * because the page table page is preserved by the
2045 pa = *pmap_pde_to_pte(&pde, va);
2046 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2052 /***************************************************
2053 * Low level mapping routines.....
2054 ***************************************************/
2057 * Add a wired page to the kva.
2058 * Note: not SMP coherent.
2061 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2066 pte_store(pte, pa | X86_PG_RW | X86_PG_V | X86_PG_G);
2069 static __inline void
2070 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2076 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2077 pte_store(pte, pa | X86_PG_RW | X86_PG_V | X86_PG_G | cache_bits);
2081 * Remove a page from the kernel pagetables.
2082 * Note: not SMP coherent.
2085 pmap_kremove(vm_offset_t va)
2094 * Used to map a range of physical addresses into kernel
2095 * virtual address space.
2097 * The value passed in '*virt' is a suggested virtual address for
2098 * the mapping. Architectures which can support a direct-mapped
2099 * physical to virtual region can return the appropriate address
2100 * within that region, leaving '*virt' unchanged. Other
2101 * architectures should map the pages starting at '*virt' and
2102 * update '*virt' with the first usable address after the mapped
2106 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2108 return PHYS_TO_DMAP(start);
2113 * Add a list of wired pages to the kva
2114 * this routine is only used for temporary
2115 * kernel mappings that do not need to have
2116 * page modification or references recorded.
2117 * Note that old mappings are simply written
2118 * over. The page *must* be wired.
2119 * Note: SMP coherent. Uses a ranged shootdown IPI.
2122 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2124 pt_entry_t *endpte, oldpte, pa, *pte;
2130 endpte = pte + count;
2131 while (pte < endpte) {
2133 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2134 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2135 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2137 pte_store(pte, pa | X86_PG_G | X86_PG_RW | X86_PG_V);
2141 if (__predict_false((oldpte & X86_PG_V) != 0))
2142 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2147 * This routine tears out page mappings from the
2148 * kernel -- it is meant only for temporary mappings.
2149 * Note: SMP coherent. Uses a ranged shootdown IPI.
2152 pmap_qremove(vm_offset_t sva, int count)
2157 while (count-- > 0) {
2158 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2162 pmap_invalidate_range(kernel_pmap, sva, va);
2165 /***************************************************
2166 * Page table page management routines.....
2167 ***************************************************/
2168 static __inline void
2169 pmap_free_zero_pages(struct spglist *free)
2173 while ((m = SLIST_FIRST(free)) != NULL) {
2174 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2175 /* Preserve the page's PG_ZERO setting. */
2176 vm_page_free_toq(m);
2181 * Schedule the specified unused page table page to be freed. Specifically,
2182 * add the page to the specified list of pages that will be released to the
2183 * physical memory manager after the TLB has been updated.
2185 static __inline void
2186 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2187 boolean_t set_PG_ZERO)
2191 m->flags |= PG_ZERO;
2193 m->flags &= ~PG_ZERO;
2194 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2198 * Inserts the specified page table page into the specified pmap's collection
2199 * of idle page table pages. Each of a pmap's page table pages is responsible
2200 * for mapping a distinct range of virtual addresses. The pmap's collection is
2201 * ordered by this virtual address range.
2204 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2207 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2208 return (vm_radix_insert(&pmap->pm_root, mpte));
2212 * Looks for a page table page mapping the specified virtual address in the
2213 * specified pmap's collection of idle page table pages. Returns NULL if there
2214 * is no page table page corresponding to the specified virtual address.
2216 static __inline vm_page_t
2217 pmap_lookup_pt_page(pmap_t pmap, vm_offset_t va)
2220 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2221 return (vm_radix_lookup(&pmap->pm_root, pmap_pde_pindex(va)));
2225 * Removes the specified page table page from the specified pmap's collection
2226 * of idle page table pages. The specified page table page must be a member of
2227 * the pmap's collection.
2229 static __inline void
2230 pmap_remove_pt_page(pmap_t pmap, vm_page_t mpte)
2233 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2234 vm_radix_remove(&pmap->pm_root, mpte->pindex);
2238 * Decrements a page table page's wire count, which is used to record the
2239 * number of valid page table entries within the page. If the wire count
2240 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2241 * page table page was unmapped and FALSE otherwise.
2243 static inline boolean_t
2244 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2248 if (m->wire_count == 0) {
2249 _pmap_unwire_ptp(pmap, va, m, free);
2256 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2259 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2261 * unmap the page table page
2263 if (m->pindex >= (NUPDE + NUPDPE)) {
2266 pml4 = pmap_pml4e(pmap, va);
2268 } else if (m->pindex >= NUPDE) {
2271 pdp = pmap_pdpe(pmap, va);
2276 pd = pmap_pde(pmap, va);
2279 pmap_resident_count_dec(pmap, 1);
2280 if (m->pindex < NUPDE) {
2281 /* We just released a PT, unhold the matching PD */
2284 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2285 pmap_unwire_ptp(pmap, va, pdpg, free);
2287 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2288 /* We just released a PD, unhold the matching PDP */
2291 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2292 pmap_unwire_ptp(pmap, va, pdppg, free);
2296 * This is a release store so that the ordinary store unmapping
2297 * the page table page is globally performed before TLB shoot-
2300 atomic_subtract_rel_int(&vm_cnt.v_wire_count, 1);
2303 * Put page on a list so that it is released after
2304 * *ALL* TLB shootdown is done
2306 pmap_add_delayed_free_list(m, free, TRUE);
2310 * After removing a page table entry, this routine is used to
2311 * conditionally free the page, and manage the hold/wire counts.
2314 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2315 struct spglist *free)
2319 if (va >= VM_MAXUSER_ADDRESS)
2321 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2322 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2323 return (pmap_unwire_ptp(pmap, va, mpte, free));
2327 pmap_pinit0(pmap_t pmap)
2331 PMAP_LOCK_INIT(pmap);
2332 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2333 pmap->pm_cr3 = KPML4phys;
2334 pmap->pm_root.rt_root = 0;
2335 CPU_ZERO(&pmap->pm_active);
2336 TAILQ_INIT(&pmap->pm_pvchunk);
2337 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2338 pmap->pm_flags = pmap_flags;
2340 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2341 pmap->pm_pcids[i].pm_gen = 0;
2343 PCPU_SET(curpmap, kernel_pmap);
2344 pmap_activate(curthread);
2345 CPU_FILL(&kernel_pmap->pm_active);
2349 * Initialize a preallocated and zeroed pmap structure,
2350 * such as one in a vmspace structure.
2353 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2356 vm_paddr_t pml4phys;
2360 * allocate the page directory page
2362 while ((pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2363 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL)
2366 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2367 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2369 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2370 pmap->pm_pcids[i].pm_gen = 0;
2372 pmap->pm_cr3 = ~0; /* initialize to an invalid value */
2374 if ((pml4pg->flags & PG_ZERO) == 0)
2375 pagezero(pmap->pm_pml4);
2378 * Do not install the host kernel mappings in the nested page
2379 * tables. These mappings are meaningless in the guest physical
2382 if ((pmap->pm_type = pm_type) == PT_X86) {
2383 pmap->pm_cr3 = pml4phys;
2385 /* Wire in kernel global address entries. */
2386 for (i = 0; i < NKPML4E; i++) {
2387 pmap->pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) |
2388 X86_PG_RW | X86_PG_V | PG_U;
2390 for (i = 0; i < ndmpdpphys; i++) {
2391 pmap->pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) |
2392 X86_PG_RW | X86_PG_V | PG_U;
2395 /* install self-referential address mapping entry(s) */
2396 pmap->pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) |
2397 X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
2400 pmap->pm_root.rt_root = 0;
2401 CPU_ZERO(&pmap->pm_active);
2402 TAILQ_INIT(&pmap->pm_pvchunk);
2403 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2404 pmap->pm_flags = flags;
2405 pmap->pm_eptgen = 0;
2411 pmap_pinit(pmap_t pmap)
2414 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2418 * This routine is called if the desired page table page does not exist.
2420 * If page table page allocation fails, this routine may sleep before
2421 * returning NULL. It sleeps only if a lock pointer was given.
2423 * Note: If a page allocation fails at page table level two or three,
2424 * one or two pages may be held during the wait, only to be released
2425 * afterwards. This conservative approach is easily argued to avoid
2429 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2431 vm_page_t m, pdppg, pdpg;
2432 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2434 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2436 PG_A = pmap_accessed_bit(pmap);
2437 PG_M = pmap_modified_bit(pmap);
2438 PG_V = pmap_valid_bit(pmap);
2439 PG_RW = pmap_rw_bit(pmap);
2442 * Allocate a page table page.
2444 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2445 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2446 if (lockp != NULL) {
2447 RELEASE_PV_LIST_LOCK(lockp);
2449 PMAP_ASSERT_NOT_IN_DI();
2455 * Indicate the need to retry. While waiting, the page table
2456 * page may have been allocated.
2460 if ((m->flags & PG_ZERO) == 0)
2464 * Map the pagetable page into the process address space, if
2465 * it isn't already there.
2468 if (ptepindex >= (NUPDE + NUPDPE)) {
2470 vm_pindex_t pml4index;
2472 /* Wire up a new PDPE page */
2473 pml4index = ptepindex - (NUPDE + NUPDPE);
2474 pml4 = &pmap->pm_pml4[pml4index];
2475 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2477 } else if (ptepindex >= NUPDE) {
2478 vm_pindex_t pml4index;
2479 vm_pindex_t pdpindex;
2483 /* Wire up a new PDE page */
2484 pdpindex = ptepindex - NUPDE;
2485 pml4index = pdpindex >> NPML4EPGSHIFT;
2487 pml4 = &pmap->pm_pml4[pml4index];
2488 if ((*pml4 & PG_V) == 0) {
2489 /* Have to allocate a new pdp, recurse */
2490 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2493 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2494 vm_page_free_zero(m);
2498 /* Add reference to pdp page */
2499 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2500 pdppg->wire_count++;
2502 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2504 /* Now find the pdp page */
2505 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2506 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2509 vm_pindex_t pml4index;
2510 vm_pindex_t pdpindex;
2515 /* Wire up a new PTE page */
2516 pdpindex = ptepindex >> NPDPEPGSHIFT;
2517 pml4index = pdpindex >> NPML4EPGSHIFT;
2519 /* First, find the pdp and check that its valid. */
2520 pml4 = &pmap->pm_pml4[pml4index];
2521 if ((*pml4 & PG_V) == 0) {
2522 /* Have to allocate a new pd, recurse */
2523 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2526 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2527 vm_page_free_zero(m);
2530 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2531 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2533 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2534 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2535 if ((*pdp & PG_V) == 0) {
2536 /* Have to allocate a new pd, recurse */
2537 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2540 atomic_subtract_int(&vm_cnt.v_wire_count,
2542 vm_page_free_zero(m);
2546 /* Add reference to the pd page */
2547 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2551 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2553 /* Now we know where the page directory page is */
2554 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2555 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2558 pmap_resident_count_inc(pmap, 1);
2564 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2566 vm_pindex_t pdpindex, ptepindex;
2567 pdp_entry_t *pdpe, PG_V;
2570 PG_V = pmap_valid_bit(pmap);
2573 pdpe = pmap_pdpe(pmap, va);
2574 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2575 /* Add a reference to the pd page. */
2576 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2579 /* Allocate a pd page. */
2580 ptepindex = pmap_pde_pindex(va);
2581 pdpindex = ptepindex >> NPDPEPGSHIFT;
2582 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2583 if (pdpg == NULL && lockp != NULL)
2590 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2592 vm_pindex_t ptepindex;
2593 pd_entry_t *pd, PG_V;
2596 PG_V = pmap_valid_bit(pmap);
2599 * Calculate pagetable page index
2601 ptepindex = pmap_pde_pindex(va);
2604 * Get the page directory entry
2606 pd = pmap_pde(pmap, va);
2609 * This supports switching from a 2MB page to a
2612 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2613 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2615 * Invalidation of the 2MB page mapping may have caused
2616 * the deallocation of the underlying PD page.
2623 * If the page table page is mapped, we just increment the
2624 * hold count, and activate it.
2626 if (pd != NULL && (*pd & PG_V) != 0) {
2627 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2631 * Here if the pte page isn't mapped, or if it has been
2634 m = _pmap_allocpte(pmap, ptepindex, lockp);
2635 if (m == NULL && lockp != NULL)
2642 /***************************************************
2643 * Pmap allocation/deallocation routines.
2644 ***************************************************/
2647 * Release any resources held by the given physical map.
2648 * Called when a pmap initialized by pmap_pinit is being released.
2649 * Should only be called if the map contains no valid mappings.
2652 pmap_release(pmap_t pmap)
2657 KASSERT(pmap->pm_stats.resident_count == 0,
2658 ("pmap_release: pmap resident count %ld != 0",
2659 pmap->pm_stats.resident_count));
2660 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2661 ("pmap_release: pmap has reserved page table page(s)"));
2662 KASSERT(CPU_EMPTY(&pmap->pm_active),
2663 ("releasing active pmap %p", pmap));
2665 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2667 for (i = 0; i < NKPML4E; i++) /* KVA */
2668 pmap->pm_pml4[KPML4BASE + i] = 0;
2669 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
2670 pmap->pm_pml4[DMPML4I + i] = 0;
2671 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
2674 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2675 vm_page_free_zero(m);
2679 kvm_size(SYSCTL_HANDLER_ARGS)
2681 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2683 return sysctl_handle_long(oidp, &ksize, 0, req);
2685 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2686 0, 0, kvm_size, "LU", "Size of KVM");
2689 kvm_free(SYSCTL_HANDLER_ARGS)
2691 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2693 return sysctl_handle_long(oidp, &kfree, 0, req);
2695 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2696 0, 0, kvm_free, "LU", "Amount of KVM free");
2699 * grow the number of kernel page table entries, if needed
2702 pmap_growkernel(vm_offset_t addr)
2706 pd_entry_t *pde, newpdir;
2709 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2712 * Return if "addr" is within the range of kernel page table pages
2713 * that were preallocated during pmap bootstrap. Moreover, leave
2714 * "kernel_vm_end" and the kernel page table as they were.
2716 * The correctness of this action is based on the following
2717 * argument: vm_map_insert() allocates contiguous ranges of the
2718 * kernel virtual address space. It calls this function if a range
2719 * ends after "kernel_vm_end". If the kernel is mapped between
2720 * "kernel_vm_end" and "addr", then the range cannot begin at
2721 * "kernel_vm_end". In fact, its beginning address cannot be less
2722 * than the kernel. Thus, there is no immediate need to allocate
2723 * any new kernel page table pages between "kernel_vm_end" and
2726 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
2729 addr = roundup2(addr, NBPDR);
2730 if (addr - 1 >= kernel_map->max_offset)
2731 addr = kernel_map->max_offset;
2732 while (kernel_vm_end < addr) {
2733 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
2734 if ((*pdpe & X86_PG_V) == 0) {
2735 /* We need a new PDP entry */
2736 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
2737 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
2738 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2740 panic("pmap_growkernel: no memory to grow kernel");
2741 if ((nkpg->flags & PG_ZERO) == 0)
2742 pmap_zero_page(nkpg);
2743 paddr = VM_PAGE_TO_PHYS(nkpg);
2744 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
2745 X86_PG_A | X86_PG_M);
2746 continue; /* try again */
2748 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
2749 if ((*pde & X86_PG_V) != 0) {
2750 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2751 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2752 kernel_vm_end = kernel_map->max_offset;
2758 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
2759 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
2762 panic("pmap_growkernel: no memory to grow kernel");
2763 if ((nkpg->flags & PG_ZERO) == 0)
2764 pmap_zero_page(nkpg);
2765 paddr = VM_PAGE_TO_PHYS(nkpg);
2766 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
2767 pde_store(pde, newpdir);
2769 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2770 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2771 kernel_vm_end = kernel_map->max_offset;
2778 /***************************************************
2779 * page management routines.
2780 ***************************************************/
2782 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
2783 CTASSERT(_NPCM == 3);
2784 CTASSERT(_NPCPV == 168);
2786 static __inline struct pv_chunk *
2787 pv_to_chunk(pv_entry_t pv)
2790 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
2793 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
2795 #define PC_FREE0 0xfffffffffffffffful
2796 #define PC_FREE1 0xfffffffffffffffful
2797 #define PC_FREE2 0x000000fffffffffful
2799 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
2802 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2804 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2805 "Current number of pv entry chunks");
2806 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2807 "Current number of pv entry chunks allocated");
2808 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2809 "Current number of pv entry chunks frees");
2810 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
2811 "Number of times tried to get a chunk page but failed.");
2813 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
2814 static int pv_entry_spare;
2816 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2817 "Current number of pv entry frees");
2818 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
2819 "Current number of pv entry allocs");
2820 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2821 "Current number of pv entries");
2822 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2823 "Current number of spare pv entries");
2827 * We are in a serious low memory condition. Resort to
2828 * drastic measures to free some pages so we can allocate
2829 * another pv entry chunk.
2831 * Returns NULL if PV entries were reclaimed from the specified pmap.
2833 * We do not, however, unmap 2mpages because subsequent accesses will
2834 * allocate per-page pv entries until repromotion occurs, thereby
2835 * exacerbating the shortage of free pv entries.
2838 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
2840 struct pch new_tail;
2841 struct pv_chunk *pc;
2842 struct md_page *pvh;
2845 pt_entry_t *pte, tpte;
2846 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
2850 struct spglist free;
2852 int bit, field, freed;
2854 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2855 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
2858 PG_G = PG_A = PG_M = PG_RW = 0;
2860 TAILQ_INIT(&new_tail);
2861 pmap_delayed_invl_started();
2862 mtx_lock(&pv_chunks_mutex);
2863 while ((pc = TAILQ_FIRST(&pv_chunks)) != NULL && SLIST_EMPTY(&free)) {
2864 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2865 mtx_unlock(&pv_chunks_mutex);
2866 if (pmap != pc->pc_pmap) {
2868 pmap_invalidate_all(pmap);
2869 if (pmap != locked_pmap)
2872 pmap_delayed_invl_finished();
2873 pmap_delayed_invl_started();
2875 /* Avoid deadlock and lock recursion. */
2876 if (pmap > locked_pmap) {
2877 RELEASE_PV_LIST_LOCK(lockp);
2879 } else if (pmap != locked_pmap &&
2880 !PMAP_TRYLOCK(pmap)) {
2882 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2883 mtx_lock(&pv_chunks_mutex);
2886 PG_G = pmap_global_bit(pmap);
2887 PG_A = pmap_accessed_bit(pmap);
2888 PG_M = pmap_modified_bit(pmap);
2889 PG_RW = pmap_rw_bit(pmap);
2893 * Destroy every non-wired, 4 KB page mapping in the chunk.
2896 for (field = 0; field < _NPCM; field++) {
2897 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2898 inuse != 0; inuse &= ~(1UL << bit)) {
2900 pv = &pc->pc_pventry[field * 64 + bit];
2902 pde = pmap_pde(pmap, va);
2903 if ((*pde & PG_PS) != 0)
2905 pte = pmap_pde_to_pte(pde, va);
2906 if ((*pte & PG_W) != 0)
2908 tpte = pte_load_clear(pte);
2909 if ((tpte & PG_G) != 0)
2910 pmap_invalidate_page(pmap, va);
2911 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
2912 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
2914 if ((tpte & PG_A) != 0)
2915 vm_page_aflag_set(m, PGA_REFERENCED);
2916 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
2917 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
2919 if (TAILQ_EMPTY(&m->md.pv_list) &&
2920 (m->flags & PG_FICTITIOUS) == 0) {
2921 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
2922 if (TAILQ_EMPTY(&pvh->pv_list)) {
2923 vm_page_aflag_clear(m,
2927 pmap_delayed_invl_page(m);
2928 pc->pc_map[field] |= 1UL << bit;
2929 pmap_unuse_pt(pmap, va, *pde, &free);
2934 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2935 mtx_lock(&pv_chunks_mutex);
2938 /* Every freed mapping is for a 4 KB page. */
2939 pmap_resident_count_dec(pmap, freed);
2940 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
2941 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
2942 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
2943 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2944 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
2945 pc->pc_map[2] == PC_FREE2) {
2946 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
2947 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
2948 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
2949 /* Entire chunk is free; return it. */
2950 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
2951 dump_drop_page(m_pc->phys_addr);
2952 mtx_lock(&pv_chunks_mutex);
2955 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2956 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2957 mtx_lock(&pv_chunks_mutex);
2958 /* One freed pv entry in locked_pmap is sufficient. */
2959 if (pmap == locked_pmap)
2962 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
2963 mtx_unlock(&pv_chunks_mutex);
2965 pmap_invalidate_all(pmap);
2966 if (pmap != locked_pmap)
2969 pmap_delayed_invl_finished();
2970 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
2971 m_pc = SLIST_FIRST(&free);
2972 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2973 /* Recycle a freed page table page. */
2974 m_pc->wire_count = 1;
2975 atomic_add_int(&vm_cnt.v_wire_count, 1);
2977 pmap_free_zero_pages(&free);
2982 * free the pv_entry back to the free list
2985 free_pv_entry(pmap_t pmap, pv_entry_t pv)
2987 struct pv_chunk *pc;
2988 int idx, field, bit;
2990 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2991 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
2992 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
2993 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
2994 pc = pv_to_chunk(pv);
2995 idx = pv - &pc->pc_pventry[0];
2998 pc->pc_map[field] |= 1ul << bit;
2999 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3000 pc->pc_map[2] != PC_FREE2) {
3001 /* 98% of the time, pc is already at the head of the list. */
3002 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3003 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3004 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3008 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3013 free_pv_chunk(struct pv_chunk *pc)
3017 mtx_lock(&pv_chunks_mutex);
3018 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3019 mtx_unlock(&pv_chunks_mutex);
3020 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3021 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3022 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3023 /* entire chunk is free, return it */
3024 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3025 dump_drop_page(m->phys_addr);
3026 vm_page_unwire(m, PQ_NONE);
3031 * Returns a new PV entry, allocating a new PV chunk from the system when
3032 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3033 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3036 * The given PV list lock may be released.
3039 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3043 struct pv_chunk *pc;
3046 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3047 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3049 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3051 for (field = 0; field < _NPCM; field++) {
3052 if (pc->pc_map[field]) {
3053 bit = bsfq(pc->pc_map[field]);
3057 if (field < _NPCM) {
3058 pv = &pc->pc_pventry[field * 64 + bit];
3059 pc->pc_map[field] &= ~(1ul << bit);
3060 /* If this was the last item, move it to tail */
3061 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3062 pc->pc_map[2] == 0) {
3063 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3064 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3067 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3068 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3072 /* No free items, allocate another chunk */
3073 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3076 if (lockp == NULL) {
3077 PV_STAT(pc_chunk_tryfail++);
3080 m = reclaim_pv_chunk(pmap, lockp);
3084 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3085 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3086 dump_add_page(m->phys_addr);
3087 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3089 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3090 pc->pc_map[1] = PC_FREE1;
3091 pc->pc_map[2] = PC_FREE2;
3092 mtx_lock(&pv_chunks_mutex);
3093 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3094 mtx_unlock(&pv_chunks_mutex);
3095 pv = &pc->pc_pventry[0];
3096 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3097 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3098 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3103 * Returns the number of one bits within the given PV chunk map.
3105 * The erratas for Intel processors state that "POPCNT Instruction May
3106 * Take Longer to Execute Than Expected". It is believed that the
3107 * issue is the spurious dependency on the destination register.
3108 * Provide a hint to the register rename logic that the destination
3109 * value is overwritten, by clearing it, as suggested in the
3110 * optimization manual. It should be cheap for unaffected processors
3113 * Reference numbers for erratas are
3114 * 4th Gen Core: HSD146
3115 * 5th Gen Core: BDM85
3116 * 6th Gen Core: SKL029
3119 popcnt_pc_map_pq(uint64_t *map)
3123 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3124 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3125 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3126 : "=&r" (result), "=&r" (tmp)
3127 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3132 * Ensure that the number of spare PV entries in the specified pmap meets or
3133 * exceeds the given count, "needed".
3135 * The given PV list lock may be released.
3138 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3140 struct pch new_tail;
3141 struct pv_chunk *pc;
3145 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3146 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3149 * Newly allocated PV chunks must be stored in a private list until
3150 * the required number of PV chunks have been allocated. Otherwise,
3151 * reclaim_pv_chunk() could recycle one of these chunks. In
3152 * contrast, these chunks must be added to the pmap upon allocation.
3154 TAILQ_INIT(&new_tail);
3157 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3159 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3160 bit_count((bitstr_t *)pc->pc_map, 0,
3161 sizeof(pc->pc_map) * NBBY, &free);
3164 free = popcnt_pc_map_pq(pc->pc_map);
3168 if (avail >= needed)
3171 for (; avail < needed; avail += _NPCPV) {
3172 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3175 m = reclaim_pv_chunk(pmap, lockp);
3179 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3180 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3181 dump_add_page(m->phys_addr);
3182 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3184 pc->pc_map[0] = PC_FREE0;
3185 pc->pc_map[1] = PC_FREE1;
3186 pc->pc_map[2] = PC_FREE2;
3187 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3188 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3189 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3191 if (!TAILQ_EMPTY(&new_tail)) {
3192 mtx_lock(&pv_chunks_mutex);
3193 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3194 mtx_unlock(&pv_chunks_mutex);
3199 * First find and then remove the pv entry for the specified pmap and virtual
3200 * address from the specified pv list. Returns the pv entry if found and NULL
3201 * otherwise. This operation can be performed on pv lists for either 4KB or
3202 * 2MB page mappings.
3204 static __inline pv_entry_t
3205 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3209 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3210 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3211 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3220 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3221 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3222 * entries for each of the 4KB page mappings.
3225 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3226 struct rwlock **lockp)
3228 struct md_page *pvh;
3229 struct pv_chunk *pc;
3231 vm_offset_t va_last;
3235 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3236 KASSERT((pa & PDRMASK) == 0,
3237 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3238 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3241 * Transfer the 2mpage's pv entry for this mapping to the first
3242 * page's pv list. Once this transfer begins, the pv list lock
3243 * must not be released until the last pv entry is reinstantiated.
3245 pvh = pa_to_pvh(pa);
3246 va = trunc_2mpage(va);
3247 pv = pmap_pvh_remove(pvh, pmap, va);
3248 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3249 m = PHYS_TO_VM_PAGE(pa);
3250 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3252 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3253 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3254 va_last = va + NBPDR - PAGE_SIZE;
3256 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3257 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3258 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3259 for (field = 0; field < _NPCM; field++) {
3260 while (pc->pc_map[field]) {
3261 bit = bsfq(pc->pc_map[field]);
3262 pc->pc_map[field] &= ~(1ul << bit);
3263 pv = &pc->pc_pventry[field * 64 + bit];
3267 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3268 ("pmap_pv_demote_pde: page %p is not managed", m));
3269 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3275 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3276 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3279 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3280 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3281 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3283 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3284 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3288 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3289 * replace the many pv entries for the 4KB page mappings by a single pv entry
3290 * for the 2MB page mapping.
3293 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3294 struct rwlock **lockp)
3296 struct md_page *pvh;
3298 vm_offset_t va_last;
3301 KASSERT((pa & PDRMASK) == 0,
3302 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3303 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3306 * Transfer the first page's pv entry for this mapping to the 2mpage's
3307 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3308 * a transfer avoids the possibility that get_pv_entry() calls
3309 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3310 * mappings that is being promoted.
3312 m = PHYS_TO_VM_PAGE(pa);
3313 va = trunc_2mpage(va);
3314 pv = pmap_pvh_remove(&m->md, pmap, va);
3315 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3316 pvh = pa_to_pvh(pa);
3317 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3319 /* Free the remaining NPTEPG - 1 pv entries. */
3320 va_last = va + NBPDR - PAGE_SIZE;
3324 pmap_pvh_free(&m->md, pmap, va);
3325 } while (va < va_last);
3329 * First find and then destroy the pv entry for the specified pmap and virtual
3330 * address. This operation can be performed on pv lists for either 4KB or 2MB
3334 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3338 pv = pmap_pvh_remove(pvh, pmap, va);
3339 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3340 free_pv_entry(pmap, pv);
3344 * Conditionally create the PV entry for a 4KB page mapping if the required
3345 * memory can be allocated without resorting to reclamation.
3348 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3349 struct rwlock **lockp)
3353 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3354 /* Pass NULL instead of the lock pointer to disable reclamation. */
3355 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3357 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3358 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3366 * Conditionally create the PV entry for a 2MB page mapping if the required
3367 * memory can be allocated without resorting to reclamation.
3370 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3371 struct rwlock **lockp)
3373 struct md_page *pvh;
3376 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3377 /* Pass NULL instead of the lock pointer to disable reclamation. */
3378 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3380 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3381 pvh = pa_to_pvh(pa);
3382 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3390 * Fills a page table page with mappings to consecutive physical pages.
3393 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3397 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3399 newpte += PAGE_SIZE;
3404 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3405 * mapping is invalidated.
3408 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3410 struct rwlock *lock;
3414 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3421 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3422 struct rwlock **lockp)
3424 pd_entry_t newpde, oldpde;
3425 pt_entry_t *firstpte, newpte;
3426 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3429 struct spglist free;
3432 PG_G = pmap_global_bit(pmap);
3433 PG_A = pmap_accessed_bit(pmap);
3434 PG_M = pmap_modified_bit(pmap);
3435 PG_RW = pmap_rw_bit(pmap);
3436 PG_V = pmap_valid_bit(pmap);
3437 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3439 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3441 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3442 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3443 if ((oldpde & PG_A) != 0 && (mpte = pmap_lookup_pt_page(pmap, va)) !=
3445 pmap_remove_pt_page(pmap, mpte);
3447 KASSERT((oldpde & PG_W) == 0,
3448 ("pmap_demote_pde: page table page for a wired mapping"
3452 * Invalidate the 2MB page mapping and return "failure" if the
3453 * mapping was never accessed or the allocation of the new
3454 * page table page fails. If the 2MB page mapping belongs to
3455 * the direct map region of the kernel's address space, then
3456 * the page allocation request specifies the highest possible
3457 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3458 * normal. Page table pages are preallocated for every other
3459 * part of the kernel address space, so the direct map region
3460 * is the only part of the kernel address space that must be
3463 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3464 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3465 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3466 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3468 pmap_remove_pde(pmap, pde, trunc_2mpage(va), &free,
3470 pmap_invalidate_page(pmap, trunc_2mpage(va));
3471 pmap_free_zero_pages(&free);
3472 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3473 " in pmap %p", va, pmap);
3476 if (va < VM_MAXUSER_ADDRESS)
3477 pmap_resident_count_inc(pmap, 1);
3479 mptepa = VM_PAGE_TO_PHYS(mpte);
3480 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3481 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3482 KASSERT((oldpde & PG_A) != 0,
3483 ("pmap_demote_pde: oldpde is missing PG_A"));
3484 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3485 ("pmap_demote_pde: oldpde is missing PG_M"));
3486 newpte = oldpde & ~PG_PS;
3487 newpte = pmap_swap_pat(pmap, newpte);
3490 * If the page table page is new, initialize it.
3492 if (mpte->wire_count == 1) {
3493 mpte->wire_count = NPTEPG;
3494 pmap_fill_ptp(firstpte, newpte);
3496 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3497 ("pmap_demote_pde: firstpte and newpte map different physical"
3501 * If the mapping has changed attributes, update the page table
3504 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3505 pmap_fill_ptp(firstpte, newpte);
3508 * The spare PV entries must be reserved prior to demoting the
3509 * mapping, that is, prior to changing the PDE. Otherwise, the state
3510 * of the PDE and the PV lists will be inconsistent, which can result
3511 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3512 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3513 * PV entry for the 2MB page mapping that is being demoted.
3515 if ((oldpde & PG_MANAGED) != 0)
3516 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3519 * Demote the mapping. This pmap is locked. The old PDE has
3520 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3521 * set. Thus, there is no danger of a race with another
3522 * processor changing the setting of PG_A and/or PG_M between
3523 * the read above and the store below.
3525 if (workaround_erratum383)
3526 pmap_update_pde(pmap, va, pde, newpde);
3528 pde_store(pde, newpde);
3531 * Invalidate a stale recursive mapping of the page table page.
3533 if (va >= VM_MAXUSER_ADDRESS)
3534 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3537 * Demote the PV entry.
3539 if ((oldpde & PG_MANAGED) != 0)
3540 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3542 atomic_add_long(&pmap_pde_demotions, 1);
3543 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3544 " in pmap %p", va, pmap);
3549 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3552 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3558 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3559 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3560 mpte = pmap_lookup_pt_page(pmap, va);
3562 panic("pmap_remove_kernel_pde: Missing pt page.");
3564 pmap_remove_pt_page(pmap, mpte);
3565 mptepa = VM_PAGE_TO_PHYS(mpte);
3566 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3569 * Initialize the page table page.
3571 pagezero((void *)PHYS_TO_DMAP(mptepa));
3574 * Demote the mapping.
3576 if (workaround_erratum383)
3577 pmap_update_pde(pmap, va, pde, newpde);
3579 pde_store(pde, newpde);
3582 * Invalidate a stale recursive mapping of the page table page.
3584 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3588 * pmap_remove_pde: do the things to unmap a superpage in a process
3591 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
3592 struct spglist *free, struct rwlock **lockp)
3594 struct md_page *pvh;
3596 vm_offset_t eva, va;
3598 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3600 PG_G = pmap_global_bit(pmap);
3601 PG_A = pmap_accessed_bit(pmap);
3602 PG_M = pmap_modified_bit(pmap);
3603 PG_RW = pmap_rw_bit(pmap);
3605 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3606 KASSERT((sva & PDRMASK) == 0,
3607 ("pmap_remove_pde: sva is not 2mpage aligned"));
3608 oldpde = pte_load_clear(pdq);
3610 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
3613 * Machines that don't support invlpg, also don't support
3617 pmap_invalidate_page(kernel_pmap, sva);
3618 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
3619 if (oldpde & PG_MANAGED) {
3620 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
3621 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
3622 pmap_pvh_free(pvh, pmap, sva);
3624 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3625 va < eva; va += PAGE_SIZE, m++) {
3626 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3629 vm_page_aflag_set(m, PGA_REFERENCED);
3630 if (TAILQ_EMPTY(&m->md.pv_list) &&
3631 TAILQ_EMPTY(&pvh->pv_list))
3632 vm_page_aflag_clear(m, PGA_WRITEABLE);
3633 pmap_delayed_invl_page(m);
3636 if (pmap == kernel_pmap) {
3637 pmap_remove_kernel_pde(pmap, pdq, sva);
3639 mpte = pmap_lookup_pt_page(pmap, sva);
3641 pmap_remove_pt_page(pmap, mpte);
3642 pmap_resident_count_dec(pmap, 1);
3643 KASSERT(mpte->wire_count == NPTEPG,
3644 ("pmap_remove_pde: pte page wire count error"));
3645 mpte->wire_count = 0;
3646 pmap_add_delayed_free_list(mpte, free, FALSE);
3647 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3650 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
3654 * pmap_remove_pte: do the things to unmap a page in a process
3657 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
3658 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
3660 struct md_page *pvh;
3661 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
3664 PG_A = pmap_accessed_bit(pmap);
3665 PG_M = pmap_modified_bit(pmap);
3666 PG_RW = pmap_rw_bit(pmap);
3668 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3669 oldpte = pte_load_clear(ptq);
3671 pmap->pm_stats.wired_count -= 1;
3672 pmap_resident_count_dec(pmap, 1);
3673 if (oldpte & PG_MANAGED) {
3674 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
3675 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3678 vm_page_aflag_set(m, PGA_REFERENCED);
3679 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3680 pmap_pvh_free(&m->md, pmap, va);
3681 if (TAILQ_EMPTY(&m->md.pv_list) &&
3682 (m->flags & PG_FICTITIOUS) == 0) {
3683 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3684 if (TAILQ_EMPTY(&pvh->pv_list))
3685 vm_page_aflag_clear(m, PGA_WRITEABLE);
3687 pmap_delayed_invl_page(m);
3689 return (pmap_unuse_pt(pmap, va, ptepde, free));
3693 * Remove a single page from a process address space
3696 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
3697 struct spglist *free)
3699 struct rwlock *lock;
3700 pt_entry_t *pte, PG_V;
3702 PG_V = pmap_valid_bit(pmap);
3703 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3704 if ((*pde & PG_V) == 0)
3706 pte = pmap_pde_to_pte(pde, va);
3707 if ((*pte & PG_V) == 0)
3710 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
3713 pmap_invalidate_page(pmap, va);
3717 * Remove the given range of addresses from the specified map.
3719 * It is assumed that the start and end are properly
3720 * rounded to the page size.
3723 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3725 struct rwlock *lock;
3726 vm_offset_t va, va_next;
3727 pml4_entry_t *pml4e;
3729 pd_entry_t ptpaddr, *pde;
3730 pt_entry_t *pte, PG_G, PG_V;
3731 struct spglist free;
3734 PG_G = pmap_global_bit(pmap);
3735 PG_V = pmap_valid_bit(pmap);
3738 * Perform an unsynchronized read. This is, however, safe.
3740 if (pmap->pm_stats.resident_count == 0)
3746 pmap_delayed_invl_started();
3750 * special handling of removing one page. a very
3751 * common operation and easy to short circuit some
3754 if (sva + PAGE_SIZE == eva) {
3755 pde = pmap_pde(pmap, sva);
3756 if (pde && (*pde & PG_PS) == 0) {
3757 pmap_remove_page(pmap, sva, pde, &free);
3763 for (; sva < eva; sva = va_next) {
3765 if (pmap->pm_stats.resident_count == 0)
3768 pml4e = pmap_pml4e(pmap, sva);
3769 if ((*pml4e & PG_V) == 0) {
3770 va_next = (sva + NBPML4) & ~PML4MASK;
3776 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
3777 if ((*pdpe & PG_V) == 0) {
3778 va_next = (sva + NBPDP) & ~PDPMASK;
3785 * Calculate index for next page table.
3787 va_next = (sva + NBPDR) & ~PDRMASK;
3791 pde = pmap_pdpe_to_pde(pdpe, sva);
3795 * Weed out invalid mappings.
3801 * Check for large page.
3803 if ((ptpaddr & PG_PS) != 0) {
3805 * Are we removing the entire large page? If not,
3806 * demote the mapping and fall through.
3808 if (sva + NBPDR == va_next && eva >= va_next) {
3810 * The TLB entry for a PG_G mapping is
3811 * invalidated by pmap_remove_pde().
3813 if ((ptpaddr & PG_G) == 0)
3815 pmap_remove_pde(pmap, pde, sva, &free, &lock);
3817 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
3819 /* The large page mapping was destroyed. */
3826 * Limit our scan to either the end of the va represented
3827 * by the current page table page, or to the end of the
3828 * range being removed.
3834 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
3837 if (va != va_next) {
3838 pmap_invalidate_range(pmap, va, sva);
3843 if ((*pte & PG_G) == 0)
3845 else if (va == va_next)
3847 if (pmap_remove_pte(pmap, pte, sva, ptpaddr, &free,
3854 pmap_invalidate_range(pmap, va, sva);
3860 pmap_invalidate_all(pmap);
3862 pmap_delayed_invl_finished();
3863 pmap_free_zero_pages(&free);
3867 * Routine: pmap_remove_all
3869 * Removes this physical page from
3870 * all physical maps in which it resides.
3871 * Reflects back modify bits to the pager.
3874 * Original versions of this routine were very
3875 * inefficient because they iteratively called
3876 * pmap_remove (slow...)
3880 pmap_remove_all(vm_page_t m)
3882 struct md_page *pvh;
3885 struct rwlock *lock;
3886 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
3889 struct spglist free;
3890 int pvh_gen, md_gen;
3892 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3893 ("pmap_remove_all: page %p is not managed", m));
3895 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3896 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
3897 pa_to_pvh(VM_PAGE_TO_PHYS(m));
3900 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
3902 if (!PMAP_TRYLOCK(pmap)) {
3903 pvh_gen = pvh->pv_gen;
3907 if (pvh_gen != pvh->pv_gen) {
3914 pde = pmap_pde(pmap, va);
3915 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
3918 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3920 if (!PMAP_TRYLOCK(pmap)) {
3921 pvh_gen = pvh->pv_gen;
3922 md_gen = m->md.pv_gen;
3926 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
3932 PG_A = pmap_accessed_bit(pmap);
3933 PG_M = pmap_modified_bit(pmap);
3934 PG_RW = pmap_rw_bit(pmap);
3935 pmap_resident_count_dec(pmap, 1);
3936 pde = pmap_pde(pmap, pv->pv_va);
3937 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
3938 " a 2mpage in page %p's pv list", m));
3939 pte = pmap_pde_to_pte(pde, pv->pv_va);
3940 tpte = pte_load_clear(pte);
3942 pmap->pm_stats.wired_count--;
3944 vm_page_aflag_set(m, PGA_REFERENCED);
3947 * Update the vm_page_t clean and reference bits.
3949 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3951 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
3952 pmap_invalidate_page(pmap, pv->pv_va);
3953 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3955 free_pv_entry(pmap, pv);
3958 vm_page_aflag_clear(m, PGA_WRITEABLE);
3960 pmap_delayed_invl_wait(m);
3961 pmap_free_zero_pages(&free);
3965 * pmap_protect_pde: do the things to protect a 2mpage in a process
3968 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
3970 pd_entry_t newpde, oldpde;
3971 vm_offset_t eva, va;
3973 boolean_t anychanged;
3974 pt_entry_t PG_G, PG_M, PG_RW;
3976 PG_G = pmap_global_bit(pmap);
3977 PG_M = pmap_modified_bit(pmap);
3978 PG_RW = pmap_rw_bit(pmap);
3980 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3981 KASSERT((sva & PDRMASK) == 0,
3982 ("pmap_protect_pde: sva is not 2mpage aligned"));
3985 oldpde = newpde = *pde;
3986 if (oldpde & PG_MANAGED) {
3988 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3989 va < eva; va += PAGE_SIZE, m++)
3990 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3993 if ((prot & VM_PROT_WRITE) == 0)
3994 newpde &= ~(PG_RW | PG_M);
3995 if ((prot & VM_PROT_EXECUTE) == 0)
3997 if (newpde != oldpde) {
3998 if (!atomic_cmpset_long(pde, oldpde, newpde))
4001 pmap_invalidate_page(pmap, sva);
4005 return (anychanged);
4009 * Set the physical protection on the
4010 * specified range of this map as requested.
4013 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4015 vm_offset_t va_next;
4016 pml4_entry_t *pml4e;
4018 pd_entry_t ptpaddr, *pde;
4019 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4020 boolean_t anychanged;
4022 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4023 if (prot == VM_PROT_NONE) {
4024 pmap_remove(pmap, sva, eva);
4028 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4029 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4032 PG_G = pmap_global_bit(pmap);
4033 PG_M = pmap_modified_bit(pmap);
4034 PG_V = pmap_valid_bit(pmap);
4035 PG_RW = pmap_rw_bit(pmap);
4039 for (; sva < eva; sva = va_next) {
4041 pml4e = pmap_pml4e(pmap, sva);
4042 if ((*pml4e & PG_V) == 0) {
4043 va_next = (sva + NBPML4) & ~PML4MASK;
4049 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4050 if ((*pdpe & PG_V) == 0) {
4051 va_next = (sva + NBPDP) & ~PDPMASK;
4057 va_next = (sva + NBPDR) & ~PDRMASK;
4061 pde = pmap_pdpe_to_pde(pdpe, sva);
4065 * Weed out invalid mappings.
4071 * Check for large page.
4073 if ((ptpaddr & PG_PS) != 0) {
4075 * Are we protecting the entire large page? If not,
4076 * demote the mapping and fall through.
4078 if (sva + NBPDR == va_next && eva >= va_next) {
4080 * The TLB entry for a PG_G mapping is
4081 * invalidated by pmap_protect_pde().
4083 if (pmap_protect_pde(pmap, pde, sva, prot))
4086 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4088 * The large page mapping was destroyed.
4097 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4099 pt_entry_t obits, pbits;
4103 obits = pbits = *pte;
4104 if ((pbits & PG_V) == 0)
4107 if ((prot & VM_PROT_WRITE) == 0) {
4108 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4109 (PG_MANAGED | PG_M | PG_RW)) {
4110 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4113 pbits &= ~(PG_RW | PG_M);
4115 if ((prot & VM_PROT_EXECUTE) == 0)
4118 if (pbits != obits) {
4119 if (!atomic_cmpset_long(pte, obits, pbits))
4122 pmap_invalidate_page(pmap, sva);
4129 pmap_invalidate_all(pmap);
4134 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4135 * single page table page (PTP) to a single 2MB page mapping. For promotion
4136 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4137 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4138 * identical characteristics.
4141 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4142 struct rwlock **lockp)
4145 pt_entry_t *firstpte, oldpte, pa, *pte;
4146 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4150 PG_A = pmap_accessed_bit(pmap);
4151 PG_G = pmap_global_bit(pmap);
4152 PG_M = pmap_modified_bit(pmap);
4153 PG_V = pmap_valid_bit(pmap);
4154 PG_RW = pmap_rw_bit(pmap);
4155 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4157 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4160 * Examine the first PTE in the specified PTP. Abort if this PTE is
4161 * either invalid, unused, or does not map the first 4KB physical page
4162 * within a 2MB page.
4164 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4167 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4168 atomic_add_long(&pmap_pde_p_failures, 1);
4169 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4170 " in pmap %p", va, pmap);
4173 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4175 * When PG_M is already clear, PG_RW can be cleared without
4176 * a TLB invalidation.
4178 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4184 * Examine each of the other PTEs in the specified PTP. Abort if this
4185 * PTE maps an unexpected 4KB physical page or does not have identical
4186 * characteristics to the first PTE.
4188 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4189 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4192 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4193 atomic_add_long(&pmap_pde_p_failures, 1);
4194 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4195 " in pmap %p", va, pmap);
4198 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4200 * When PG_M is already clear, PG_RW can be cleared
4201 * without a TLB invalidation.
4203 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4206 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4207 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4208 (va & ~PDRMASK), pmap);
4210 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4211 atomic_add_long(&pmap_pde_p_failures, 1);
4212 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4213 " in pmap %p", va, pmap);
4220 * Save the page table page in its current state until the PDE
4221 * mapping the superpage is demoted by pmap_demote_pde() or
4222 * destroyed by pmap_remove_pde().
4224 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4225 KASSERT(mpte >= vm_page_array &&
4226 mpte < &vm_page_array[vm_page_array_size],
4227 ("pmap_promote_pde: page table page is out of range"));
4228 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4229 ("pmap_promote_pde: page table page's pindex is wrong"));
4230 if (pmap_insert_pt_page(pmap, mpte)) {
4231 atomic_add_long(&pmap_pde_p_failures, 1);
4233 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4239 * Promote the pv entries.
4241 if ((newpde & PG_MANAGED) != 0)
4242 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4245 * Propagate the PAT index to its proper position.
4247 newpde = pmap_swap_pat(pmap, newpde);
4250 * Map the superpage.
4252 if (workaround_erratum383)
4253 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4255 pde_store(pde, PG_PS | newpde);
4257 atomic_add_long(&pmap_pde_promotions, 1);
4258 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4259 " in pmap %p", va, pmap);
4263 * Insert the given physical page (p) at
4264 * the specified virtual address (v) in the
4265 * target physical map with the protection requested.
4267 * If specified, the page will be wired down, meaning
4268 * that the related pte can not be reclaimed.
4270 * NB: This is the only routine which MAY NOT lazy-evaluate
4271 * or lose information. That is, this routine must actually
4272 * insert this page into the given map NOW.
4274 * When destroying both a page table and PV entry, this function
4275 * performs the TLB invalidation before releasing the PV list
4276 * lock, so we do not need pmap_delayed_invl_page() calls here.
4279 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4280 u_int flags, int8_t psind __unused)
4282 struct rwlock *lock;
4284 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4285 pt_entry_t newpte, origpte;
4291 PG_A = pmap_accessed_bit(pmap);
4292 PG_G = pmap_global_bit(pmap);
4293 PG_M = pmap_modified_bit(pmap);
4294 PG_V = pmap_valid_bit(pmap);
4295 PG_RW = pmap_rw_bit(pmap);
4297 va = trunc_page(va);
4298 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4299 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4300 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4302 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4303 va >= kmi.clean_eva,
4304 ("pmap_enter: managed mapping within the clean submap"));
4305 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4306 VM_OBJECT_ASSERT_LOCKED(m->object);
4307 pa = VM_PAGE_TO_PHYS(m);
4308 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4309 if ((flags & VM_PROT_WRITE) != 0)
4311 if ((prot & VM_PROT_WRITE) != 0)
4313 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4314 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4315 if ((prot & VM_PROT_EXECUTE) == 0)
4317 if ((flags & PMAP_ENTER_WIRED) != 0)
4319 if (va < VM_MAXUSER_ADDRESS)
4321 if (pmap == kernel_pmap)
4323 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, 0);
4326 * Set modified bit gratuitously for writeable mappings if
4327 * the page is unmanaged. We do not want to take a fault
4328 * to do the dirty bit accounting for these mappings.
4330 if ((m->oflags & VPO_UNMANAGED) != 0) {
4331 if ((newpte & PG_RW) != 0)
4341 * In the case that a page table page is not
4342 * resident, we are creating it here.
4345 pde = pmap_pde(pmap, va);
4346 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4347 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4348 pte = pmap_pde_to_pte(pde, va);
4349 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4350 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4353 } else if (va < VM_MAXUSER_ADDRESS) {
4355 * Here if the pte page isn't mapped, or if it has been
4358 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4359 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4360 nosleep ? NULL : &lock);
4361 if (mpte == NULL && nosleep) {
4365 return (KERN_RESOURCE_SHORTAGE);
4369 panic("pmap_enter: invalid page directory va=%#lx", va);
4374 * Is the specified virtual address already mapped?
4376 if ((origpte & PG_V) != 0) {
4378 * Wiring change, just update stats. We don't worry about
4379 * wiring PT pages as they remain resident as long as there
4380 * are valid mappings in them. Hence, if a user page is wired,
4381 * the PT page will be also.
4383 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4384 pmap->pm_stats.wired_count++;
4385 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4386 pmap->pm_stats.wired_count--;
4389 * Remove the extra PT page reference.
4393 KASSERT(mpte->wire_count > 0,
4394 ("pmap_enter: missing reference to page table page,"
4399 * Has the physical page changed?
4401 opa = origpte & PG_FRAME;
4404 * No, might be a protection or wiring change.
4406 if ((origpte & PG_MANAGED) != 0) {
4407 newpte |= PG_MANAGED;
4408 if ((newpte & PG_RW) != 0)
4409 vm_page_aflag_set(m, PGA_WRITEABLE);
4411 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4417 * Increment the counters.
4419 if ((newpte & PG_W) != 0)
4420 pmap->pm_stats.wired_count++;
4421 pmap_resident_count_inc(pmap, 1);
4425 * Enter on the PV list if part of our managed memory.
4427 if ((m->oflags & VPO_UNMANAGED) == 0) {
4428 newpte |= PG_MANAGED;
4429 pv = get_pv_entry(pmap, &lock);
4431 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4432 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4434 if ((newpte & PG_RW) != 0)
4435 vm_page_aflag_set(m, PGA_WRITEABLE);
4441 if ((origpte & PG_V) != 0) {
4443 origpte = pte_load_store(pte, newpte);
4444 opa = origpte & PG_FRAME;
4446 if ((origpte & PG_MANAGED) != 0) {
4447 om = PHYS_TO_VM_PAGE(opa);
4448 if ((origpte & (PG_M | PG_RW)) == (PG_M |
4451 if ((origpte & PG_A) != 0)
4452 vm_page_aflag_set(om, PGA_REFERENCED);
4453 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4454 pmap_pvh_free(&om->md, pmap, va);
4455 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4456 TAILQ_EMPTY(&om->md.pv_list) &&
4457 ((om->flags & PG_FICTITIOUS) != 0 ||
4458 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4459 vm_page_aflag_clear(om, PGA_WRITEABLE);
4461 } else if ((newpte & PG_M) == 0 && (origpte & (PG_M |
4462 PG_RW)) == (PG_M | PG_RW)) {
4463 if ((origpte & PG_MANAGED) != 0)
4467 * Although the PTE may still have PG_RW set, TLB
4468 * invalidation may nonetheless be required because
4469 * the PTE no longer has PG_M set.
4471 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4473 * This PTE change does not require TLB invalidation.
4477 if ((origpte & PG_A) != 0)
4478 pmap_invalidate_page(pmap, va);
4480 pte_store(pte, newpte);
4485 * If both the page table page and the reservation are fully
4486 * populated, then attempt promotion.
4488 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4489 pmap_ps_enabled(pmap) &&
4490 (m->flags & PG_FICTITIOUS) == 0 &&
4491 vm_reserv_level_iffullpop(m) == 0)
4492 pmap_promote_pde(pmap, pde, va, &lock);
4497 return (KERN_SUCCESS);
4501 * Tries to create a 2MB page mapping. Returns TRUE if successful and FALSE
4502 * otherwise. Fails if (1) a page table page cannot be allocated without
4503 * blocking, (2) a mapping already exists at the specified virtual address, or
4504 * (3) a pv entry cannot be allocated without reclaiming another pv entry.
4507 pmap_enter_pde(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4508 struct rwlock **lockp)
4510 pd_entry_t *pde, newpde;
4513 struct spglist free;
4515 PG_V = pmap_valid_bit(pmap);
4516 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4518 if ((mpde = pmap_allocpde(pmap, va, NULL)) == NULL) {
4519 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4520 " in pmap %p", va, pmap);
4523 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpde));
4524 pde = &pde[pmap_pde_index(va)];
4525 if ((*pde & PG_V) != 0) {
4526 KASSERT(mpde->wire_count > 1,
4527 ("pmap_enter_pde: mpde's wire count is too low"));
4529 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4530 " in pmap %p", va, pmap);
4533 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
4535 if ((m->oflags & VPO_UNMANAGED) == 0) {
4536 newpde |= PG_MANAGED;
4539 * Abort this mapping if its PV entry could not be created.
4541 if (!pmap_pv_insert_pde(pmap, va, VM_PAGE_TO_PHYS(m),
4544 if (pmap_unwire_ptp(pmap, va, mpde, &free)) {
4546 * Although "va" is not mapped, paging-
4547 * structure caches could nonetheless have
4548 * entries that refer to the freed page table
4549 * pages. Invalidate those entries.
4551 pmap_invalidate_page(pmap, va);
4552 pmap_free_zero_pages(&free);
4554 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
4555 " in pmap %p", va, pmap);
4559 if ((prot & VM_PROT_EXECUTE) == 0)
4561 if (va < VM_MAXUSER_ADDRESS)
4565 * Increment counters.
4567 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
4570 * Map the superpage.
4572 pde_store(pde, newpde);
4574 atomic_add_long(&pmap_pde_mappings, 1);
4575 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
4576 " in pmap %p", va, pmap);
4581 * Maps a sequence of resident pages belonging to the same object.
4582 * The sequence begins with the given page m_start. This page is
4583 * mapped at the given virtual address start. Each subsequent page is
4584 * mapped at a virtual address that is offset from start by the same
4585 * amount as the page is offset from m_start within the object. The
4586 * last page in the sequence is the page with the largest offset from
4587 * m_start that can be mapped at a virtual address less than the given
4588 * virtual address end. Not every virtual page between start and end
4589 * is mapped; only those for which a resident page exists with the
4590 * corresponding offset from m_start are mapped.
4593 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
4594 vm_page_t m_start, vm_prot_t prot)
4596 struct rwlock *lock;
4599 vm_pindex_t diff, psize;
4601 VM_OBJECT_ASSERT_LOCKED(m_start->object);
4603 psize = atop(end - start);
4608 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
4609 va = start + ptoa(diff);
4610 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
4611 m->psind == 1 && pmap_ps_enabled(pmap) &&
4612 pmap_enter_pde(pmap, va, m, prot, &lock))
4613 m = &m[NBPDR / PAGE_SIZE - 1];
4615 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
4617 m = TAILQ_NEXT(m, listq);
4625 * this code makes some *MAJOR* assumptions:
4626 * 1. Current pmap & pmap exists.
4629 * 4. No page table pages.
4630 * but is *MUCH* faster than pmap_enter...
4634 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
4636 struct rwlock *lock;
4640 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
4647 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
4648 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
4650 struct spglist free;
4651 pt_entry_t *pte, PG_V;
4654 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
4655 (m->oflags & VPO_UNMANAGED) != 0,
4656 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
4657 PG_V = pmap_valid_bit(pmap);
4658 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4661 * In the case that a page table page is not
4662 * resident, we are creating it here.
4664 if (va < VM_MAXUSER_ADDRESS) {
4665 vm_pindex_t ptepindex;
4669 * Calculate pagetable page index
4671 ptepindex = pmap_pde_pindex(va);
4672 if (mpte && (mpte->pindex == ptepindex)) {
4676 * Get the page directory entry
4678 ptepa = pmap_pde(pmap, va);
4681 * If the page table page is mapped, we just increment
4682 * the hold count, and activate it. Otherwise, we
4683 * attempt to allocate a page table page. If this
4684 * attempt fails, we don't retry. Instead, we give up.
4686 if (ptepa && (*ptepa & PG_V) != 0) {
4689 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
4693 * Pass NULL instead of the PV list lock
4694 * pointer, because we don't intend to sleep.
4696 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
4701 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
4702 pte = &pte[pmap_pte_index(va)];
4716 * Enter on the PV list if part of our managed memory.
4718 if ((m->oflags & VPO_UNMANAGED) == 0 &&
4719 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
4722 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
4724 * Although "va" is not mapped, paging-
4725 * structure caches could nonetheless have
4726 * entries that refer to the freed page table
4727 * pages. Invalidate those entries.
4729 pmap_invalidate_page(pmap, va);
4730 pmap_free_zero_pages(&free);
4738 * Increment counters
4740 pmap_resident_count_inc(pmap, 1);
4742 pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
4743 if ((prot & VM_PROT_EXECUTE) == 0)
4747 * Now validate mapping with RO protection
4749 if ((m->oflags & VPO_UNMANAGED) != 0)
4750 pte_store(pte, pa | PG_V | PG_U);
4752 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
4757 * Make a temporary mapping for a physical address. This is only intended
4758 * to be used for panic dumps.
4761 pmap_kenter_temporary(vm_paddr_t pa, int i)
4765 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
4766 pmap_kenter(va, pa);
4768 return ((void *)crashdumpmap);
4772 * This code maps large physical mmap regions into the
4773 * processor address space. Note that some shortcuts
4774 * are taken, but the code works.
4777 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
4778 vm_pindex_t pindex, vm_size_t size)
4781 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
4782 vm_paddr_t pa, ptepa;
4786 PG_A = pmap_accessed_bit(pmap);
4787 PG_M = pmap_modified_bit(pmap);
4788 PG_V = pmap_valid_bit(pmap);
4789 PG_RW = pmap_rw_bit(pmap);
4791 VM_OBJECT_ASSERT_WLOCKED(object);
4792 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
4793 ("pmap_object_init_pt: non-device object"));
4794 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
4795 if (!pmap_ps_enabled(pmap))
4797 if (!vm_object_populate(object, pindex, pindex + atop(size)))
4799 p = vm_page_lookup(object, pindex);
4800 KASSERT(p->valid == VM_PAGE_BITS_ALL,
4801 ("pmap_object_init_pt: invalid page %p", p));
4802 pat_mode = p->md.pat_mode;
4805 * Abort the mapping if the first page is not physically
4806 * aligned to a 2MB page boundary.
4808 ptepa = VM_PAGE_TO_PHYS(p);
4809 if (ptepa & (NBPDR - 1))
4813 * Skip the first page. Abort the mapping if the rest of
4814 * the pages are not physically contiguous or have differing
4815 * memory attributes.
4817 p = TAILQ_NEXT(p, listq);
4818 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
4820 KASSERT(p->valid == VM_PAGE_BITS_ALL,
4821 ("pmap_object_init_pt: invalid page %p", p));
4822 if (pa != VM_PAGE_TO_PHYS(p) ||
4823 pat_mode != p->md.pat_mode)
4825 p = TAILQ_NEXT(p, listq);
4829 * Map using 2MB pages. Since "ptepa" is 2M aligned and
4830 * "size" is a multiple of 2M, adding the PAT setting to "pa"
4831 * will not affect the termination of this loop.
4834 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
4835 pa < ptepa + size; pa += NBPDR) {
4836 pdpg = pmap_allocpde(pmap, addr, NULL);
4839 * The creation of mappings below is only an
4840 * optimization. If a page directory page
4841 * cannot be allocated without blocking,
4842 * continue on to the next mapping rather than
4848 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4849 pde = &pde[pmap_pde_index(addr)];
4850 if ((*pde & PG_V) == 0) {
4851 pde_store(pde, pa | PG_PS | PG_M | PG_A |
4852 PG_U | PG_RW | PG_V);
4853 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
4854 atomic_add_long(&pmap_pde_mappings, 1);
4856 /* Continue on if the PDE is already valid. */
4858 KASSERT(pdpg->wire_count > 0,
4859 ("pmap_object_init_pt: missing reference "
4860 "to page directory page, va: 0x%lx", addr));
4869 * Clear the wired attribute from the mappings for the specified range of
4870 * addresses in the given pmap. Every valid mapping within that range
4871 * must have the wired attribute set. In contrast, invalid mappings
4872 * cannot have the wired attribute set, so they are ignored.
4874 * The wired attribute of the page table entry is not a hardware
4875 * feature, so there is no need to invalidate any TLB entries.
4876 * Since pmap_demote_pde() for the wired entry must never fail,
4877 * pmap_delayed_invl_started()/finished() calls around the
4878 * function are not needed.
4881 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4883 vm_offset_t va_next;
4884 pml4_entry_t *pml4e;
4887 pt_entry_t *pte, PG_V;
4889 PG_V = pmap_valid_bit(pmap);
4891 for (; sva < eva; sva = va_next) {
4892 pml4e = pmap_pml4e(pmap, sva);
4893 if ((*pml4e & PG_V) == 0) {
4894 va_next = (sva + NBPML4) & ~PML4MASK;
4899 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4900 if ((*pdpe & PG_V) == 0) {
4901 va_next = (sva + NBPDP) & ~PDPMASK;
4906 va_next = (sva + NBPDR) & ~PDRMASK;
4909 pde = pmap_pdpe_to_pde(pdpe, sva);
4910 if ((*pde & PG_V) == 0)
4912 if ((*pde & PG_PS) != 0) {
4913 if ((*pde & PG_W) == 0)
4914 panic("pmap_unwire: pde %#jx is missing PG_W",
4918 * Are we unwiring the entire large page? If not,
4919 * demote the mapping and fall through.
4921 if (sva + NBPDR == va_next && eva >= va_next) {
4922 atomic_clear_long(pde, PG_W);
4923 pmap->pm_stats.wired_count -= NBPDR /
4926 } else if (!pmap_demote_pde(pmap, pde, sva))
4927 panic("pmap_unwire: demotion failed");
4931 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4933 if ((*pte & PG_V) == 0)
4935 if ((*pte & PG_W) == 0)
4936 panic("pmap_unwire: pte %#jx is missing PG_W",
4940 * PG_W must be cleared atomically. Although the pmap
4941 * lock synchronizes access to PG_W, another processor
4942 * could be setting PG_M and/or PG_A concurrently.
4944 atomic_clear_long(pte, PG_W);
4945 pmap->pm_stats.wired_count--;
4952 * Copy the range specified by src_addr/len
4953 * from the source map to the range dst_addr/len
4954 * in the destination map.
4956 * This routine is only advisory and need not do anything.
4960 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
4961 vm_offset_t src_addr)
4963 struct rwlock *lock;
4964 struct spglist free;
4966 vm_offset_t end_addr = src_addr + len;
4967 vm_offset_t va_next;
4968 pt_entry_t PG_A, PG_M, PG_V;
4970 if (dst_addr != src_addr)
4973 if (dst_pmap->pm_type != src_pmap->pm_type)
4977 * EPT page table entries that require emulation of A/D bits are
4978 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
4979 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
4980 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
4981 * implementations flag an EPT misconfiguration for exec-only
4982 * mappings we skip this function entirely for emulated pmaps.
4984 if (pmap_emulate_ad_bits(dst_pmap))
4988 if (dst_pmap < src_pmap) {
4989 PMAP_LOCK(dst_pmap);
4990 PMAP_LOCK(src_pmap);
4992 PMAP_LOCK(src_pmap);
4993 PMAP_LOCK(dst_pmap);
4996 PG_A = pmap_accessed_bit(dst_pmap);
4997 PG_M = pmap_modified_bit(dst_pmap);
4998 PG_V = pmap_valid_bit(dst_pmap);
5000 for (addr = src_addr; addr < end_addr; addr = va_next) {
5001 pt_entry_t *src_pte, *dst_pte;
5002 vm_page_t dstmpde, dstmpte, srcmpte;
5003 pml4_entry_t *pml4e;
5005 pd_entry_t srcptepaddr, *pde;
5007 KASSERT(addr < UPT_MIN_ADDRESS,
5008 ("pmap_copy: invalid to pmap_copy page tables"));
5010 pml4e = pmap_pml4e(src_pmap, addr);
5011 if ((*pml4e & PG_V) == 0) {
5012 va_next = (addr + NBPML4) & ~PML4MASK;
5018 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5019 if ((*pdpe & PG_V) == 0) {
5020 va_next = (addr + NBPDP) & ~PDPMASK;
5026 va_next = (addr + NBPDR) & ~PDRMASK;
5030 pde = pmap_pdpe_to_pde(pdpe, addr);
5032 if (srcptepaddr == 0)
5035 if (srcptepaddr & PG_PS) {
5036 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5038 dstmpde = pmap_allocpde(dst_pmap, addr, NULL);
5039 if (dstmpde == NULL)
5041 pde = (pd_entry_t *)
5042 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpde));
5043 pde = &pde[pmap_pde_index(addr)];
5044 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5045 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr &
5046 PG_PS_FRAME, &lock))) {
5047 *pde = srcptepaddr & ~PG_W;
5048 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5049 atomic_add_long(&pmap_pde_mappings, 1);
5051 dstmpde->wire_count--;
5055 srcptepaddr &= PG_FRAME;
5056 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5057 KASSERT(srcmpte->wire_count > 0,
5058 ("pmap_copy: source page table page is unused"));
5060 if (va_next > end_addr)
5063 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5064 src_pte = &src_pte[pmap_pte_index(addr)];
5066 while (addr < va_next) {
5070 * we only virtual copy managed pages
5072 if ((ptetemp & PG_MANAGED) != 0) {
5073 if (dstmpte != NULL &&
5074 dstmpte->pindex == pmap_pde_pindex(addr))
5075 dstmpte->wire_count++;
5076 else if ((dstmpte = pmap_allocpte(dst_pmap,
5077 addr, NULL)) == NULL)
5079 dst_pte = (pt_entry_t *)
5080 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5081 dst_pte = &dst_pte[pmap_pte_index(addr)];
5082 if (*dst_pte == 0 &&
5083 pmap_try_insert_pv_entry(dst_pmap, addr,
5084 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5087 * Clear the wired, modified, and
5088 * accessed (referenced) bits
5091 *dst_pte = ptetemp & ~(PG_W | PG_M |
5093 pmap_resident_count_inc(dst_pmap, 1);
5096 if (pmap_unwire_ptp(dst_pmap, addr,
5099 * Although "addr" is not
5100 * mapped, paging-structure
5101 * caches could nonetheless
5102 * have entries that refer to
5103 * the freed page table pages.
5104 * Invalidate those entries.
5106 pmap_invalidate_page(dst_pmap,
5108 pmap_free_zero_pages(&free);
5112 if (dstmpte->wire_count >= srcmpte->wire_count)
5122 PMAP_UNLOCK(src_pmap);
5123 PMAP_UNLOCK(dst_pmap);
5127 * pmap_zero_page zeros the specified hardware page by mapping
5128 * the page into KVM and using bzero to clear its contents.
5131 pmap_zero_page(vm_page_t m)
5133 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5135 pagezero((void *)va);
5139 * pmap_zero_page_area zeros the specified hardware page by mapping
5140 * the page into KVM and using bzero to clear its contents.
5142 * off and size may not cover an area beyond a single hardware page.
5145 pmap_zero_page_area(vm_page_t m, int off, int size)
5147 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5149 if (off == 0 && size == PAGE_SIZE)
5150 pagezero((void *)va);
5152 bzero((char *)va + off, size);
5156 * pmap_zero_page_idle zeros the specified hardware page by mapping
5157 * the page into KVM and using bzero to clear its contents. This
5158 * is intended to be called from the vm_pagezero process only and
5162 pmap_zero_page_idle(vm_page_t m)
5164 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5166 pagezero((void *)va);
5170 * pmap_copy_page copies the specified (machine independent)
5171 * page by mapping the page into virtual memory and using
5172 * bcopy to copy the page, one machine dependent page at a
5176 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5178 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5179 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5181 pagecopy((void *)src, (void *)dst);
5184 int unmapped_buf_allowed = 1;
5187 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5188 vm_offset_t b_offset, int xfersize)
5192 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5196 while (xfersize > 0) {
5197 a_pg_offset = a_offset & PAGE_MASK;
5198 pages[0] = ma[a_offset >> PAGE_SHIFT];
5199 b_pg_offset = b_offset & PAGE_MASK;
5200 pages[1] = mb[b_offset >> PAGE_SHIFT];
5201 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5202 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5203 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5204 a_cp = (char *)vaddr[0] + a_pg_offset;
5205 b_cp = (char *)vaddr[1] + b_pg_offset;
5206 bcopy(a_cp, b_cp, cnt);
5207 if (__predict_false(mapped))
5208 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5216 * Returns true if the pmap's pv is one of the first
5217 * 16 pvs linked to from this page. This count may
5218 * be changed upwards or downwards in the future; it
5219 * is only necessary that true be returned for a small
5220 * subset of pmaps for proper page aging.
5223 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5225 struct md_page *pvh;
5226 struct rwlock *lock;
5231 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5232 ("pmap_page_exists_quick: page %p is not managed", m));
5234 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5236 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5237 if (PV_PMAP(pv) == pmap) {
5245 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5246 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5247 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5248 if (PV_PMAP(pv) == pmap) {
5262 * pmap_page_wired_mappings:
5264 * Return the number of managed mappings to the given physical page
5268 pmap_page_wired_mappings(vm_page_t m)
5270 struct rwlock *lock;
5271 struct md_page *pvh;
5275 int count, md_gen, pvh_gen;
5277 if ((m->oflags & VPO_UNMANAGED) != 0)
5279 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5283 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5285 if (!PMAP_TRYLOCK(pmap)) {
5286 md_gen = m->md.pv_gen;
5290 if (md_gen != m->md.pv_gen) {
5295 pte = pmap_pte(pmap, pv->pv_va);
5296 if ((*pte & PG_W) != 0)
5300 if ((m->flags & PG_FICTITIOUS) == 0) {
5301 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5302 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5304 if (!PMAP_TRYLOCK(pmap)) {
5305 md_gen = m->md.pv_gen;
5306 pvh_gen = pvh->pv_gen;
5310 if (md_gen != m->md.pv_gen ||
5311 pvh_gen != pvh->pv_gen) {
5316 pte = pmap_pde(pmap, pv->pv_va);
5317 if ((*pte & PG_W) != 0)
5327 * Returns TRUE if the given page is mapped individually or as part of
5328 * a 2mpage. Otherwise, returns FALSE.
5331 pmap_page_is_mapped(vm_page_t m)
5333 struct rwlock *lock;
5336 if ((m->oflags & VPO_UNMANAGED) != 0)
5338 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5340 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5341 ((m->flags & PG_FICTITIOUS) == 0 &&
5342 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5348 * Destroy all managed, non-wired mappings in the given user-space
5349 * pmap. This pmap cannot be active on any processor besides the
5352 * This function cannot be applied to the kernel pmap. Moreover, it
5353 * is not intended for general use. It is only to be used during
5354 * process termination. Consequently, it can be implemented in ways
5355 * that make it faster than pmap_remove(). First, it can more quickly
5356 * destroy mappings by iterating over the pmap's collection of PV
5357 * entries, rather than searching the page table. Second, it doesn't
5358 * have to test and clear the page table entries atomically, because
5359 * no processor is currently accessing the user address space. In
5360 * particular, a page table entry's dirty bit won't change state once
5361 * this function starts.
5364 pmap_remove_pages(pmap_t pmap)
5367 pt_entry_t *pte, tpte;
5368 pt_entry_t PG_M, PG_RW, PG_V;
5369 struct spglist free;
5370 vm_page_t m, mpte, mt;
5372 struct md_page *pvh;
5373 struct pv_chunk *pc, *npc;
5374 struct rwlock *lock;
5376 uint64_t inuse, bitmask;
5377 int allfree, field, freed, idx;
5378 boolean_t superpage;
5382 * Assert that the given pmap is only active on the current
5383 * CPU. Unfortunately, we cannot block another CPU from
5384 * activating the pmap while this function is executing.
5386 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5389 cpuset_t other_cpus;
5391 other_cpus = all_cpus;
5393 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5394 CPU_AND(&other_cpus, &pmap->pm_active);
5396 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5401 PG_M = pmap_modified_bit(pmap);
5402 PG_V = pmap_valid_bit(pmap);
5403 PG_RW = pmap_rw_bit(pmap);
5407 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5410 for (field = 0; field < _NPCM; field++) {
5411 inuse = ~pc->pc_map[field] & pc_freemask[field];
5412 while (inuse != 0) {
5414 bitmask = 1UL << bit;
5415 idx = field * 64 + bit;
5416 pv = &pc->pc_pventry[idx];
5419 pte = pmap_pdpe(pmap, pv->pv_va);
5421 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5423 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5426 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5428 pte = &pte[pmap_pte_index(pv->pv_va)];
5432 * Keep track whether 'tpte' is a
5433 * superpage explicitly instead of
5434 * relying on PG_PS being set.
5436 * This is because PG_PS is numerically
5437 * identical to PG_PTE_PAT and thus a
5438 * regular page could be mistaken for
5444 if ((tpte & PG_V) == 0) {
5445 panic("bad pte va %lx pte %lx",
5450 * We cannot remove wired pages from a process' mapping at this time
5458 pa = tpte & PG_PS_FRAME;
5460 pa = tpte & PG_FRAME;
5462 m = PHYS_TO_VM_PAGE(pa);
5463 KASSERT(m->phys_addr == pa,
5464 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5465 m, (uintmax_t)m->phys_addr,
5468 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5469 m < &vm_page_array[vm_page_array_size],
5470 ("pmap_remove_pages: bad tpte %#jx",
5476 * Update the vm_page_t clean/reference bits.
5478 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5480 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5486 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5489 pc->pc_map[field] |= bitmask;
5491 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
5492 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
5493 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5495 if (TAILQ_EMPTY(&pvh->pv_list)) {
5496 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5497 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
5498 TAILQ_EMPTY(&mt->md.pv_list))
5499 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5501 mpte = pmap_lookup_pt_page(pmap, pv->pv_va);
5503 pmap_remove_pt_page(pmap, mpte);
5504 pmap_resident_count_dec(pmap, 1);
5505 KASSERT(mpte->wire_count == NPTEPG,
5506 ("pmap_remove_pages: pte page wire count error"));
5507 mpte->wire_count = 0;
5508 pmap_add_delayed_free_list(mpte, &free, FALSE);
5509 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
5512 pmap_resident_count_dec(pmap, 1);
5513 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5515 if ((m->aflags & PGA_WRITEABLE) != 0 &&
5516 TAILQ_EMPTY(&m->md.pv_list) &&
5517 (m->flags & PG_FICTITIOUS) == 0) {
5518 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5519 if (TAILQ_EMPTY(&pvh->pv_list))
5520 vm_page_aflag_clear(m, PGA_WRITEABLE);
5523 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
5527 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5528 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5529 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5531 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5537 pmap_invalidate_all(pmap);
5539 pmap_free_zero_pages(&free);
5543 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
5545 struct rwlock *lock;
5547 struct md_page *pvh;
5548 pt_entry_t *pte, mask;
5549 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5551 int md_gen, pvh_gen;
5555 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5558 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5560 if (!PMAP_TRYLOCK(pmap)) {
5561 md_gen = m->md.pv_gen;
5565 if (md_gen != m->md.pv_gen) {
5570 pte = pmap_pte(pmap, pv->pv_va);
5573 PG_M = pmap_modified_bit(pmap);
5574 PG_RW = pmap_rw_bit(pmap);
5575 mask |= PG_RW | PG_M;
5578 PG_A = pmap_accessed_bit(pmap);
5579 PG_V = pmap_valid_bit(pmap);
5580 mask |= PG_V | PG_A;
5582 rv = (*pte & mask) == mask;
5587 if ((m->flags & PG_FICTITIOUS) == 0) {
5588 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5589 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5591 if (!PMAP_TRYLOCK(pmap)) {
5592 md_gen = m->md.pv_gen;
5593 pvh_gen = pvh->pv_gen;
5597 if (md_gen != m->md.pv_gen ||
5598 pvh_gen != pvh->pv_gen) {
5603 pte = pmap_pde(pmap, pv->pv_va);
5606 PG_M = pmap_modified_bit(pmap);
5607 PG_RW = pmap_rw_bit(pmap);
5608 mask |= PG_RW | PG_M;
5611 PG_A = pmap_accessed_bit(pmap);
5612 PG_V = pmap_valid_bit(pmap);
5613 mask |= PG_V | PG_A;
5615 rv = (*pte & mask) == mask;
5629 * Return whether or not the specified physical page was modified
5630 * in any physical maps.
5633 pmap_is_modified(vm_page_t m)
5636 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5637 ("pmap_is_modified: page %p is not managed", m));
5640 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5641 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
5642 * is clear, no PTEs can have PG_M set.
5644 VM_OBJECT_ASSERT_WLOCKED(m->object);
5645 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
5647 return (pmap_page_test_mappings(m, FALSE, TRUE));
5651 * pmap_is_prefaultable:
5653 * Return whether or not the specified virtual address is eligible
5657 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
5660 pt_entry_t *pte, PG_V;
5663 PG_V = pmap_valid_bit(pmap);
5666 pde = pmap_pde(pmap, addr);
5667 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
5668 pte = pmap_pde_to_pte(pde, addr);
5669 rv = (*pte & PG_V) == 0;
5676 * pmap_is_referenced:
5678 * Return whether or not the specified physical page was referenced
5679 * in any physical maps.
5682 pmap_is_referenced(vm_page_t m)
5685 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5686 ("pmap_is_referenced: page %p is not managed", m));
5687 return (pmap_page_test_mappings(m, TRUE, FALSE));
5691 * Clear the write and modified bits in each of the given page's mappings.
5694 pmap_remove_write(vm_page_t m)
5696 struct md_page *pvh;
5698 struct rwlock *lock;
5699 pv_entry_t next_pv, pv;
5701 pt_entry_t oldpte, *pte, PG_M, PG_RW;
5703 int pvh_gen, md_gen;
5705 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5706 ("pmap_remove_write: page %p is not managed", m));
5709 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
5710 * set by another thread while the object is locked. Thus,
5711 * if PGA_WRITEABLE is clear, no page table entries need updating.
5713 VM_OBJECT_ASSERT_WLOCKED(m->object);
5714 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
5716 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5717 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
5718 pa_to_pvh(VM_PAGE_TO_PHYS(m));
5721 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
5723 if (!PMAP_TRYLOCK(pmap)) {
5724 pvh_gen = pvh->pv_gen;
5728 if (pvh_gen != pvh->pv_gen) {
5734 PG_RW = pmap_rw_bit(pmap);
5736 pde = pmap_pde(pmap, va);
5737 if ((*pde & PG_RW) != 0)
5738 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
5739 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
5740 ("inconsistent pv lock %p %p for page %p",
5741 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
5744 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5746 if (!PMAP_TRYLOCK(pmap)) {
5747 pvh_gen = pvh->pv_gen;
5748 md_gen = m->md.pv_gen;
5752 if (pvh_gen != pvh->pv_gen ||
5753 md_gen != m->md.pv_gen) {
5759 PG_M = pmap_modified_bit(pmap);
5760 PG_RW = pmap_rw_bit(pmap);
5761 pde = pmap_pde(pmap, pv->pv_va);
5762 KASSERT((*pde & PG_PS) == 0,
5763 ("pmap_remove_write: found a 2mpage in page %p's pv list",
5765 pte = pmap_pde_to_pte(pde, pv->pv_va);
5768 if (oldpte & PG_RW) {
5769 if (!atomic_cmpset_long(pte, oldpte, oldpte &
5772 if ((oldpte & PG_M) != 0)
5774 pmap_invalidate_page(pmap, pv->pv_va);
5779 vm_page_aflag_clear(m, PGA_WRITEABLE);
5780 pmap_delayed_invl_wait(m);
5783 static __inline boolean_t
5784 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
5787 if (!pmap_emulate_ad_bits(pmap))
5790 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
5793 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
5794 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
5795 * if the EPT_PG_WRITE bit is set.
5797 if ((pte & EPT_PG_WRITE) != 0)
5801 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
5803 if ((pte & EPT_PG_EXECUTE) == 0 ||
5804 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
5810 #define PMAP_TS_REFERENCED_MAX 5
5813 * pmap_ts_referenced:
5815 * Return a count of reference bits for a page, clearing those bits.
5816 * It is not necessary for every reference bit to be cleared, but it
5817 * is necessary that 0 only be returned when there are truly no
5818 * reference bits set.
5820 * XXX: The exact number of bits to check and clear is a matter that
5821 * should be tested and standardized at some point in the future for
5822 * optimal aging of shared pages.
5824 * A DI block is not needed within this function, because
5825 * invalidations are performed before the PV list lock is
5829 pmap_ts_referenced(vm_page_t m)
5831 struct md_page *pvh;
5834 struct rwlock *lock;
5835 pd_entry_t oldpde, *pde;
5836 pt_entry_t *pte, PG_A;
5839 int cleared, md_gen, not_cleared, pvh_gen;
5840 struct spglist free;
5843 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5844 ("pmap_ts_referenced: page %p is not managed", m));
5847 pa = VM_PAGE_TO_PHYS(m);
5848 lock = PHYS_TO_PV_LIST_LOCK(pa);
5849 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
5853 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
5854 goto small_mappings;
5860 if (!PMAP_TRYLOCK(pmap)) {
5861 pvh_gen = pvh->pv_gen;
5865 if (pvh_gen != pvh->pv_gen) {
5870 PG_A = pmap_accessed_bit(pmap);
5872 pde = pmap_pde(pmap, pv->pv_va);
5874 if ((*pde & PG_A) != 0) {
5876 * Since this reference bit is shared by 512 4KB
5877 * pages, it should not be cleared every time it is
5878 * tested. Apply a simple "hash" function on the
5879 * physical page number, the virtual superpage number,
5880 * and the pmap address to select one 4KB page out of
5881 * the 512 on which testing the reference bit will
5882 * result in clearing that reference bit. This
5883 * function is designed to avoid the selection of the
5884 * same 4KB page for every 2MB page mapping.
5886 * On demotion, a mapping that hasn't been referenced
5887 * is simply destroyed. To avoid the possibility of a
5888 * subsequent page fault on a demoted wired mapping,
5889 * always leave its reference bit set. Moreover,
5890 * since the superpage is wired, the current state of
5891 * its reference bit won't affect page replacement.
5893 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
5894 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
5895 (*pde & PG_W) == 0) {
5896 if (safe_to_clear_referenced(pmap, oldpde)) {
5897 atomic_clear_long(pde, PG_A);
5898 pmap_invalidate_page(pmap, pv->pv_va);
5900 } else if (pmap_demote_pde_locked(pmap, pde,
5901 pv->pv_va, &lock)) {
5903 * Remove the mapping to a single page
5904 * so that a subsequent access may
5905 * repromote. Since the underlying
5906 * page table page is fully populated,
5907 * this removal never frees a page
5911 va += VM_PAGE_TO_PHYS(m) - (oldpde &
5913 pte = pmap_pde_to_pte(pde, va);
5914 pmap_remove_pte(pmap, pte, va, *pde,
5916 pmap_invalidate_page(pmap, va);
5922 * The superpage mapping was removed
5923 * entirely and therefore 'pv' is no
5931 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
5932 ("inconsistent pv lock %p %p for page %p",
5933 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
5938 /* Rotate the PV list if it has more than one entry. */
5939 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
5940 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5941 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5944 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
5946 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
5948 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
5955 if (!PMAP_TRYLOCK(pmap)) {
5956 pvh_gen = pvh->pv_gen;
5957 md_gen = m->md.pv_gen;
5961 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
5966 PG_A = pmap_accessed_bit(pmap);
5967 pde = pmap_pde(pmap, pv->pv_va);
5968 KASSERT((*pde & PG_PS) == 0,
5969 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
5971 pte = pmap_pde_to_pte(pde, pv->pv_va);
5972 if ((*pte & PG_A) != 0) {
5973 if (safe_to_clear_referenced(pmap, *pte)) {
5974 atomic_clear_long(pte, PG_A);
5975 pmap_invalidate_page(pmap, pv->pv_va);
5977 } else if ((*pte & PG_W) == 0) {
5979 * Wired pages cannot be paged out so
5980 * doing accessed bit emulation for
5981 * them is wasted effort. We do the
5982 * hard work for unwired pages only.
5984 pmap_remove_pte(pmap, pte, pv->pv_va,
5985 *pde, &free, &lock);
5986 pmap_invalidate_page(pmap, pv->pv_va);
5991 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
5992 ("inconsistent pv lock %p %p for page %p",
5993 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
5998 /* Rotate the PV list if it has more than one entry. */
5999 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6000 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6001 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6004 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6005 not_cleared < PMAP_TS_REFERENCED_MAX);
6008 pmap_free_zero_pages(&free);
6009 return (cleared + not_cleared);
6013 * Apply the given advice to the specified range of addresses within the
6014 * given pmap. Depending on the advice, clear the referenced and/or
6015 * modified flags in each mapping and set the mapped page's dirty field.
6018 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6020 struct rwlock *lock;
6021 pml4_entry_t *pml4e;
6023 pd_entry_t oldpde, *pde;
6024 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6025 vm_offset_t va_next;
6027 boolean_t anychanged;
6029 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6033 * A/D bit emulation requires an alternate code path when clearing
6034 * the modified and accessed bits below. Since this function is
6035 * advisory in nature we skip it entirely for pmaps that require
6036 * A/D bit emulation.
6038 if (pmap_emulate_ad_bits(pmap))
6041 PG_A = pmap_accessed_bit(pmap);
6042 PG_G = pmap_global_bit(pmap);
6043 PG_M = pmap_modified_bit(pmap);
6044 PG_V = pmap_valid_bit(pmap);
6045 PG_RW = pmap_rw_bit(pmap);
6047 pmap_delayed_invl_started();
6049 for (; sva < eva; sva = va_next) {
6050 pml4e = pmap_pml4e(pmap, sva);
6051 if ((*pml4e & PG_V) == 0) {
6052 va_next = (sva + NBPML4) & ~PML4MASK;
6057 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6058 if ((*pdpe & PG_V) == 0) {
6059 va_next = (sva + NBPDP) & ~PDPMASK;
6064 va_next = (sva + NBPDR) & ~PDRMASK;
6067 pde = pmap_pdpe_to_pde(pdpe, sva);
6069 if ((oldpde & PG_V) == 0)
6071 else if ((oldpde & PG_PS) != 0) {
6072 if ((oldpde & PG_MANAGED) == 0)
6075 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6080 * The large page mapping was destroyed.
6086 * Unless the page mappings are wired, remove the
6087 * mapping to a single page so that a subsequent
6088 * access may repromote. Since the underlying page
6089 * table page is fully populated, this removal never
6090 * frees a page table page.
6092 if ((oldpde & PG_W) == 0) {
6093 pte = pmap_pde_to_pte(pde, sva);
6094 KASSERT((*pte & PG_V) != 0,
6095 ("pmap_advise: invalid PTE"));
6096 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6105 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6107 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED |
6110 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6111 if (advice == MADV_DONTNEED) {
6113 * Future calls to pmap_is_modified()
6114 * can be avoided by making the page
6117 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6120 atomic_clear_long(pte, PG_M | PG_A);
6121 } else if ((*pte & PG_A) != 0)
6122 atomic_clear_long(pte, PG_A);
6125 if ((*pte & PG_G) != 0)
6126 pmap_invalidate_page(pmap, sva);
6132 pmap_invalidate_all(pmap);
6134 pmap_delayed_invl_finished();
6138 * Clear the modify bits on the specified physical page.
6141 pmap_clear_modify(vm_page_t m)
6143 struct md_page *pvh;
6145 pv_entry_t next_pv, pv;
6146 pd_entry_t oldpde, *pde;
6147 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6148 struct rwlock *lock;
6150 int md_gen, pvh_gen;
6152 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6153 ("pmap_clear_modify: page %p is not managed", m));
6154 VM_OBJECT_ASSERT_WLOCKED(m->object);
6155 KASSERT(!vm_page_xbusied(m),
6156 ("pmap_clear_modify: page %p is exclusive busied", m));
6159 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6160 * If the object containing the page is locked and the page is not
6161 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6163 if ((m->aflags & PGA_WRITEABLE) == 0)
6165 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6166 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6167 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6170 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6172 if (!PMAP_TRYLOCK(pmap)) {
6173 pvh_gen = pvh->pv_gen;
6177 if (pvh_gen != pvh->pv_gen) {
6182 PG_M = pmap_modified_bit(pmap);
6183 PG_V = pmap_valid_bit(pmap);
6184 PG_RW = pmap_rw_bit(pmap);
6186 pde = pmap_pde(pmap, va);
6188 if ((oldpde & PG_RW) != 0) {
6189 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6190 if ((oldpde & PG_W) == 0) {
6192 * Write protect the mapping to a
6193 * single page so that a subsequent
6194 * write access may repromote.
6196 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6198 pte = pmap_pde_to_pte(pde, va);
6200 if ((oldpte & PG_V) != 0) {
6201 while (!atomic_cmpset_long(pte,
6203 oldpte & ~(PG_M | PG_RW)))
6206 pmap_invalidate_page(pmap, va);
6213 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6215 if (!PMAP_TRYLOCK(pmap)) {
6216 md_gen = m->md.pv_gen;
6217 pvh_gen = pvh->pv_gen;
6221 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6226 PG_M = pmap_modified_bit(pmap);
6227 PG_RW = pmap_rw_bit(pmap);
6228 pde = pmap_pde(pmap, pv->pv_va);
6229 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6230 " a 2mpage in page %p's pv list", m));
6231 pte = pmap_pde_to_pte(pde, pv->pv_va);
6232 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6233 atomic_clear_long(pte, PG_M);
6234 pmap_invalidate_page(pmap, pv->pv_va);
6242 * Miscellaneous support routines follow
6245 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6246 static __inline void
6247 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6252 * The cache mode bits are all in the low 32-bits of the
6253 * PTE, so we can just spin on updating the low 32-bits.
6256 opte = *(u_int *)pte;
6257 npte = opte & ~mask;
6259 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6262 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6263 static __inline void
6264 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6269 * The cache mode bits are all in the low 32-bits of the
6270 * PDE, so we can just spin on updating the low 32-bits.
6273 opde = *(u_int *)pde;
6274 npde = opde & ~mask;
6276 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6280 * Map a set of physical memory pages into the kernel virtual
6281 * address space. Return a pointer to where it is mapped. This
6282 * routine is intended to be used for mapping device memory,
6286 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6288 struct pmap_preinit_mapping *ppim;
6289 vm_offset_t va, offset;
6293 offset = pa & PAGE_MASK;
6294 size = round_page(offset + size);
6295 pa = trunc_page(pa);
6297 if (!pmap_initialized) {
6299 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6300 ppim = pmap_preinit_mapping + i;
6301 if (ppim->va == 0) {
6305 ppim->va = virtual_avail;
6306 virtual_avail += size;
6312 panic("%s: too many preinit mappings", __func__);
6315 * If we have a preinit mapping, re-use it.
6317 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6318 ppim = pmap_preinit_mapping + i;
6319 if (ppim->pa == pa && ppim->sz == size &&
6321 return ((void *)(ppim->va + offset));
6324 * If the specified range of physical addresses fits within
6325 * the direct map window, use the direct map.
6327 if (pa < dmaplimit && pa + size < dmaplimit) {
6328 va = PHYS_TO_DMAP(pa);
6329 if (!pmap_change_attr(va, size, mode))
6330 return ((void *)(va + offset));
6332 va = kva_alloc(size);
6334 panic("%s: Couldn't allocate KVA", __func__);
6336 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6337 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6338 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6339 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6340 return ((void *)(va + offset));
6344 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6347 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6351 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6354 return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6358 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6360 struct pmap_preinit_mapping *ppim;
6364 /* If we gave a direct map region in pmap_mapdev, do nothing */
6365 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6367 offset = va & PAGE_MASK;
6368 size = round_page(offset + size);
6369 va = trunc_page(va);
6370 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6371 ppim = pmap_preinit_mapping + i;
6372 if (ppim->va == va && ppim->sz == size) {
6373 if (pmap_initialized)
6379 if (va + size == virtual_avail)
6384 if (pmap_initialized)
6389 * Tries to demote a 1GB page mapping.
6392 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6394 pdp_entry_t newpdpe, oldpdpe;
6395 pd_entry_t *firstpde, newpde, *pde;
6396 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6400 PG_A = pmap_accessed_bit(pmap);
6401 PG_M = pmap_modified_bit(pmap);
6402 PG_V = pmap_valid_bit(pmap);
6403 PG_RW = pmap_rw_bit(pmap);
6405 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6407 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6408 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6409 if ((mpde = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6410 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6411 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6412 " in pmap %p", va, pmap);
6415 mpdepa = VM_PAGE_TO_PHYS(mpde);
6416 firstpde = (pd_entry_t *)PHYS_TO_DMAP(mpdepa);
6417 newpdpe = mpdepa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6418 KASSERT((oldpdpe & PG_A) != 0,
6419 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6420 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6421 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
6425 * Initialize the page directory page.
6427 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
6433 * Demote the mapping.
6438 * Invalidate a stale recursive mapping of the page directory page.
6440 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
6442 pmap_pdpe_demotions++;
6443 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
6444 " in pmap %p", va, pmap);
6449 * Sets the memory attribute for the specified page.
6452 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6455 m->md.pat_mode = ma;
6458 * If "m" is a normal page, update its direct mapping. This update
6459 * can be relied upon to perform any cache operations that are
6460 * required for data coherence.
6462 if ((m->flags & PG_FICTITIOUS) == 0 &&
6463 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6465 panic("memory attribute change on the direct map failed");
6469 * Changes the specified virtual address range's memory type to that given by
6470 * the parameter "mode". The specified virtual address range must be
6471 * completely contained within either the direct map or the kernel map. If
6472 * the virtual address range is contained within the kernel map, then the
6473 * memory type for each of the corresponding ranges of the direct map is also
6474 * changed. (The corresponding ranges of the direct map are those ranges that
6475 * map the same physical pages as the specified virtual address range.) These
6476 * changes to the direct map are necessary because Intel describes the
6477 * behavior of their processors as "undefined" if two or more mappings to the
6478 * same physical page have different memory types.
6480 * Returns zero if the change completed successfully, and either EINVAL or
6481 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6482 * of the virtual address range was not mapped, and ENOMEM is returned if
6483 * there was insufficient memory available to complete the change. In the
6484 * latter case, the memory type may have been changed on some part of the
6485 * virtual address range or the direct map.
6488 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6492 PMAP_LOCK(kernel_pmap);
6493 error = pmap_change_attr_locked(va, size, mode);
6494 PMAP_UNLOCK(kernel_pmap);
6499 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
6501 vm_offset_t base, offset, tmpva;
6502 vm_paddr_t pa_start, pa_end, pa_end1;
6506 int cache_bits_pte, cache_bits_pde, error;
6509 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6510 base = trunc_page(va);
6511 offset = va & PAGE_MASK;
6512 size = round_page(offset + size);
6515 * Only supported on kernel virtual addresses, including the direct
6516 * map but excluding the recursive map.
6518 if (base < DMAP_MIN_ADDRESS)
6521 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
6522 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
6526 * Pages that aren't mapped aren't supported. Also break down 2MB pages
6527 * into 4KB pages if required.
6529 for (tmpva = base; tmpva < base + size; ) {
6530 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6531 if (pdpe == NULL || *pdpe == 0)
6533 if (*pdpe & PG_PS) {
6535 * If the current 1GB page already has the required
6536 * memory type, then we need not demote this page. Just
6537 * increment tmpva to the next 1GB page frame.
6539 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
6540 tmpva = trunc_1gpage(tmpva) + NBPDP;
6545 * If the current offset aligns with a 1GB page frame
6546 * and there is at least 1GB left within the range, then
6547 * we need not break down this page into 2MB pages.
6549 if ((tmpva & PDPMASK) == 0 &&
6550 tmpva + PDPMASK < base + size) {
6554 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
6557 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6562 * If the current 2MB page already has the required
6563 * memory type, then we need not demote this page. Just
6564 * increment tmpva to the next 2MB page frame.
6566 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
6567 tmpva = trunc_2mpage(tmpva) + NBPDR;
6572 * If the current offset aligns with a 2MB page frame
6573 * and there is at least 2MB left within the range, then
6574 * we need not break down this page into 4KB pages.
6576 if ((tmpva & PDRMASK) == 0 &&
6577 tmpva + PDRMASK < base + size) {
6581 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
6584 pte = pmap_pde_to_pte(pde, tmpva);
6592 * Ok, all the pages exist, so run through them updating their
6593 * cache mode if required.
6595 pa_start = pa_end = 0;
6596 for (tmpva = base; tmpva < base + size; ) {
6597 pdpe = pmap_pdpe(kernel_pmap, tmpva);
6598 if (*pdpe & PG_PS) {
6599 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
6600 pmap_pde_attr(pdpe, cache_bits_pde,
6604 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6605 (*pdpe & PG_PS_FRAME) < dmaplimit) {
6606 if (pa_start == pa_end) {
6607 /* Start physical address run. */
6608 pa_start = *pdpe & PG_PS_FRAME;
6609 pa_end = pa_start + NBPDP;
6610 } else if (pa_end == (*pdpe & PG_PS_FRAME))
6613 /* Run ended, update direct map. */
6614 error = pmap_change_attr_locked(
6615 PHYS_TO_DMAP(pa_start),
6616 pa_end - pa_start, mode);
6619 /* Start physical address run. */
6620 pa_start = *pdpe & PG_PS_FRAME;
6621 pa_end = pa_start + NBPDP;
6624 tmpva = trunc_1gpage(tmpva) + NBPDP;
6627 pde = pmap_pdpe_to_pde(pdpe, tmpva);
6629 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
6630 pmap_pde_attr(pde, cache_bits_pde,
6634 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6635 (*pde & PG_PS_FRAME) < dmaplimit) {
6636 if (pa_start == pa_end) {
6637 /* Start physical address run. */
6638 pa_start = *pde & PG_PS_FRAME;
6639 pa_end = pa_start + NBPDR;
6640 } else if (pa_end == (*pde & PG_PS_FRAME))
6643 /* Run ended, update direct map. */
6644 error = pmap_change_attr_locked(
6645 PHYS_TO_DMAP(pa_start),
6646 pa_end - pa_start, mode);
6649 /* Start physical address run. */
6650 pa_start = *pde & PG_PS_FRAME;
6651 pa_end = pa_start + NBPDR;
6654 tmpva = trunc_2mpage(tmpva) + NBPDR;
6656 pte = pmap_pde_to_pte(pde, tmpva);
6657 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
6658 pmap_pte_attr(pte, cache_bits_pte,
6662 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
6663 (*pte & PG_PS_FRAME) < dmaplimit) {
6664 if (pa_start == pa_end) {
6665 /* Start physical address run. */
6666 pa_start = *pte & PG_FRAME;
6667 pa_end = pa_start + PAGE_SIZE;
6668 } else if (pa_end == (*pte & PG_FRAME))
6669 pa_end += PAGE_SIZE;
6671 /* Run ended, update direct map. */
6672 error = pmap_change_attr_locked(
6673 PHYS_TO_DMAP(pa_start),
6674 pa_end - pa_start, mode);
6677 /* Start physical address run. */
6678 pa_start = *pte & PG_FRAME;
6679 pa_end = pa_start + PAGE_SIZE;
6685 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
6686 pa_end1 = MIN(pa_end, dmaplimit);
6687 if (pa_start != pa_end1)
6688 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
6689 pa_end1 - pa_start, mode);
6693 * Flush CPU caches if required to make sure any data isn't cached that
6694 * shouldn't be, etc.
6697 pmap_invalidate_range(kernel_pmap, base, tmpva);
6698 pmap_invalidate_cache_range(base, tmpva, FALSE);
6704 * Demotes any mapping within the direct map region that covers more than the
6705 * specified range of physical addresses. This range's size must be a power
6706 * of two and its starting address must be a multiple of its size. Since the
6707 * demotion does not change any attributes of the mapping, a TLB invalidation
6708 * is not mandatory. The caller may, however, request a TLB invalidation.
6711 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
6720 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
6721 KASSERT((base & (len - 1)) == 0,
6722 ("pmap_demote_DMAP: base is not a multiple of len"));
6723 if (len < NBPDP && base < dmaplimit) {
6724 va = PHYS_TO_DMAP(base);
6726 PMAP_LOCK(kernel_pmap);
6727 pdpe = pmap_pdpe(kernel_pmap, va);
6728 if ((*pdpe & X86_PG_V) == 0)
6729 panic("pmap_demote_DMAP: invalid PDPE");
6730 if ((*pdpe & PG_PS) != 0) {
6731 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
6732 panic("pmap_demote_DMAP: PDPE failed");
6736 pde = pmap_pdpe_to_pde(pdpe, va);
6737 if ((*pde & X86_PG_V) == 0)
6738 panic("pmap_demote_DMAP: invalid PDE");
6739 if ((*pde & PG_PS) != 0) {
6740 if (!pmap_demote_pde(kernel_pmap, pde, va))
6741 panic("pmap_demote_DMAP: PDE failed");
6745 if (changed && invalidate)
6746 pmap_invalidate_page(kernel_pmap, va);
6747 PMAP_UNLOCK(kernel_pmap);
6752 * perform the pmap work for mincore
6755 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
6758 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
6762 PG_A = pmap_accessed_bit(pmap);
6763 PG_M = pmap_modified_bit(pmap);
6764 PG_V = pmap_valid_bit(pmap);
6765 PG_RW = pmap_rw_bit(pmap);
6769 pdep = pmap_pde(pmap, addr);
6770 if (pdep != NULL && (*pdep & PG_V)) {
6771 if (*pdep & PG_PS) {
6773 /* Compute the physical address of the 4KB page. */
6774 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
6776 val = MINCORE_SUPER;
6778 pte = *pmap_pde_to_pte(pdep, addr);
6779 pa = pte & PG_FRAME;
6787 if ((pte & PG_V) != 0) {
6788 val |= MINCORE_INCORE;
6789 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6790 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
6791 if ((pte & PG_A) != 0)
6792 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
6794 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
6795 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
6796 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
6797 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
6798 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
6801 PA_UNLOCK_COND(*locked_pa);
6807 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
6809 uint32_t gen, new_gen, pcid_next;
6811 CRITICAL_ASSERT(curthread);
6812 gen = PCPU_GET(pcid_gen);
6813 if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN ||
6814 pmap->pm_pcids[cpuid].pm_gen == gen)
6815 return (CR3_PCID_SAVE);
6816 pcid_next = PCPU_GET(pcid_next);
6817 KASSERT(pcid_next <= PMAP_PCID_OVERMAX, ("cpu %d pcid_next %#x",
6819 if (pcid_next == PMAP_PCID_OVERMAX) {
6823 PCPU_SET(pcid_gen, new_gen);
6824 pcid_next = PMAP_PCID_KERN + 1;
6828 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
6829 pmap->pm_pcids[cpuid].pm_gen = new_gen;
6830 PCPU_SET(pcid_next, pcid_next + 1);
6835 pmap_activate_sw(struct thread *td)
6837 pmap_t oldpmap, pmap;
6838 uint64_t cached, cr3;
6841 oldpmap = PCPU_GET(curpmap);
6842 pmap = vmspace_pmap(td->td_proc->p_vmspace);
6843 if (oldpmap == pmap)
6845 cpuid = PCPU_GET(cpuid);
6847 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
6849 CPU_SET(cpuid, &pmap->pm_active);
6852 if (pmap_pcid_enabled) {
6853 cached = pmap_pcid_alloc(pmap, cpuid);
6854 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
6855 pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
6856 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
6857 pmap->pm_pcids[cpuid].pm_pcid));
6858 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
6859 pmap == kernel_pmap,
6860 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
6861 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
6862 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
6863 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
6866 PCPU_INC(pm_save_cnt);
6868 } else if (cr3 != pmap->pm_cr3) {
6869 load_cr3(pmap->pm_cr3);
6871 PCPU_SET(curpmap, pmap);
6873 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
6875 CPU_CLR(cpuid, &oldpmap->pm_active);
6880 pmap_activate(struct thread *td)
6884 pmap_activate_sw(td);
6889 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
6894 * Increase the starting virtual address of the given mapping if a
6895 * different alignment might result in more superpage mappings.
6898 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
6899 vm_offset_t *addr, vm_size_t size)
6901 vm_offset_t superpage_offset;
6905 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
6906 offset += ptoa(object->pg_color);
6907 superpage_offset = offset & PDRMASK;
6908 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
6909 (*addr & PDRMASK) == superpage_offset)
6911 if ((*addr & PDRMASK) < superpage_offset)
6912 *addr = (*addr & ~PDRMASK) + superpage_offset;
6914 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
6918 static unsigned long num_dirty_emulations;
6919 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
6920 &num_dirty_emulations, 0, NULL);
6922 static unsigned long num_accessed_emulations;
6923 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
6924 &num_accessed_emulations, 0, NULL);
6926 static unsigned long num_superpage_accessed_emulations;
6927 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
6928 &num_superpage_accessed_emulations, 0, NULL);
6930 static unsigned long ad_emulation_superpage_promotions;
6931 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
6932 &ad_emulation_superpage_promotions, 0, NULL);
6933 #endif /* INVARIANTS */
6936 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
6939 struct rwlock *lock;
6942 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
6944 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
6945 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
6947 if (!pmap_emulate_ad_bits(pmap))
6950 PG_A = pmap_accessed_bit(pmap);
6951 PG_M = pmap_modified_bit(pmap);
6952 PG_V = pmap_valid_bit(pmap);
6953 PG_RW = pmap_rw_bit(pmap);
6959 pde = pmap_pde(pmap, va);
6960 if (pde == NULL || (*pde & PG_V) == 0)
6963 if ((*pde & PG_PS) != 0) {
6964 if (ftype == VM_PROT_READ) {
6966 atomic_add_long(&num_superpage_accessed_emulations, 1);
6974 pte = pmap_pde_to_pte(pde, va);
6975 if ((*pte & PG_V) == 0)
6978 if (ftype == VM_PROT_WRITE) {
6979 if ((*pte & PG_RW) == 0)
6982 * Set the modified and accessed bits simultaneously.
6984 * Intel EPT PTEs that do software emulation of A/D bits map
6985 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
6986 * An EPT misconfiguration is triggered if the PTE is writable
6987 * but not readable (WR=10). This is avoided by setting PG_A
6988 * and PG_M simultaneously.
6990 *pte |= PG_M | PG_A;
6995 /* try to promote the mapping */
6996 if (va < VM_MAXUSER_ADDRESS)
6997 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7001 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7003 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7004 pmap_ps_enabled(pmap) &&
7005 (m->flags & PG_FICTITIOUS) == 0 &&
7006 vm_reserv_level_iffullpop(m) == 0) {
7007 pmap_promote_pde(pmap, pde, va, &lock);
7009 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7013 if (ftype == VM_PROT_WRITE)
7014 atomic_add_long(&num_dirty_emulations, 1);
7016 atomic_add_long(&num_accessed_emulations, 1);
7018 rv = 0; /* success */
7027 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7032 pt_entry_t *pte, PG_V;
7036 PG_V = pmap_valid_bit(pmap);
7039 pml4 = pmap_pml4e(pmap, va);
7041 if ((*pml4 & PG_V) == 0)
7044 pdp = pmap_pml4e_to_pdpe(pml4, va);
7046 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7049 pde = pmap_pdpe_to_pde(pdp, va);
7051 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7054 pte = pmap_pde_to_pte(pde, va);
7063 * Get the kernel virtual address of a set of physical pages. If there are
7064 * physical addresses not covered by the DMAP perform a transient mapping
7065 * that will be removed when calling pmap_unmap_io_transient.
7067 * \param page The pages the caller wishes to obtain the virtual
7068 * address on the kernel memory map.
7069 * \param vaddr On return contains the kernel virtual memory address
7070 * of the pages passed in the page parameter.
7071 * \param count Number of pages passed in.
7072 * \param can_fault TRUE if the thread using the mapped pages can take
7073 * page faults, FALSE otherwise.
7075 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7076 * finished or FALSE otherwise.
7080 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7081 boolean_t can_fault)
7084 boolean_t needs_mapping;
7086 int cache_bits, error, i;
7089 * Allocate any KVA space that we need, this is done in a separate
7090 * loop to prevent calling vmem_alloc while pinned.
7092 needs_mapping = FALSE;
7093 for (i = 0; i < count; i++) {
7094 paddr = VM_PAGE_TO_PHYS(page[i]);
7095 if (__predict_false(paddr >= dmaplimit)) {
7096 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7097 M_BESTFIT | M_WAITOK, &vaddr[i]);
7098 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7099 needs_mapping = TRUE;
7101 vaddr[i] = PHYS_TO_DMAP(paddr);
7105 /* Exit early if everything is covered by the DMAP */
7110 * NB: The sequence of updating a page table followed by accesses
7111 * to the corresponding pages used in the !DMAP case is subject to
7112 * the situation described in the "AMD64 Architecture Programmer's
7113 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7114 * Coherency Considerations". Therefore, issuing the INVLPG right
7115 * after modifying the PTE bits is crucial.
7119 for (i = 0; i < count; i++) {
7120 paddr = VM_PAGE_TO_PHYS(page[i]);
7121 if (paddr >= dmaplimit) {
7124 * Slow path, since we can get page faults
7125 * while mappings are active don't pin the
7126 * thread to the CPU and instead add a global
7127 * mapping visible to all CPUs.
7129 pmap_qenter(vaddr[i], &page[i], 1);
7131 pte = vtopte(vaddr[i]);
7132 cache_bits = pmap_cache_bits(kernel_pmap,
7133 page[i]->md.pat_mode, 0);
7134 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7141 return (needs_mapping);
7145 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7146 boolean_t can_fault)
7153 for (i = 0; i < count; i++) {
7154 paddr = VM_PAGE_TO_PHYS(page[i]);
7155 if (paddr >= dmaplimit) {
7157 pmap_qremove(vaddr[i], 1);
7158 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7164 pmap_quick_enter_page(vm_page_t m)
7168 paddr = VM_PAGE_TO_PHYS(m);
7169 if (paddr < dmaplimit)
7170 return (PHYS_TO_DMAP(paddr));
7171 mtx_lock_spin(&qframe_mtx);
7172 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7173 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7174 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7179 pmap_quick_remove_page(vm_offset_t addr)
7184 pte_store(vtopte(qframe), 0);
7186 mtx_unlock_spin(&qframe_mtx);
7189 #include "opt_ddb.h"
7191 #include <ddb/ddb.h>
7193 DB_SHOW_COMMAND(pte, pmap_print_pte)
7199 pt_entry_t *pte, PG_V;
7203 va = (vm_offset_t)addr;
7204 pmap = PCPU_GET(curpmap); /* XXX */
7206 db_printf("show pte addr\n");
7209 PG_V = pmap_valid_bit(pmap);
7210 pml4 = pmap_pml4e(pmap, va);
7211 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
7212 if ((*pml4 & PG_V) == 0) {
7216 pdp = pmap_pml4e_to_pdpe(pml4, va);
7217 db_printf(" pdpe %#016lx", *pdp);
7218 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
7222 pde = pmap_pdpe_to_pde(pdp, va);
7223 db_printf(" pde %#016lx", *pde);
7224 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
7228 pte = pmap_pde_to_pte(pde, va);
7229 db_printf(" pte %#016lx\n", *pte);
7232 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
7237 a = (vm_paddr_t)addr;
7238 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
7240 db_printf("show phys2dmap addr\n");