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.
12 * Copyright (c) 2014 Andrew Turner
13 * All rights reserved.
14 * Copyright (c) 2014-2016 The FreeBSD Foundation
15 * All rights reserved.
17 * This code is derived from software contributed to Berkeley by
18 * the Systems Programming Group of the University of Utah Computer
19 * Science Department and William Jolitz of UUNET Technologies Inc.
21 * This software was developed by Andrew Turner under sponsorship from
22 * the FreeBSD Foundation.
24 * Redistribution and use in source and binary forms, with or without
25 * modification, are permitted provided that the following conditions
27 * 1. Redistributions of source code must retain the above copyright
28 * notice, this list of conditions and the following disclaimer.
29 * 2. Redistributions in binary form must reproduce the above copyright
30 * notice, this list of conditions and the following disclaimer in the
31 * documentation and/or other materials provided with the distribution.
32 * 3. All advertising materials mentioning features or use of this software
33 * must display the following acknowledgement:
34 * This product includes software developed by the University of
35 * California, Berkeley and its contributors.
36 * 4. Neither the name of the University nor the names of its contributors
37 * may be used to endorse or promote products derived from this software
38 * without specific prior written permission.
40 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * from: @(#)pmap.c 7.7 (Berkeley) 5/12/91
55 * Copyright (c) 2003 Networks Associates Technology, Inc.
56 * All rights reserved.
58 * This software was developed for the FreeBSD Project by Jake Burkholder,
59 * Safeport Network Services, and Network Associates Laboratories, the
60 * Security Research Division of Network Associates, Inc. under
61 * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
62 * CHATS research program.
64 * Redistribution and use in source and binary forms, with or without
65 * modification, are permitted provided that the following conditions
67 * 1. Redistributions of source code must retain the above copyright
68 * notice, this list of conditions and the following disclaimer.
69 * 2. Redistributions in binary form must reproduce the above copyright
70 * notice, this list of conditions and the following disclaimer in the
71 * documentation and/or other materials provided with the distribution.
73 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
74 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
75 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
76 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
77 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
78 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
79 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
80 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
81 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
82 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
86 #include <sys/cdefs.h>
87 __FBSDID("$FreeBSD$");
90 * Manages physical address maps.
92 * Since the information managed by this module is
93 * also stored by the logical address mapping module,
94 * this module may throw away valid virtual-to-physical
95 * mappings at almost any time. However, invalidations
96 * of virtual-to-physical mappings must be done as
99 * In order to cope with hardware architectures which
100 * make virtual-to-physical map invalidates expensive,
101 * this module may delay invalidate or reduced protection
102 * operations until such time as they are actually
103 * necessary. This module is given full information as
104 * to which processors are currently using which maps,
105 * and to when physical maps must be made correct.
110 #include <sys/param.h>
111 #include <sys/asan.h>
112 #include <sys/bitstring.h>
114 #include <sys/systm.h>
115 #include <sys/kernel.h>
117 #include <sys/limits.h>
118 #include <sys/lock.h>
119 #include <sys/malloc.h>
120 #include <sys/mman.h>
121 #include <sys/msgbuf.h>
122 #include <sys/mutex.h>
123 #include <sys/physmem.h>
124 #include <sys/proc.h>
125 #include <sys/rwlock.h>
126 #include <sys/sbuf.h>
128 #include <sys/vmem.h>
129 #include <sys/vmmeter.h>
130 #include <sys/sched.h>
131 #include <sys/sysctl.h>
132 #include <sys/_unrhdr.h>
136 #include <vm/vm_param.h>
137 #include <vm/vm_kern.h>
138 #include <vm/vm_page.h>
139 #include <vm/vm_map.h>
140 #include <vm/vm_object.h>
141 #include <vm/vm_extern.h>
142 #include <vm/vm_pageout.h>
143 #include <vm/vm_pager.h>
144 #include <vm/vm_phys.h>
145 #include <vm/vm_radix.h>
146 #include <vm/vm_reserv.h>
147 #include <vm/vm_dumpset.h>
150 #include <machine/asan.h>
151 #include <machine/machdep.h>
152 #include <machine/md_var.h>
153 #include <machine/pcb.h>
156 #define PMAP_MEMDOM MAXMEMDOM
158 #define PMAP_MEMDOM 1
161 #define PMAP_ASSERT_STAGE1(pmap) MPASS((pmap)->pm_stage == PM_STAGE1)
162 #define PMAP_ASSERT_STAGE2(pmap) MPASS((pmap)->pm_stage == PM_STAGE2)
164 #define NL0PG (PAGE_SIZE/(sizeof (pd_entry_t)))
165 #define NL1PG (PAGE_SIZE/(sizeof (pd_entry_t)))
166 #define NL2PG (PAGE_SIZE/(sizeof (pd_entry_t)))
167 #define NL3PG (PAGE_SIZE/(sizeof (pt_entry_t)))
169 #define NUL0E L0_ENTRIES
170 #define NUL1E (NUL0E * NL1PG)
171 #define NUL2E (NUL1E * NL2PG)
173 #if !defined(DIAGNOSTIC)
174 #ifdef __GNUC_GNU_INLINE__
175 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
177 #define PMAP_INLINE extern inline
184 #define PV_STAT(x) do { x ; } while (0)
187 #define PV_STAT(x) do { } while (0)
188 #define __pvused __unused
191 #define pmap_l0_pindex(v) (NUL2E + NUL1E + ((v) >> L0_SHIFT))
192 #define pmap_l1_pindex(v) (NUL2E + ((v) >> L1_SHIFT))
193 #define pmap_l2_pindex(v) ((v) >> L2_SHIFT)
195 #define PMAP_SAN_PTE_BITS (ATTR_DEFAULT | ATTR_S1_XN | \
196 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) | ATTR_S1_AP(ATTR_S1_AP_RW))
198 struct pmap_large_md_page {
199 struct rwlock pv_lock;
200 struct md_page pv_page;
201 /* Pad to a power of 2, see pmap_init_pv_table(). */
205 __exclusive_cache_line static struct pmap_large_md_page pv_dummy_large;
206 #define pv_dummy pv_dummy_large.pv_page
207 __read_mostly static struct pmap_large_md_page *pv_table;
209 static struct pmap_large_md_page *
210 _pa_to_pmdp(vm_paddr_t pa)
212 struct vm_phys_seg *seg;
214 if ((seg = vm_phys_paddr_to_seg(pa)) != NULL)
215 return ((struct pmap_large_md_page *)seg->md_first +
216 pmap_l2_pindex(pa) - pmap_l2_pindex(seg->start));
220 static struct pmap_large_md_page *
221 pa_to_pmdp(vm_paddr_t pa)
223 struct pmap_large_md_page *pvd;
225 pvd = _pa_to_pmdp(pa);
227 panic("pa 0x%jx not within vm_phys_segs", (uintmax_t)pa);
231 static struct pmap_large_md_page *
232 page_to_pmdp(vm_page_t m)
234 struct vm_phys_seg *seg;
236 seg = &vm_phys_segs[m->segind];
237 return ((struct pmap_large_md_page *)seg->md_first +
238 pmap_l2_pindex(VM_PAGE_TO_PHYS(m)) - pmap_l2_pindex(seg->start));
241 #define pa_to_pvh(pa) (&(pa_to_pmdp(pa)->pv_page))
242 #define page_to_pvh(m) (&(page_to_pmdp(m)->pv_page))
244 #define PHYS_TO_PV_LIST_LOCK(pa) ({ \
245 struct pmap_large_md_page *_pvd; \
246 struct rwlock *_lock; \
247 _pvd = _pa_to_pmdp(pa); \
248 if (__predict_false(_pvd == NULL)) \
249 _lock = &pv_dummy_large.pv_lock; \
251 _lock = &(_pvd->pv_lock); \
255 static struct rwlock *
256 VM_PAGE_TO_PV_LIST_LOCK(vm_page_t m)
258 if ((m->flags & PG_FICTITIOUS) == 0)
259 return (&page_to_pmdp(m)->pv_lock);
261 return (&pv_dummy_large.pv_lock);
264 #define CHANGE_PV_LIST_LOCK(lockp, new_lock) do { \
265 struct rwlock **_lockp = (lockp); \
266 struct rwlock *_new_lock = (new_lock); \
268 if (_new_lock != *_lockp) { \
269 if (*_lockp != NULL) \
270 rw_wunlock(*_lockp); \
271 *_lockp = _new_lock; \
276 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) \
277 CHANGE_PV_LIST_LOCK(lockp, PHYS_TO_PV_LIST_LOCK(pa))
279 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
280 CHANGE_PV_LIST_LOCK(lockp, VM_PAGE_TO_PV_LIST_LOCK(m))
282 #define RELEASE_PV_LIST_LOCK(lockp) do { \
283 struct rwlock **_lockp = (lockp); \
285 if (*_lockp != NULL) { \
286 rw_wunlock(*_lockp); \
292 * The presence of this flag indicates that the mapping is writeable.
293 * If the ATTR_S1_AP_RO bit is also set, then the mapping is clean, otherwise
294 * it is dirty. This flag may only be set on managed mappings.
296 * The DBM bit is reserved on ARMv8.0 but it seems we can safely treat it
297 * as a software managed bit.
299 #define ATTR_SW_DBM ATTR_DBM
301 struct pmap kernel_pmap_store;
303 /* Used for mapping ACPI memory before VM is initialized */
304 #define PMAP_PREINIT_MAPPING_COUNT 32
305 #define PMAP_PREINIT_MAPPING_SIZE (PMAP_PREINIT_MAPPING_COUNT * L2_SIZE)
306 static vm_offset_t preinit_map_va; /* Start VA of pre-init mapping space */
307 static int vm_initialized = 0; /* No need to use pre-init maps when set */
310 * Reserve a few L2 blocks starting from 'preinit_map_va' pointer.
311 * Always map entire L2 block for simplicity.
312 * VA of L2 block = preinit_map_va + i * L2_SIZE
314 static struct pmap_preinit_mapping {
318 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
320 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
321 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
322 vm_offset_t kernel_vm_end = 0;
325 * Data for the pv entry allocation mechanism.
329 pc_to_domain(struct pv_chunk *pc)
331 return (vm_phys_domain(DMAP_TO_PHYS((vm_offset_t)pc)));
335 pc_to_domain(struct pv_chunk *pc __unused)
341 struct pv_chunks_list {
343 TAILQ_HEAD(pch, pv_chunk) pvc_list;
345 } __aligned(CACHE_LINE_SIZE);
347 struct pv_chunks_list __exclusive_cache_line pv_chunks[PMAP_MEMDOM];
349 vm_paddr_t dmap_phys_base; /* The start of the dmap region */
350 vm_paddr_t dmap_phys_max; /* The limit of the dmap region */
351 vm_offset_t dmap_max_addr; /* The virtual address limit of the dmap */
353 extern pt_entry_t pagetable_l0_ttbr1[];
355 #define PHYSMAP_SIZE (2 * (VM_PHYSSEG_MAX - 1))
356 static vm_paddr_t physmap[PHYSMAP_SIZE];
357 static u_int physmap_idx;
359 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
360 "VM/pmap parameters");
362 #if PAGE_SIZE == PAGE_SIZE_4K
363 #define L1_BLOCKS_SUPPORTED 1
365 /* TODO: Make this dynamic when we support FEAT_LPA2 (TCR_EL1.DS == 1) */
366 #define L1_BLOCKS_SUPPORTED 0
369 #define PMAP_ASSERT_L1_BLOCKS_SUPPORTED MPASS(L1_BLOCKS_SUPPORTED)
372 * This ASID allocator uses a bit vector ("asid_set") to remember which ASIDs
373 * that it has currently allocated to a pmap, a cursor ("asid_next") to
374 * optimize its search for a free ASID in the bit vector, and an epoch number
375 * ("asid_epoch") to indicate when it has reclaimed all previously allocated
376 * ASIDs that are not currently active on a processor.
378 * The current epoch number is always in the range [0, INT_MAX). Negative
379 * numbers and INT_MAX are reserved for special cases that are described
388 struct mtx asid_set_mutex;
391 static struct asid_set asids;
392 static struct asid_set vmids;
394 static SYSCTL_NODE(_vm_pmap, OID_AUTO, asid, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
396 SYSCTL_INT(_vm_pmap_asid, OID_AUTO, bits, CTLFLAG_RD, &asids.asid_bits, 0,
397 "The number of bits in an ASID");
398 SYSCTL_INT(_vm_pmap_asid, OID_AUTO, next, CTLFLAG_RD, &asids.asid_next, 0,
399 "The last allocated ASID plus one");
400 SYSCTL_INT(_vm_pmap_asid, OID_AUTO, epoch, CTLFLAG_RD, &asids.asid_epoch, 0,
401 "The current epoch number");
403 static SYSCTL_NODE(_vm_pmap, OID_AUTO, vmid, CTLFLAG_RD, 0, "VMID allocator");
404 SYSCTL_INT(_vm_pmap_vmid, OID_AUTO, bits, CTLFLAG_RD, &vmids.asid_bits, 0,
405 "The number of bits in an VMID");
406 SYSCTL_INT(_vm_pmap_vmid, OID_AUTO, next, CTLFLAG_RD, &vmids.asid_next, 0,
407 "The last allocated VMID plus one");
408 SYSCTL_INT(_vm_pmap_vmid, OID_AUTO, epoch, CTLFLAG_RD, &vmids.asid_epoch, 0,
409 "The current epoch number");
411 void (*pmap_clean_stage2_tlbi)(void);
412 void (*pmap_invalidate_vpipt_icache)(void);
413 void (*pmap_stage2_invalidate_range)(uint64_t, vm_offset_t, vm_offset_t, bool);
414 void (*pmap_stage2_invalidate_all)(uint64_t);
417 * A pmap's cookie encodes an ASID and epoch number. Cookies for reserved
418 * ASIDs have a negative epoch number, specifically, INT_MIN. Cookies for
419 * dynamically allocated ASIDs have a non-negative epoch number.
421 * An invalid ASID is represented by -1.
423 * There are two special-case cookie values: (1) COOKIE_FROM(-1, INT_MIN),
424 * which indicates that an ASID should never be allocated to the pmap, and
425 * (2) COOKIE_FROM(-1, INT_MAX), which indicates that an ASID should be
426 * allocated when the pmap is next activated.
428 #define COOKIE_FROM(asid, epoch) ((long)((u_int)(asid) | \
429 ((u_long)(epoch) << 32)))
430 #define COOKIE_TO_ASID(cookie) ((int)(cookie))
431 #define COOKIE_TO_EPOCH(cookie) ((int)((u_long)(cookie) >> 32))
433 #define TLBI_VA_SHIFT 12
434 #define TLBI_VA_MASK ((1ul << 44) - 1)
435 #define TLBI_VA(addr) (((addr) >> TLBI_VA_SHIFT) & TLBI_VA_MASK)
436 #define TLBI_VA_L3_INCR (L3_SIZE >> TLBI_VA_SHIFT)
438 static int superpages_enabled = 1;
439 SYSCTL_INT(_vm_pmap, OID_AUTO, superpages_enabled,
440 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &superpages_enabled, 0,
441 "Are large page mappings enabled?");
444 * Internal flags for pmap_enter()'s helper functions.
446 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
447 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
449 TAILQ_HEAD(pv_chunklist, pv_chunk);
451 static void free_pv_chunk(struct pv_chunk *pc);
452 static void free_pv_chunk_batch(struct pv_chunklist *batch);
453 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
454 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
455 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
456 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
457 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
460 static void pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte);
461 static bool pmap_activate_int(pmap_t pmap);
462 static void pmap_alloc_asid(pmap_t pmap);
463 static int pmap_change_props_locked(vm_offset_t va, vm_size_t size,
464 vm_prot_t prot, int mode, bool skip_unmapped);
465 static pt_entry_t *pmap_demote_l1(pmap_t pmap, pt_entry_t *l1, vm_offset_t va);
466 static pt_entry_t *pmap_demote_l2_locked(pmap_t pmap, pt_entry_t *l2,
467 vm_offset_t va, struct rwlock **lockp);
468 static pt_entry_t *pmap_demote_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va);
469 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
470 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
471 static int pmap_enter_l2(pmap_t pmap, vm_offset_t va, pd_entry_t new_l2,
472 u_int flags, vm_page_t m, struct rwlock **lockp);
473 static int pmap_remove_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva,
474 pd_entry_t l1e, struct spglist *free, struct rwlock **lockp);
475 static int pmap_remove_l3(pmap_t pmap, pt_entry_t *l3, vm_offset_t sva,
476 pd_entry_t l2e, struct spglist *free, struct rwlock **lockp);
477 static void pmap_reset_asid_set(pmap_t pmap);
478 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
479 vm_page_t m, struct rwlock **lockp);
481 static vm_page_t _pmap_alloc_l3(pmap_t pmap, vm_pindex_t ptepindex,
482 struct rwlock **lockp);
484 static void _pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m,
485 struct spglist *free);
486 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
487 static __inline vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
490 * These load the old table data and store the new value.
491 * They need to be atomic as the System MMU may write to the table at
492 * the same time as the CPU.
494 #define pmap_clear(table) atomic_store_64(table, 0)
495 #define pmap_clear_bits(table, bits) atomic_clear_64(table, bits)
496 #define pmap_load(table) (*table)
497 #define pmap_load_clear(table) atomic_swap_64(table, 0)
498 #define pmap_load_store(table, entry) atomic_swap_64(table, entry)
499 #define pmap_set_bits(table, bits) atomic_set_64(table, bits)
500 #define pmap_store(table, entry) atomic_store_64(table, entry)
502 /********************/
503 /* Inline functions */
504 /********************/
507 pagecopy(void *s, void *d)
510 memcpy(d, s, PAGE_SIZE);
513 static __inline pd_entry_t *
514 pmap_l0(pmap_t pmap, vm_offset_t va)
517 return (&pmap->pm_l0[pmap_l0_index(va)]);
520 static __inline pd_entry_t *
521 pmap_l0_to_l1(pd_entry_t *l0, vm_offset_t va)
525 l1 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(pmap_load(l0)));
526 return (&l1[pmap_l1_index(va)]);
529 static __inline pd_entry_t *
530 pmap_l1(pmap_t pmap, vm_offset_t va)
534 l0 = pmap_l0(pmap, va);
535 if ((pmap_load(l0) & ATTR_DESCR_MASK) != L0_TABLE)
538 return (pmap_l0_to_l1(l0, va));
541 static __inline pd_entry_t *
542 pmap_l1_to_l2(pd_entry_t *l1p, vm_offset_t va)
548 KASSERT(ADDR_IS_CANONICAL(va),
549 ("%s: Address not in canonical form: %lx", __func__, va));
551 * The valid bit may be clear if pmap_update_entry() is concurrently
552 * modifying the entry, so for KVA only the entry type may be checked.
554 KASSERT(ADDR_IS_KERNEL(va) || (l1 & ATTR_DESCR_VALID) != 0,
555 ("%s: L1 entry %#lx for %#lx is invalid", __func__, l1, va));
556 KASSERT((l1 & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_TABLE,
557 ("%s: L1 entry %#lx for %#lx is a leaf", __func__, l1, va));
558 l2p = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(l1));
559 return (&l2p[pmap_l2_index(va)]);
562 static __inline pd_entry_t *
563 pmap_l2(pmap_t pmap, vm_offset_t va)
567 l1 = pmap_l1(pmap, va);
568 if ((pmap_load(l1) & ATTR_DESCR_MASK) != L1_TABLE)
571 return (pmap_l1_to_l2(l1, va));
574 static __inline pt_entry_t *
575 pmap_l2_to_l3(pd_entry_t *l2p, vm_offset_t va)
582 KASSERT(ADDR_IS_CANONICAL(va),
583 ("%s: Address not in canonical form: %lx", __func__, va));
585 * The valid bit may be clear if pmap_update_entry() is concurrently
586 * modifying the entry, so for KVA only the entry type may be checked.
588 KASSERT(ADDR_IS_KERNEL(va) || (l2 & ATTR_DESCR_VALID) != 0,
589 ("%s: L2 entry %#lx for %#lx is invalid", __func__, l2, va));
590 KASSERT((l2 & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_TABLE,
591 ("%s: L2 entry %#lx for %#lx is a leaf", __func__, l2, va));
592 l3p = (pt_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(l2));
593 return (&l3p[pmap_l3_index(va)]);
597 * Returns the lowest valid pde for a given virtual address.
598 * The next level may or may not point to a valid page or block.
600 static __inline pd_entry_t *
601 pmap_pde(pmap_t pmap, vm_offset_t va, int *level)
603 pd_entry_t *l0, *l1, *l2, desc;
605 l0 = pmap_l0(pmap, va);
606 desc = pmap_load(l0) & ATTR_DESCR_MASK;
607 if (desc != L0_TABLE) {
612 l1 = pmap_l0_to_l1(l0, va);
613 desc = pmap_load(l1) & ATTR_DESCR_MASK;
614 if (desc != L1_TABLE) {
619 l2 = pmap_l1_to_l2(l1, va);
620 desc = pmap_load(l2) & ATTR_DESCR_MASK;
621 if (desc != L2_TABLE) {
631 * Returns the lowest valid pte block or table entry for a given virtual
632 * address. If there are no valid entries return NULL and set the level to
633 * the first invalid level.
635 static __inline pt_entry_t *
636 pmap_pte(pmap_t pmap, vm_offset_t va, int *level)
638 pd_entry_t *l1, *l2, desc;
641 l1 = pmap_l1(pmap, va);
646 desc = pmap_load(l1) & ATTR_DESCR_MASK;
647 if (desc == L1_BLOCK) {
648 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
653 if (desc != L1_TABLE) {
658 l2 = pmap_l1_to_l2(l1, va);
659 desc = pmap_load(l2) & ATTR_DESCR_MASK;
660 if (desc == L2_BLOCK) {
665 if (desc != L2_TABLE) {
671 l3 = pmap_l2_to_l3(l2, va);
672 if ((pmap_load(l3) & ATTR_DESCR_MASK) != L3_PAGE)
679 * If the given pmap has an L{1,2}_BLOCK or L3_PAGE entry at the specified
680 * level that maps the specified virtual address, then a pointer to that entry
681 * is returned. Otherwise, NULL is returned, unless INVARIANTS are enabled
682 * and a diagnostic message is provided, in which case this function panics.
684 static __always_inline pt_entry_t *
685 pmap_pte_exists(pmap_t pmap, vm_offset_t va, int level, const char *diag)
687 pd_entry_t *l0p, *l1p, *l2p;
688 pt_entry_t desc, *l3p;
689 int walk_level __diagused;
691 KASSERT(level >= 0 && level < 4,
692 ("%s: %s passed an out-of-range level (%d)", __func__, diag,
694 l0p = pmap_l0(pmap, va);
695 desc = pmap_load(l0p) & ATTR_DESCR_MASK;
696 if (desc == L0_TABLE && level > 0) {
697 l1p = pmap_l0_to_l1(l0p, va);
698 desc = pmap_load(l1p) & ATTR_DESCR_MASK;
699 if (desc == L1_BLOCK && level == 1) {
700 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
703 if (desc == L1_TABLE && level > 1) {
704 l2p = pmap_l1_to_l2(l1p, va);
705 desc = pmap_load(l2p) & ATTR_DESCR_MASK;
706 if (desc == L2_BLOCK && level == 2)
708 else if (desc == L2_TABLE && level > 2) {
709 l3p = pmap_l2_to_l3(l2p, va);
710 desc = pmap_load(l3p) & ATTR_DESCR_MASK;
711 if (desc == L3_PAGE && level == 3)
721 KASSERT(diag == NULL,
722 ("%s: va %#lx not mapped at level %d, desc %ld at level %d",
723 diag, va, level, desc, walk_level));
728 pmap_ps_enabled(pmap_t pmap)
731 * Promotion requires a hypervisor call when the kernel is running
732 * in EL1. To stop this disable superpage support on non-stage 1
735 if (pmap->pm_stage != PM_STAGE1)
738 return (superpages_enabled != 0);
742 pmap_get_tables(pmap_t pmap, vm_offset_t va, pd_entry_t **l0, pd_entry_t **l1,
743 pd_entry_t **l2, pt_entry_t **l3)
745 pd_entry_t *l0p, *l1p, *l2p;
747 if (pmap->pm_l0 == NULL)
750 l0p = pmap_l0(pmap, va);
753 if ((pmap_load(l0p) & ATTR_DESCR_MASK) != L0_TABLE)
756 l1p = pmap_l0_to_l1(l0p, va);
759 if ((pmap_load(l1p) & ATTR_DESCR_MASK) == L1_BLOCK) {
760 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
766 if ((pmap_load(l1p) & ATTR_DESCR_MASK) != L1_TABLE)
769 l2p = pmap_l1_to_l2(l1p, va);
772 if ((pmap_load(l2p) & ATTR_DESCR_MASK) == L2_BLOCK) {
777 if ((pmap_load(l2p) & ATTR_DESCR_MASK) != L2_TABLE)
780 *l3 = pmap_l2_to_l3(l2p, va);
786 pmap_l3_valid(pt_entry_t l3)
789 return ((l3 & ATTR_DESCR_MASK) == L3_PAGE);
792 CTASSERT(L1_BLOCK == L2_BLOCK);
795 pmap_pte_memattr(pmap_t pmap, vm_memattr_t memattr)
799 if (pmap->pm_stage == PM_STAGE1) {
800 val = ATTR_S1_IDX(memattr);
801 if (memattr == VM_MEMATTR_DEVICE)
809 case VM_MEMATTR_DEVICE:
810 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_DEVICE_nGnRnE) |
811 ATTR_S2_XN(ATTR_S2_XN_ALL));
812 case VM_MEMATTR_UNCACHEABLE:
813 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_NC));
814 case VM_MEMATTR_WRITE_BACK:
815 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_WB));
816 case VM_MEMATTR_WRITE_THROUGH:
817 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_WT));
819 panic("%s: invalid memory attribute %x", __func__, memattr);
824 pmap_pte_prot(pmap_t pmap, vm_prot_t prot)
829 if (pmap->pm_stage == PM_STAGE1) {
830 if ((prot & VM_PROT_EXECUTE) == 0)
832 if ((prot & VM_PROT_WRITE) == 0)
833 val |= ATTR_S1_AP(ATTR_S1_AP_RO);
835 if ((prot & VM_PROT_WRITE) != 0)
836 val |= ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
837 if ((prot & VM_PROT_READ) != 0)
838 val |= ATTR_S2_S2AP(ATTR_S2_S2AP_READ);
839 if ((prot & VM_PROT_EXECUTE) == 0)
840 val |= ATTR_S2_XN(ATTR_S2_XN_ALL);
847 * Checks if the PTE is dirty.
850 pmap_pte_dirty(pmap_t pmap, pt_entry_t pte)
853 KASSERT((pte & ATTR_SW_MANAGED) != 0, ("pte %#lx is unmanaged", pte));
855 if (pmap->pm_stage == PM_STAGE1) {
856 KASSERT((pte & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) != 0,
857 ("pte %#lx is writeable and missing ATTR_SW_DBM", pte));
859 return ((pte & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
860 (ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_SW_DBM));
863 return ((pte & ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE)) ==
864 ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE));
868 pmap_resident_count_inc(pmap_t pmap, int count)
871 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
872 pmap->pm_stats.resident_count += count;
876 pmap_resident_count_dec(pmap_t pmap, int count)
879 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
880 KASSERT(pmap->pm_stats.resident_count >= count,
881 ("pmap %p resident count underflow %ld %d", pmap,
882 pmap->pm_stats.resident_count, count));
883 pmap->pm_stats.resident_count -= count;
887 pmap_early_vtophys(vm_offset_t va)
891 pa_page = arm64_address_translate_s1e1r(va) & PAR_PA_MASK;
892 return (pa_page | (va & PAR_LOW_MASK));
895 /* State of the bootstrapped DMAP page tables */
896 struct pmap_bootstrap_state {
900 vm_offset_t freemempos;
903 pt_entry_t table_attrs;
910 /* The bootstrap state */
911 static struct pmap_bootstrap_state bs_state = {
915 .table_attrs = TATTR_PXN_TABLE,
916 .l0_slot = L0_ENTRIES,
917 .l1_slot = Ln_ENTRIES,
918 .l2_slot = Ln_ENTRIES,
923 pmap_bootstrap_l0_table(struct pmap_bootstrap_state *state)
929 /* Link the level 0 table to a level 1 table */
930 l0_slot = pmap_l0_index(state->va);
931 if (l0_slot != state->l0_slot) {
933 * Make sure we move from a low address to high address
934 * before the DMAP region is ready. This ensures we never
935 * modify an existing mapping until we can map from a
936 * physical address to a virtual address.
938 MPASS(state->l0_slot < l0_slot ||
939 state->l0_slot == L0_ENTRIES ||
942 /* Reset lower levels */
945 state->l1_slot = Ln_ENTRIES;
946 state->l2_slot = Ln_ENTRIES;
948 /* Check the existing L0 entry */
949 state->l0_slot = l0_slot;
950 if (state->dmap_valid) {
951 l0e = pagetable_l0_ttbr1[l0_slot];
952 if ((l0e & ATTR_DESCR_VALID) != 0) {
953 MPASS((l0e & ATTR_DESCR_MASK) == L0_TABLE);
954 l1_pa = PTE_TO_PHYS(l0e);
955 state->l1 = (pt_entry_t *)PHYS_TO_DMAP(l1_pa);
960 /* Create a new L0 table entry */
961 state->l1 = (pt_entry_t *)state->freemempos;
962 memset(state->l1, 0, PAGE_SIZE);
963 state->freemempos += PAGE_SIZE;
965 l1_pa = pmap_early_vtophys((vm_offset_t)state->l1);
966 MPASS((l1_pa & Ln_TABLE_MASK) == 0);
967 MPASS(pagetable_l0_ttbr1[l0_slot] == 0);
968 pmap_store(&pagetable_l0_ttbr1[l0_slot], PHYS_TO_PTE(l1_pa) |
969 TATTR_UXN_TABLE | TATTR_AP_TABLE_NO_EL0 | L0_TABLE);
971 KASSERT(state->l1 != NULL, ("%s: NULL l1", __func__));
975 pmap_bootstrap_l1_table(struct pmap_bootstrap_state *state)
981 /* Make sure there is a valid L0 -> L1 table */
982 pmap_bootstrap_l0_table(state);
984 /* Link the level 1 table to a level 2 table */
985 l1_slot = pmap_l1_index(state->va);
986 if (l1_slot != state->l1_slot) {
987 /* See pmap_bootstrap_l0_table for a description */
988 MPASS(state->l1_slot < l1_slot ||
989 state->l1_slot == Ln_ENTRIES ||
992 /* Reset lower levels */
994 state->l2_slot = Ln_ENTRIES;
996 /* Check the existing L1 entry */
997 state->l1_slot = l1_slot;
998 if (state->dmap_valid) {
999 l1e = state->l1[l1_slot];
1000 if ((l1e & ATTR_DESCR_VALID) != 0) {
1001 MPASS((l1e & ATTR_DESCR_MASK) == L1_TABLE);
1002 l2_pa = PTE_TO_PHYS(l1e);
1003 state->l2 = (pt_entry_t *)PHYS_TO_DMAP(l2_pa);
1008 /* Create a new L1 table entry */
1009 state->l2 = (pt_entry_t *)state->freemempos;
1010 memset(state->l2, 0, PAGE_SIZE);
1011 state->freemempos += PAGE_SIZE;
1013 l2_pa = pmap_early_vtophys((vm_offset_t)state->l2);
1014 MPASS((l2_pa & Ln_TABLE_MASK) == 0);
1015 MPASS(state->l1[l1_slot] == 0);
1016 pmap_store(&state->l1[l1_slot], PHYS_TO_PTE(l2_pa) |
1017 state->table_attrs | L1_TABLE);
1019 KASSERT(state->l2 != NULL, ("%s: NULL l2", __func__));
1023 pmap_bootstrap_l2_table(struct pmap_bootstrap_state *state)
1029 /* Make sure there is a valid L1 -> L2 table */
1030 pmap_bootstrap_l1_table(state);
1032 /* Link the level 2 table to a level 3 table */
1033 l2_slot = pmap_l2_index(state->va);
1034 if (l2_slot != state->l2_slot) {
1035 /* See pmap_bootstrap_l0_table for a description */
1036 MPASS(state->l2_slot < l2_slot ||
1037 state->l2_slot == Ln_ENTRIES ||
1040 /* Check the existing L2 entry */
1041 state->l2_slot = l2_slot;
1042 if (state->dmap_valid) {
1043 l2e = state->l2[l2_slot];
1044 if ((l2e & ATTR_DESCR_VALID) != 0) {
1045 MPASS((l2e & ATTR_DESCR_MASK) == L2_TABLE);
1046 l3_pa = PTE_TO_PHYS(l2e);
1047 state->l3 = (pt_entry_t *)PHYS_TO_DMAP(l3_pa);
1052 /* Create a new L2 table entry */
1053 state->l3 = (pt_entry_t *)state->freemempos;
1054 memset(state->l3, 0, PAGE_SIZE);
1055 state->freemempos += PAGE_SIZE;
1057 l3_pa = pmap_early_vtophys((vm_offset_t)state->l3);
1058 MPASS((l3_pa & Ln_TABLE_MASK) == 0);
1059 MPASS(state->l2[l2_slot] == 0);
1060 pmap_store(&state->l2[l2_slot], PHYS_TO_PTE(l3_pa) |
1061 state->table_attrs | L2_TABLE);
1063 KASSERT(state->l3 != NULL, ("%s: NULL l3", __func__));
1067 pmap_bootstrap_l2_block(struct pmap_bootstrap_state *state, int i)
1072 if ((physmap[i + 1] - state->pa) < L2_SIZE)
1075 /* Make sure there is a valid L1 table */
1076 pmap_bootstrap_l1_table(state);
1078 MPASS((state->va & L2_OFFSET) == 0);
1080 state->va < DMAP_MAX_ADDRESS &&
1081 (physmap[i + 1] - state->pa) >= L2_SIZE;
1082 state->va += L2_SIZE, state->pa += L2_SIZE) {
1084 * Stop if we are about to walk off the end of what the
1085 * current L1 slot can address.
1087 if (!first && (state->pa & L1_OFFSET) == 0)
1091 l2_slot = pmap_l2_index(state->va);
1092 MPASS((state->pa & L2_OFFSET) == 0);
1093 MPASS(state->l2[l2_slot] == 0);
1094 pmap_store(&state->l2[l2_slot], PHYS_TO_PTE(state->pa) |
1095 ATTR_DEFAULT | ATTR_S1_XN |
1096 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) | L2_BLOCK);
1098 MPASS(state->va == (state->pa - dmap_phys_base + DMAP_MIN_ADDRESS));
1102 pmap_bootstrap_l3_page(struct pmap_bootstrap_state *state, int i)
1107 if ((physmap[i + 1] - state->pa) < L3_SIZE)
1110 /* Make sure there is a valid L2 table */
1111 pmap_bootstrap_l2_table(state);
1113 MPASS((state->va & L3_OFFSET) == 0);
1115 state->va < DMAP_MAX_ADDRESS &&
1116 (physmap[i + 1] - state->pa) >= L3_SIZE;
1117 state->va += L3_SIZE, state->pa += L3_SIZE) {
1119 * Stop if we are about to walk off the end of what the
1120 * current L2 slot can address.
1122 if (!first && (state->pa & L2_OFFSET) == 0)
1126 l3_slot = pmap_l3_index(state->va);
1127 MPASS((state->pa & L3_OFFSET) == 0);
1128 MPASS(state->l3[l3_slot] == 0);
1129 pmap_store(&state->l3[l3_slot], PHYS_TO_PTE(state->pa) |
1130 ATTR_DEFAULT | ATTR_S1_XN |
1131 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) | L3_PAGE);
1133 MPASS(state->va == (state->pa - dmap_phys_base + DMAP_MIN_ADDRESS));
1137 pmap_bootstrap_dmap(vm_paddr_t min_pa)
1141 dmap_phys_base = min_pa & ~L1_OFFSET;
1145 for (i = 0; i < (physmap_idx * 2); i += 2) {
1146 bs_state.pa = physmap[i] & ~L3_OFFSET;
1147 bs_state.va = bs_state.pa - dmap_phys_base + DMAP_MIN_ADDRESS;
1149 /* Create L3 mappings at the start of the region */
1150 if ((bs_state.pa & L2_OFFSET) != 0)
1151 pmap_bootstrap_l3_page(&bs_state, i);
1152 MPASS(bs_state.pa <= physmap[i + 1]);
1154 if (L1_BLOCKS_SUPPORTED) {
1155 /* Create L2 mappings at the start of the region */
1156 if ((bs_state.pa & L1_OFFSET) != 0)
1157 pmap_bootstrap_l2_block(&bs_state, i);
1158 MPASS(bs_state.pa <= physmap[i + 1]);
1160 /* Create the main L1 block mappings */
1161 for (; bs_state.va < DMAP_MAX_ADDRESS &&
1162 (physmap[i + 1] - bs_state.pa) >= L1_SIZE;
1163 bs_state.va += L1_SIZE, bs_state.pa += L1_SIZE) {
1164 /* Make sure there is a valid L1 table */
1165 pmap_bootstrap_l0_table(&bs_state);
1166 MPASS((bs_state.pa & L1_OFFSET) == 0);
1168 &bs_state.l1[pmap_l1_index(bs_state.va)],
1169 PHYS_TO_PTE(bs_state.pa) | ATTR_DEFAULT |
1170 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) |
1171 ATTR_S1_XN | L1_BLOCK);
1173 MPASS(bs_state.pa <= physmap[i + 1]);
1175 /* Create L2 mappings at the end of the region */
1176 pmap_bootstrap_l2_block(&bs_state, i);
1178 while (bs_state.va < DMAP_MAX_ADDRESS &&
1179 (physmap[i + 1] - bs_state.pa) >= L2_SIZE) {
1180 pmap_bootstrap_l2_block(&bs_state, i);
1183 MPASS(bs_state.pa <= physmap[i + 1]);
1185 /* Create L3 mappings at the end of the region */
1186 pmap_bootstrap_l3_page(&bs_state, i);
1187 MPASS(bs_state.pa == physmap[i + 1]);
1189 if (bs_state.pa > dmap_phys_max) {
1190 dmap_phys_max = bs_state.pa;
1191 dmap_max_addr = bs_state.va;
1199 pmap_bootstrap_l2(vm_offset_t va)
1201 KASSERT((va & L1_OFFSET) == 0, ("Invalid virtual address"));
1203 /* Leave bs_state.pa as it's only needed to bootstrap blocks and pages*/
1206 for (; bs_state.va < VM_MAX_KERNEL_ADDRESS; bs_state.va += L1_SIZE)
1207 pmap_bootstrap_l1_table(&bs_state);
1211 pmap_bootstrap_l3(vm_offset_t va)
1213 KASSERT((va & L2_OFFSET) == 0, ("Invalid virtual address"));
1215 /* Leave bs_state.pa as it's only needed to bootstrap blocks and pages*/
1218 for (; bs_state.va < VM_MAX_KERNEL_ADDRESS; bs_state.va += L2_SIZE)
1219 pmap_bootstrap_l2_table(&bs_state);
1224 pmap_bootstrap_allocate_kasan_l2(vm_paddr_t start_pa, vm_paddr_t end_pa,
1225 vm_offset_t *start_va, int *nkasan_l2)
1233 pa = rounddown2(end_pa - L2_SIZE, L2_SIZE);
1234 l2 = pmap_l2(kernel_pmap, va);
1236 for (i = 0; pa >= start_pa && i < *nkasan_l2;
1237 i++, va += L2_SIZE, pa -= L2_SIZE, l2++) {
1239 * KASAN stack checking results in us having already allocated
1240 * part of our shadow map, so we can just skip those segments.
1242 if ((pmap_load(l2) & ATTR_DESCR_VALID) != 0) {
1247 pmap_store(l2, PHYS_TO_PTE(pa) | PMAP_SAN_PTE_BITS | L2_BLOCK);
1251 * Ended the allocation due to start_pa constraint, rather than because
1252 * we allocated everything. Adjust back up to the start_pa and remove
1253 * the invalid L2 block from our accounting.
1255 if (pa < start_pa) {
1261 bzero((void *)PHYS_TO_DMAP(pa), i * L2_SIZE);
1262 physmem_exclude_region(pa, i * L2_SIZE, EXFLAG_NOALLOC);
1270 * Bootstrap the system enough to run with virtual memory.
1273 pmap_bootstrap(vm_paddr_t kernstart, vm_size_t kernlen)
1275 vm_offset_t dpcpu, msgbufpv;
1276 vm_paddr_t start_pa, pa, min_pa;
1277 uint64_t kern_delta;
1280 /* Verify that the ASID is set through TTBR0. */
1281 KASSERT((READ_SPECIALREG(tcr_el1) & TCR_A1) == 0,
1282 ("pmap_bootstrap: TCR_EL1.A1 != 0"));
1284 kern_delta = KERNBASE - kernstart;
1286 printf("pmap_bootstrap %lx %lx\n", kernstart, kernlen);
1287 printf("%lx\n", (KERNBASE >> L1_SHIFT) & Ln_ADDR_MASK);
1289 /* Set this early so we can use the pagetable walking functions */
1290 kernel_pmap_store.pm_l0 = pagetable_l0_ttbr1;
1291 PMAP_LOCK_INIT(kernel_pmap);
1292 kernel_pmap->pm_l0_paddr =
1293 pmap_early_vtophys((vm_offset_t)kernel_pmap_store.pm_l0);
1294 kernel_pmap->pm_cookie = COOKIE_FROM(-1, INT_MIN);
1295 kernel_pmap->pm_stage = PM_STAGE1;
1296 kernel_pmap->pm_levels = 4;
1297 kernel_pmap->pm_ttbr = kernel_pmap->pm_l0_paddr;
1298 kernel_pmap->pm_asid_set = &asids;
1300 /* Assume the address we were loaded to is a valid physical address */
1301 min_pa = KERNBASE - kern_delta;
1303 physmap_idx = physmem_avail(physmap, nitems(physmap));
1307 * Find the minimum physical address. physmap is sorted,
1308 * but may contain empty ranges.
1310 for (i = 0; i < physmap_idx * 2; i += 2) {
1311 if (physmap[i] == physmap[i + 1])
1313 if (physmap[i] <= min_pa)
1314 min_pa = physmap[i];
1317 bs_state.freemempos = KERNBASE + kernlen;
1318 bs_state.freemempos = roundup2(bs_state.freemempos, PAGE_SIZE);
1320 /* Create a direct map region early so we can use it for pa -> va */
1321 pmap_bootstrap_dmap(min_pa);
1322 bs_state.dmap_valid = true;
1324 * We only use PXN when we know nothing will be executed from it, e.g.
1327 bs_state.table_attrs &= ~TATTR_PXN_TABLE;
1329 start_pa = pa = KERNBASE - kern_delta;
1332 * Create the l2 tables up to VM_MAX_KERNEL_ADDRESS. We assume that the
1333 * loader allocated the first and only l2 page table page used to map
1334 * the kernel, preloaded files and module metadata.
1336 pmap_bootstrap_l2(KERNBASE + L1_SIZE);
1337 /* And the l3 tables for the early devmap */
1338 pmap_bootstrap_l3(VM_MAX_KERNEL_ADDRESS - (PMAP_MAPDEV_EARLY_SIZE));
1342 #define alloc_pages(var, np) \
1343 (var) = bs_state.freemempos; \
1344 bs_state.freemempos += (np * PAGE_SIZE); \
1345 memset((char *)(var), 0, ((np) * PAGE_SIZE));
1347 /* Allocate dynamic per-cpu area. */
1348 alloc_pages(dpcpu, DPCPU_SIZE / PAGE_SIZE);
1349 dpcpu_init((void *)dpcpu, 0);
1351 /* Allocate memory for the msgbuf, e.g. for /sbin/dmesg */
1352 alloc_pages(msgbufpv, round_page(msgbufsize) / PAGE_SIZE);
1353 msgbufp = (void *)msgbufpv;
1355 /* Reserve some VA space for early BIOS/ACPI mapping */
1356 preinit_map_va = roundup2(bs_state.freemempos, L2_SIZE);
1358 virtual_avail = preinit_map_va + PMAP_PREINIT_MAPPING_SIZE;
1359 virtual_avail = roundup2(virtual_avail, L1_SIZE);
1360 virtual_end = VM_MAX_KERNEL_ADDRESS - (PMAP_MAPDEV_EARLY_SIZE);
1361 kernel_vm_end = virtual_avail;
1363 pa = pmap_early_vtophys(bs_state.freemempos);
1365 physmem_exclude_region(start_pa, pa - start_pa, EXFLAG_NOALLOC);
1372 * Finish constructing the initial shadow map:
1373 * - Count how many pages from KERNBASE to virtual_avail (scaled for
1375 * - Map that entire range using L2 superpages.
1378 pmap_bootstrap_san(vm_paddr_t kernstart)
1381 int i, shadow_npages, nkasan_l2;
1384 * Rebuild physmap one more time, we may have excluded more regions from
1385 * allocation since pmap_bootstrap().
1387 bzero(physmap, sizeof(physmap));
1388 physmap_idx = physmem_avail(physmap, nitems(physmap));
1391 shadow_npages = (virtual_avail - VM_MIN_KERNEL_ADDRESS) / PAGE_SIZE;
1392 shadow_npages = howmany(shadow_npages, KASAN_SHADOW_SCALE);
1393 nkasan_l2 = howmany(shadow_npages, Ln_ENTRIES);
1395 /* Map the valid KVA up to this point. */
1396 va = KASAN_MIN_ADDRESS;
1399 * Find a slot in the physmap large enough for what we needed. We try to put
1400 * the shadow map as high up as we can to avoid depleting the lower 4GB in case
1401 * it's needed for, e.g., an xhci controller that can only do 32-bit DMA.
1403 for (i = (physmap_idx * 2) - 2; i >= 0 && nkasan_l2 > 0; i -= 2) {
1404 vm_paddr_t plow, phigh;
1406 /* L2 mappings must be backed by memory that is L2-aligned */
1407 plow = roundup2(physmap[i], L2_SIZE);
1408 phigh = physmap[i + 1];
1411 if (kernstart >= plow && kernstart < phigh)
1413 if (phigh - plow >= L2_SIZE)
1414 pmap_bootstrap_allocate_kasan_l2(plow, phigh, &va,
1419 panic("Could not find phys region for shadow map");
1422 * Done. We should now have a valid shadow address mapped for all KVA
1423 * that has been mapped so far, i.e., KERNBASE to virtual_avail. Thus,
1424 * shadow accesses by the kasan(9) runtime will succeed for this range.
1425 * When the kernel virtual address range is later expanded, as will
1426 * happen in vm_mem_init(), the shadow map will be grown as well. This
1427 * is handled by pmap_san_enter().
1433 * Initialize a vm_page's machine-dependent fields.
1436 pmap_page_init(vm_page_t m)
1439 TAILQ_INIT(&m->md.pv_list);
1440 m->md.pv_memattr = VM_MEMATTR_WRITE_BACK;
1444 pmap_init_asids(struct asid_set *set, int bits)
1448 set->asid_bits = bits;
1451 * We may be too early in the overall initialization process to use
1454 set->asid_set_size = 1 << set->asid_bits;
1455 set->asid_set = kmem_malloc(bitstr_size(set->asid_set_size),
1457 for (i = 0; i < ASID_FIRST_AVAILABLE; i++)
1458 bit_set(set->asid_set, i);
1459 set->asid_next = ASID_FIRST_AVAILABLE;
1460 mtx_init(&set->asid_set_mutex, "asid set", NULL, MTX_SPIN);
1464 pmap_init_pv_table(void)
1466 struct vm_phys_seg *seg, *next_seg;
1467 struct pmap_large_md_page *pvd;
1469 int domain, i, j, pages;
1472 * We strongly depend on the size being a power of two, so the assert
1473 * is overzealous. However, should the struct be resized to a
1474 * different power of two, the code below needs to be revisited.
1476 CTASSERT((sizeof(*pvd) == 64));
1479 * Calculate the size of the array.
1482 for (i = 0; i < vm_phys_nsegs; i++) {
1483 seg = &vm_phys_segs[i];
1484 pages = pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) -
1485 pmap_l2_pindex(seg->start);
1486 s += round_page(pages * sizeof(*pvd));
1488 pv_table = (struct pmap_large_md_page *)kva_alloc(s);
1489 if (pv_table == NULL)
1490 panic("%s: kva_alloc failed\n", __func__);
1493 * Iterate physical segments to allocate domain-local memory for PV
1497 for (i = 0; i < vm_phys_nsegs; i++) {
1498 seg = &vm_phys_segs[i];
1499 pages = pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) -
1500 pmap_l2_pindex(seg->start);
1501 domain = seg->domain;
1503 s = round_page(pages * sizeof(*pvd));
1505 for (j = 0; j < s; j += PAGE_SIZE) {
1506 vm_page_t m = vm_page_alloc_noobj_domain(domain,
1509 panic("failed to allocate PV table page");
1510 pmap_qenter((vm_offset_t)pvd + j, &m, 1);
1513 for (j = 0; j < s / sizeof(*pvd); j++) {
1514 rw_init_flags(&pvd->pv_lock, "pmap pv list", RW_NEW);
1515 TAILQ_INIT(&pvd->pv_page.pv_list);
1519 pvd = &pv_dummy_large;
1520 memset(pvd, 0, sizeof(*pvd));
1521 rw_init_flags(&pvd->pv_lock, "pmap pv list dummy", RW_NEW);
1522 TAILQ_INIT(&pvd->pv_page.pv_list);
1525 * Set pointers from vm_phys_segs to pv_table.
1527 for (i = 0, pvd = pv_table; i < vm_phys_nsegs; i++) {
1528 seg = &vm_phys_segs[i];
1529 seg->md_first = pvd;
1530 pvd += pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) -
1531 pmap_l2_pindex(seg->start);
1534 * If there is a following segment, and the final
1535 * superpage of this segment and the initial superpage
1536 * of the next segment are the same then adjust the
1537 * pv_table entry for that next segment down by one so
1538 * that the pv_table entries will be shared.
1540 if (i + 1 < vm_phys_nsegs) {
1541 next_seg = &vm_phys_segs[i + 1];
1542 if (pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) - 1 ==
1543 pmap_l2_pindex(next_seg->start)) {
1551 * Initialize the pmap module.
1552 * Called by vm_init, to initialize any structures that the pmap
1553 * system needs to map virtual memory.
1562 * Are large page mappings enabled?
1564 TUNABLE_INT_FETCH("vm.pmap.superpages_enabled", &superpages_enabled);
1565 if (superpages_enabled) {
1566 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1567 ("pmap_init: can't assign to pagesizes[1]"));
1568 pagesizes[1] = L2_SIZE;
1569 if (L1_BLOCKS_SUPPORTED) {
1570 KASSERT(MAXPAGESIZES > 2 && pagesizes[2] == 0,
1571 ("pmap_init: can't assign to pagesizes[2]"));
1572 pagesizes[2] = L1_SIZE;
1577 * Initialize the ASID allocator.
1579 pmap_init_asids(&asids,
1580 (READ_SPECIALREG(tcr_el1) & TCR_ASID_16) != 0 ? 16 : 8);
1583 mmfr1 = READ_SPECIALREG(id_aa64mmfr1_el1);
1586 if (ID_AA64MMFR1_VMIDBits_VAL(mmfr1) ==
1587 ID_AA64MMFR1_VMIDBits_16)
1589 pmap_init_asids(&vmids, vmid_bits);
1593 * Initialize pv chunk lists.
1595 for (i = 0; i < PMAP_MEMDOM; i++) {
1596 mtx_init(&pv_chunks[i].pvc_lock, "pmap pv chunk list", NULL,
1598 TAILQ_INIT(&pv_chunks[i].pvc_list);
1600 pmap_init_pv_table();
1605 static SYSCTL_NODE(_vm_pmap, OID_AUTO, l2, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
1606 "2MB page mapping counters");
1608 static u_long pmap_l2_demotions;
1609 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, demotions, CTLFLAG_RD,
1610 &pmap_l2_demotions, 0, "2MB page demotions");
1612 static u_long pmap_l2_mappings;
1613 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, mappings, CTLFLAG_RD,
1614 &pmap_l2_mappings, 0, "2MB page mappings");
1616 static u_long pmap_l2_p_failures;
1617 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, p_failures, CTLFLAG_RD,
1618 &pmap_l2_p_failures, 0, "2MB page promotion failures");
1620 static u_long pmap_l2_promotions;
1621 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, promotions, CTLFLAG_RD,
1622 &pmap_l2_promotions, 0, "2MB page promotions");
1625 * If the given value for "final_only" is false, then any cached intermediate-
1626 * level entries, i.e., L{0,1,2}_TABLE entries, are invalidated in addition to
1627 * any cached final-level entry, i.e., either an L{1,2}_BLOCK or L3_PAGE entry.
1628 * Otherwise, just the cached final-level entry is invalidated.
1630 static __inline void
1631 pmap_s1_invalidate_kernel(uint64_t r, bool final_only)
1634 __asm __volatile("tlbi vaale1is, %0" : : "r" (r));
1636 __asm __volatile("tlbi vaae1is, %0" : : "r" (r));
1639 static __inline void
1640 pmap_s1_invalidate_user(uint64_t r, bool final_only)
1643 __asm __volatile("tlbi vale1is, %0" : : "r" (r));
1645 __asm __volatile("tlbi vae1is, %0" : : "r" (r));
1649 * Invalidates any cached final- and optionally intermediate-level TLB entries
1650 * for the specified virtual address in the given virtual address space.
1652 static __inline void
1653 pmap_s1_invalidate_page(pmap_t pmap, vm_offset_t va, bool final_only)
1657 PMAP_ASSERT_STAGE1(pmap);
1661 if (pmap == kernel_pmap) {
1662 pmap_s1_invalidate_kernel(r, final_only);
1664 r |= ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
1665 pmap_s1_invalidate_user(r, final_only);
1671 static __inline void
1672 pmap_s2_invalidate_page(pmap_t pmap, vm_offset_t va, bool final_only)
1674 PMAP_ASSERT_STAGE2(pmap);
1675 MPASS(pmap_stage2_invalidate_range != NULL);
1676 pmap_stage2_invalidate_range(pmap_to_ttbr0(pmap), va, va + PAGE_SIZE,
1680 static __inline void
1681 pmap_invalidate_page(pmap_t pmap, vm_offset_t va, bool final_only)
1683 if (pmap->pm_stage == PM_STAGE1)
1684 pmap_s1_invalidate_page(pmap, va, final_only);
1686 pmap_s2_invalidate_page(pmap, va, final_only);
1690 * Invalidates any cached final- and optionally intermediate-level TLB entries
1691 * for the specified virtual address range in the given virtual address space.
1693 static __inline void
1694 pmap_s1_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1697 uint64_t end, r, start;
1699 PMAP_ASSERT_STAGE1(pmap);
1702 if (pmap == kernel_pmap) {
1703 start = TLBI_VA(sva);
1705 for (r = start; r < end; r += TLBI_VA_L3_INCR)
1706 pmap_s1_invalidate_kernel(r, final_only);
1708 start = end = ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
1709 start |= TLBI_VA(sva);
1710 end |= TLBI_VA(eva);
1711 for (r = start; r < end; r += TLBI_VA_L3_INCR)
1712 pmap_s1_invalidate_user(r, final_only);
1718 static __inline void
1719 pmap_s2_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1722 PMAP_ASSERT_STAGE2(pmap);
1723 MPASS(pmap_stage2_invalidate_range != NULL);
1724 pmap_stage2_invalidate_range(pmap_to_ttbr0(pmap), sva, eva, final_only);
1727 static __inline void
1728 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1731 if (pmap->pm_stage == PM_STAGE1)
1732 pmap_s1_invalidate_range(pmap, sva, eva, final_only);
1734 pmap_s2_invalidate_range(pmap, sva, eva, final_only);
1738 * Invalidates all cached intermediate- and final-level TLB entries for the
1739 * given virtual address space.
1741 static __inline void
1742 pmap_s1_invalidate_all(pmap_t pmap)
1746 PMAP_ASSERT_STAGE1(pmap);
1749 if (pmap == kernel_pmap) {
1750 __asm __volatile("tlbi vmalle1is");
1752 r = ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
1753 __asm __volatile("tlbi aside1is, %0" : : "r" (r));
1759 static __inline void
1760 pmap_s2_invalidate_all(pmap_t pmap)
1762 PMAP_ASSERT_STAGE2(pmap);
1763 MPASS(pmap_stage2_invalidate_all != NULL);
1764 pmap_stage2_invalidate_all(pmap_to_ttbr0(pmap));
1767 static __inline void
1768 pmap_invalidate_all(pmap_t pmap)
1770 if (pmap->pm_stage == PM_STAGE1)
1771 pmap_s1_invalidate_all(pmap);
1773 pmap_s2_invalidate_all(pmap);
1777 * Routine: pmap_extract
1779 * Extract the physical page address associated
1780 * with the given map/virtual_address pair.
1783 pmap_extract(pmap_t pmap, vm_offset_t va)
1785 pt_entry_t *pte, tpte;
1792 * Find the block or page map for this virtual address. pmap_pte
1793 * will return either a valid block/page entry, or NULL.
1795 pte = pmap_pte(pmap, va, &lvl);
1797 tpte = pmap_load(pte);
1798 pa = PTE_TO_PHYS(tpte);
1801 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
1802 KASSERT((tpte & ATTR_DESCR_MASK) == L1_BLOCK,
1803 ("pmap_extract: Invalid L1 pte found: %lx",
1804 tpte & ATTR_DESCR_MASK));
1805 pa |= (va & L1_OFFSET);
1808 KASSERT((tpte & ATTR_DESCR_MASK) == L2_BLOCK,
1809 ("pmap_extract: Invalid L2 pte found: %lx",
1810 tpte & ATTR_DESCR_MASK));
1811 pa |= (va & L2_OFFSET);
1814 KASSERT((tpte & ATTR_DESCR_MASK) == L3_PAGE,
1815 ("pmap_extract: Invalid L3 pte found: %lx",
1816 tpte & ATTR_DESCR_MASK));
1817 pa |= (va & L3_OFFSET);
1826 * Routine: pmap_extract_and_hold
1828 * Atomically extract and hold the physical page
1829 * with the given pmap and virtual address pair
1830 * if that mapping permits the given protection.
1833 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1835 pt_entry_t *pte, tpte;
1843 pte = pmap_pte(pmap, va, &lvl);
1845 tpte = pmap_load(pte);
1847 KASSERT(lvl > 0 && lvl <= 3,
1848 ("pmap_extract_and_hold: Invalid level %d", lvl));
1850 * Check that the pte is either a L3 page, or a L1 or L2 block
1851 * entry. We can assume L1_BLOCK == L2_BLOCK.
1853 KASSERT((lvl == 3 && (tpte & ATTR_DESCR_MASK) == L3_PAGE) ||
1854 (lvl < 3 && (tpte & ATTR_DESCR_MASK) == L1_BLOCK),
1855 ("pmap_extract_and_hold: Invalid pte at L%d: %lx", lvl,
1856 tpte & ATTR_DESCR_MASK));
1859 if ((prot & VM_PROT_WRITE) == 0)
1861 else if (pmap->pm_stage == PM_STAGE1 &&
1862 (tpte & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP(ATTR_S1_AP_RW))
1864 else if (pmap->pm_stage == PM_STAGE2 &&
1865 ((tpte & ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE)) ==
1866 ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE)))
1872 off = va & L1_OFFSET;
1875 off = va & L2_OFFSET;
1881 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tpte) | off);
1882 if (m != NULL && !vm_page_wire_mapped(m))
1891 * Walks the page tables to translate a kernel virtual address to a
1892 * physical address. Returns true if the kva is valid and stores the
1893 * physical address in pa if it is not NULL.
1895 * See the comment above data_abort() for the rationale for specifying
1896 * NO_PERTHREAD_SSP here.
1898 bool NO_PERTHREAD_SSP
1899 pmap_klookup(vm_offset_t va, vm_paddr_t *pa)
1901 pt_entry_t *pte, tpte;
1906 * Disable interrupts so we don't get interrupted between asking
1907 * for address translation, and getting the result back.
1909 intr = intr_disable();
1910 par = arm64_address_translate_s1e1r(va);
1913 if (PAR_SUCCESS(par)) {
1915 *pa = (par & PAR_PA_MASK) | (va & PAR_LOW_MASK);
1920 * Fall back to walking the page table. The address translation
1921 * instruction may fail when the page is in a break-before-make
1922 * sequence. As we only clear the valid bit in said sequence we
1923 * can walk the page table to find the physical address.
1926 pte = pmap_l1(kernel_pmap, va);
1931 * A concurrent pmap_update_entry() will clear the entry's valid bit
1932 * but leave the rest of the entry unchanged. Therefore, we treat a
1933 * non-zero entry as being valid, and we ignore the valid bit when
1934 * determining whether the entry maps a block, page, or table.
1936 tpte = pmap_load(pte);
1939 if ((tpte & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
1941 *pa = PTE_TO_PHYS(tpte) | (va & L1_OFFSET);
1944 pte = pmap_l1_to_l2(&tpte, va);
1945 tpte = pmap_load(pte);
1948 if ((tpte & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
1950 *pa = PTE_TO_PHYS(tpte) | (va & L2_OFFSET);
1953 pte = pmap_l2_to_l3(&tpte, va);
1954 tpte = pmap_load(pte);
1958 *pa = PTE_TO_PHYS(tpte) | (va & L3_OFFSET);
1963 pmap_kextract(vm_offset_t va)
1967 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
1968 return (DMAP_TO_PHYS(va));
1970 if (pmap_klookup(va, &pa) == false)
1975 /***************************************************
1976 * Low level mapping routines.....
1977 ***************************************************/
1980 pmap_kenter(vm_offset_t sva, vm_size_t size, vm_paddr_t pa, int mode)
1983 pt_entry_t *pte, attr;
1987 KASSERT((pa & L3_OFFSET) == 0,
1988 ("pmap_kenter: Invalid physical address"));
1989 KASSERT((sva & L3_OFFSET) == 0,
1990 ("pmap_kenter: Invalid virtual address"));
1991 KASSERT((size & PAGE_MASK) == 0,
1992 ("pmap_kenter: Mapping is not page-sized"));
1994 attr = ATTR_DEFAULT | ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_S1_XN |
1995 ATTR_S1_IDX(mode) | L3_PAGE;
1998 pde = pmap_pde(kernel_pmap, va, &lvl);
1999 KASSERT(pde != NULL,
2000 ("pmap_kenter: Invalid page entry, va: 0x%lx", va));
2001 KASSERT(lvl == 2, ("pmap_kenter: Invalid level %d", lvl));
2003 pte = pmap_l2_to_l3(pde, va);
2004 pmap_load_store(pte, PHYS_TO_PTE(pa) | attr);
2010 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
2014 pmap_kenter_device(vm_offset_t sva, vm_size_t size, vm_paddr_t pa)
2017 pmap_kenter(sva, size, pa, VM_MEMATTR_DEVICE);
2021 * Remove a page from the kernel pagetables.
2024 pmap_kremove(vm_offset_t va)
2028 pte = pmap_pte_exists(kernel_pmap, va, 3, __func__);
2030 pmap_s1_invalidate_page(kernel_pmap, va, true);
2034 pmap_kremove_device(vm_offset_t sva, vm_size_t size)
2039 KASSERT((sva & L3_OFFSET) == 0,
2040 ("pmap_kremove_device: Invalid virtual address"));
2041 KASSERT((size & PAGE_MASK) == 0,
2042 ("pmap_kremove_device: Mapping is not page-sized"));
2046 pte = pmap_pte_exists(kernel_pmap, va, 3, __func__);
2052 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
2056 * Used to map a range of physical addresses into kernel
2057 * virtual address space.
2059 * The value passed in '*virt' is a suggested virtual address for
2060 * the mapping. Architectures which can support a direct-mapped
2061 * physical to virtual region can return the appropriate address
2062 * within that region, leaving '*virt' unchanged. Other
2063 * architectures should map the pages starting at '*virt' and
2064 * update '*virt' with the first usable address after the mapped
2068 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2070 return PHYS_TO_DMAP(start);
2074 * Add a list of wired pages to the kva
2075 * this routine is only used for temporary
2076 * kernel mappings that do not need to have
2077 * page modification or references recorded.
2078 * Note that old mappings are simply written
2079 * over. The page *must* be wired.
2080 * Note: SMP coherent. Uses a ranged shootdown IPI.
2083 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2086 pt_entry_t *pte, pa, attr;
2092 for (i = 0; i < count; i++) {
2093 pde = pmap_pde(kernel_pmap, va, &lvl);
2094 KASSERT(pde != NULL,
2095 ("pmap_qenter: Invalid page entry, va: 0x%lx", va));
2097 ("pmap_qenter: Invalid level %d", lvl));
2100 pa = VM_PAGE_TO_PHYS(m);
2101 attr = ATTR_DEFAULT | ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_S1_XN |
2102 ATTR_S1_IDX(m->md.pv_memattr) | L3_PAGE;
2103 pte = pmap_l2_to_l3(pde, va);
2104 pmap_load_store(pte, PHYS_TO_PTE(pa) | attr);
2108 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
2112 * This routine tears out page mappings from the
2113 * kernel -- it is meant only for temporary mappings.
2116 pmap_qremove(vm_offset_t sva, int count)
2121 KASSERT(ADDR_IS_CANONICAL(sva),
2122 ("%s: Address not in canonical form: %lx", __func__, sva));
2123 KASSERT(ADDR_IS_KERNEL(sva), ("usermode va %lx", sva));
2126 while (count-- > 0) {
2127 pte = pmap_pte_exists(kernel_pmap, va, 3, NULL);
2134 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
2137 /***************************************************
2138 * Page table page management routines.....
2139 ***************************************************/
2141 * Schedule the specified unused page table page to be freed. Specifically,
2142 * add the page to the specified list of pages that will be released to the
2143 * physical memory manager after the TLB has been updated.
2145 static __inline void
2146 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2147 boolean_t set_PG_ZERO)
2151 m->flags |= PG_ZERO;
2153 m->flags &= ~PG_ZERO;
2154 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2158 * Decrements a page table page's reference count, which is used to record the
2159 * number of valid page table entries within the page. If the reference count
2160 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2161 * page table page was unmapped and FALSE otherwise.
2163 static inline boolean_t
2164 pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2168 if (m->ref_count == 0) {
2169 _pmap_unwire_l3(pmap, va, m, free);
2176 _pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2179 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2181 * unmap the page table page
2183 if (m->pindex >= (NUL2E + NUL1E)) {
2187 l0 = pmap_l0(pmap, va);
2189 } else if (m->pindex >= NUL2E) {
2193 l1 = pmap_l1(pmap, va);
2199 l2 = pmap_l2(pmap, va);
2202 pmap_resident_count_dec(pmap, 1);
2203 if (m->pindex < NUL2E) {
2204 /* We just released an l3, unhold the matching l2 */
2205 pd_entry_t *l1, tl1;
2208 l1 = pmap_l1(pmap, va);
2209 tl1 = pmap_load(l1);
2210 l2pg = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tl1));
2211 pmap_unwire_l3(pmap, va, l2pg, free);
2212 } else if (m->pindex < (NUL2E + NUL1E)) {
2213 /* We just released an l2, unhold the matching l1 */
2214 pd_entry_t *l0, tl0;
2217 l0 = pmap_l0(pmap, va);
2218 tl0 = pmap_load(l0);
2219 l1pg = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tl0));
2220 pmap_unwire_l3(pmap, va, l1pg, free);
2222 pmap_invalidate_page(pmap, va, false);
2225 * Put page on a list so that it is released after
2226 * *ALL* TLB shootdown is done
2228 pmap_add_delayed_free_list(m, free, TRUE);
2232 * After removing a page table entry, this routine is used to
2233 * conditionally free the page, and manage the reference count.
2236 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2237 struct spglist *free)
2241 KASSERT(ADDR_IS_CANONICAL(va),
2242 ("%s: Address not in canonical form: %lx", __func__, va));
2243 if (ADDR_IS_KERNEL(va))
2245 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2246 mpte = PHYS_TO_VM_PAGE(PTE_TO_PHYS(ptepde));
2247 return (pmap_unwire_l3(pmap, va, mpte, free));
2251 * Release a page table page reference after a failed attempt to create a
2255 pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
2257 struct spglist free;
2260 if (pmap_unwire_l3(pmap, va, mpte, &free))
2261 vm_page_free_pages_toq(&free, true);
2265 pmap_pinit0(pmap_t pmap)
2268 PMAP_LOCK_INIT(pmap);
2269 bzero(&pmap->pm_stats, sizeof(pmap->pm_stats));
2270 pmap->pm_l0_paddr = READ_SPECIALREG(ttbr0_el1);
2271 pmap->pm_l0 = (pd_entry_t *)PHYS_TO_DMAP(pmap->pm_l0_paddr);
2272 vm_radix_init(&pmap->pm_root);
2273 pmap->pm_cookie = COOKIE_FROM(ASID_RESERVED_FOR_PID_0, INT_MIN);
2274 pmap->pm_stage = PM_STAGE1;
2275 pmap->pm_levels = 4;
2276 pmap->pm_ttbr = pmap->pm_l0_paddr;
2277 pmap->pm_asid_set = &asids;
2279 PCPU_SET(curpmap, pmap);
2283 pmap_pinit_stage(pmap_t pmap, enum pmap_stage stage, int levels)
2288 * allocate the l0 page
2290 m = vm_page_alloc_noobj(VM_ALLOC_WAITOK | VM_ALLOC_WIRED |
2292 pmap->pm_l0_paddr = VM_PAGE_TO_PHYS(m);
2293 pmap->pm_l0 = (pd_entry_t *)PHYS_TO_DMAP(pmap->pm_l0_paddr);
2295 vm_radix_init(&pmap->pm_root);
2296 bzero(&pmap->pm_stats, sizeof(pmap->pm_stats));
2297 pmap->pm_cookie = COOKIE_FROM(-1, INT_MAX);
2299 MPASS(levels == 3 || levels == 4);
2300 pmap->pm_levels = levels;
2301 pmap->pm_stage = stage;
2304 pmap->pm_asid_set = &asids;
2307 pmap->pm_asid_set = &vmids;
2310 panic("%s: Invalid pmap type %d", __func__, stage);
2314 /* XXX Temporarily disable deferred ASID allocation. */
2315 pmap_alloc_asid(pmap);
2318 * Allocate the level 1 entry to use as the root. This will increase
2319 * the refcount on the level 1 page so it won't be removed until
2320 * pmap_release() is called.
2322 if (pmap->pm_levels == 3) {
2324 m = _pmap_alloc_l3(pmap, NUL2E + NUL1E, NULL);
2327 pmap->pm_ttbr = VM_PAGE_TO_PHYS(m);
2333 pmap_pinit(pmap_t pmap)
2336 return (pmap_pinit_stage(pmap, PM_STAGE1, 4));
2340 * This routine is called if the desired page table page does not exist.
2342 * If page table page allocation fails, this routine may sleep before
2343 * returning NULL. It sleeps only if a lock pointer was given.
2345 * Note: If a page allocation fails at page table level two or three,
2346 * one or two pages may be held during the wait, only to be released
2347 * afterwards. This conservative approach is easily argued to avoid
2351 _pmap_alloc_l3(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2353 vm_page_t m, l1pg, l2pg;
2355 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2358 * Allocate a page table page.
2360 if ((m = vm_page_alloc_noobj(VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2361 if (lockp != NULL) {
2362 RELEASE_PV_LIST_LOCK(lockp);
2369 * Indicate the need to retry. While waiting, the page table
2370 * page may have been allocated.
2374 m->pindex = ptepindex;
2377 * Because of AArch64's weak memory consistency model, we must have a
2378 * barrier here to ensure that the stores for zeroing "m", whether by
2379 * pmap_zero_page() or an earlier function, are visible before adding
2380 * "m" to the page table. Otherwise, a page table walk by another
2381 * processor's MMU could see the mapping to "m" and a stale, non-zero
2387 * Map the pagetable page into the process address space, if
2388 * it isn't already there.
2391 if (ptepindex >= (NUL2E + NUL1E)) {
2392 pd_entry_t *l0p, l0e;
2393 vm_pindex_t l0index;
2395 l0index = ptepindex - (NUL2E + NUL1E);
2396 l0p = &pmap->pm_l0[l0index];
2397 KASSERT((pmap_load(l0p) & ATTR_DESCR_VALID) == 0,
2398 ("%s: L0 entry %#lx is valid", __func__, pmap_load(l0p)));
2399 l0e = PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) | L0_TABLE;
2402 * Mark all kernel memory as not accessible from userspace
2403 * and userspace memory as not executable from the kernel.
2404 * This has been done for the bootstrap L0 entries in
2407 if (pmap == kernel_pmap)
2408 l0e |= TATTR_UXN_TABLE | TATTR_AP_TABLE_NO_EL0;
2410 l0e |= TATTR_PXN_TABLE;
2411 pmap_store(l0p, l0e);
2412 } else if (ptepindex >= NUL2E) {
2413 vm_pindex_t l0index, l1index;
2414 pd_entry_t *l0, *l1;
2417 l1index = ptepindex - NUL2E;
2418 l0index = l1index >> Ln_ENTRIES_SHIFT;
2420 l0 = &pmap->pm_l0[l0index];
2421 tl0 = pmap_load(l0);
2423 /* recurse for allocating page dir */
2424 if (_pmap_alloc_l3(pmap, NUL2E + NUL1E + l0index,
2426 vm_page_unwire_noq(m);
2427 vm_page_free_zero(m);
2431 l1pg = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tl0));
2435 l1 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(pmap_load(l0)));
2436 l1 = &l1[ptepindex & Ln_ADDR_MASK];
2437 KASSERT((pmap_load(l1) & ATTR_DESCR_VALID) == 0,
2438 ("%s: L1 entry %#lx is valid", __func__, pmap_load(l1)));
2439 pmap_store(l1, PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) | L1_TABLE);
2441 vm_pindex_t l0index, l1index;
2442 pd_entry_t *l0, *l1, *l2;
2443 pd_entry_t tl0, tl1;
2445 l1index = ptepindex >> Ln_ENTRIES_SHIFT;
2446 l0index = l1index >> Ln_ENTRIES_SHIFT;
2448 l0 = &pmap->pm_l0[l0index];
2449 tl0 = pmap_load(l0);
2451 /* recurse for allocating page dir */
2452 if (_pmap_alloc_l3(pmap, NUL2E + l1index,
2454 vm_page_unwire_noq(m);
2455 vm_page_free_zero(m);
2458 tl0 = pmap_load(l0);
2459 l1 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(tl0));
2460 l1 = &l1[l1index & Ln_ADDR_MASK];
2462 l1 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(tl0));
2463 l1 = &l1[l1index & Ln_ADDR_MASK];
2464 tl1 = pmap_load(l1);
2466 /* recurse for allocating page dir */
2467 if (_pmap_alloc_l3(pmap, NUL2E + l1index,
2469 vm_page_unwire_noq(m);
2470 vm_page_free_zero(m);
2474 l2pg = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tl1));
2479 l2 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(pmap_load(l1)));
2480 l2 = &l2[ptepindex & Ln_ADDR_MASK];
2481 KASSERT((pmap_load(l2) & ATTR_DESCR_VALID) == 0,
2482 ("%s: L2 entry %#lx is valid", __func__, pmap_load(l2)));
2483 pmap_store(l2, PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) | L2_TABLE);
2486 pmap_resident_count_inc(pmap, 1);
2492 pmap_alloc_l2(pmap_t pmap, vm_offset_t va, vm_page_t *l2pgp,
2493 struct rwlock **lockp)
2495 pd_entry_t *l1, *l2;
2497 vm_pindex_t l2pindex;
2499 KASSERT(ADDR_IS_CANONICAL(va),
2500 ("%s: Address not in canonical form: %lx", __func__, va));
2503 l1 = pmap_l1(pmap, va);
2504 if (l1 != NULL && (pmap_load(l1) & ATTR_DESCR_MASK) == L1_TABLE) {
2505 l2 = pmap_l1_to_l2(l1, va);
2506 if (!ADDR_IS_KERNEL(va)) {
2507 /* Add a reference to the L2 page. */
2508 l2pg = PHYS_TO_VM_PAGE(PTE_TO_PHYS(pmap_load(l1)));
2512 } else if (!ADDR_IS_KERNEL(va)) {
2513 /* Allocate a L2 page. */
2514 l2pindex = pmap_l2_pindex(va) >> Ln_ENTRIES_SHIFT;
2515 l2pg = _pmap_alloc_l3(pmap, NUL2E + l2pindex, lockp);
2522 l2 = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(l2pg));
2523 l2 = &l2[pmap_l2_index(va)];
2525 panic("pmap_alloc_l2: missing page table page for va %#lx",
2532 pmap_alloc_l3(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2534 vm_pindex_t ptepindex;
2535 pd_entry_t *pde, tpde;
2543 * Calculate pagetable page index
2545 ptepindex = pmap_l2_pindex(va);
2548 * Get the page directory entry
2550 pde = pmap_pde(pmap, va, &lvl);
2553 * If the page table page is mapped, we just increment the hold count,
2554 * and activate it. If we get a level 2 pde it will point to a level 3
2562 pte = pmap_l0_to_l1(pde, va);
2563 KASSERT(pmap_load(pte) == 0,
2564 ("pmap_alloc_l3: TODO: l0 superpages"));
2569 pte = pmap_l1_to_l2(pde, va);
2570 KASSERT(pmap_load(pte) == 0,
2571 ("pmap_alloc_l3: TODO: l1 superpages"));
2575 tpde = pmap_load(pde);
2577 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tpde));
2583 panic("pmap_alloc_l3: Invalid level %d", lvl);
2587 * Here if the pte page isn't mapped, or if it has been deallocated.
2589 m = _pmap_alloc_l3(pmap, ptepindex, lockp);
2590 if (m == NULL && lockp != NULL)
2596 /***************************************************
2597 * Pmap allocation/deallocation routines.
2598 ***************************************************/
2601 * Release any resources held by the given physical map.
2602 * Called when a pmap initialized by pmap_pinit is being released.
2603 * Should only be called if the map contains no valid mappings.
2606 pmap_release(pmap_t pmap)
2608 boolean_t rv __diagused;
2609 struct spglist free;
2610 struct asid_set *set;
2614 if (pmap->pm_levels != 4) {
2615 PMAP_ASSERT_STAGE2(pmap);
2616 KASSERT(pmap->pm_stats.resident_count == 1,
2617 ("pmap_release: pmap resident count %ld != 0",
2618 pmap->pm_stats.resident_count));
2619 KASSERT((pmap->pm_l0[0] & ATTR_DESCR_VALID) == ATTR_DESCR_VALID,
2620 ("pmap_release: Invalid l0 entry: %lx", pmap->pm_l0[0]));
2623 m = PHYS_TO_VM_PAGE(pmap->pm_ttbr);
2625 rv = pmap_unwire_l3(pmap, 0, m, &free);
2628 vm_page_free_pages_toq(&free, true);
2631 KASSERT(pmap->pm_stats.resident_count == 0,
2632 ("pmap_release: pmap resident count %ld != 0",
2633 pmap->pm_stats.resident_count));
2634 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2635 ("pmap_release: pmap has reserved page table page(s)"));
2637 set = pmap->pm_asid_set;
2638 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
2641 * Allow the ASID to be reused. In stage 2 VMIDs we don't invalidate
2642 * the entries when removing them so rely on a later tlb invalidation.
2643 * this will happen when updating the VMID generation. Because of this
2644 * we don't reuse VMIDs within a generation.
2646 if (pmap->pm_stage == PM_STAGE1) {
2647 mtx_lock_spin(&set->asid_set_mutex);
2648 if (COOKIE_TO_EPOCH(pmap->pm_cookie) == set->asid_epoch) {
2649 asid = COOKIE_TO_ASID(pmap->pm_cookie);
2650 KASSERT(asid >= ASID_FIRST_AVAILABLE &&
2651 asid < set->asid_set_size,
2652 ("pmap_release: pmap cookie has out-of-range asid"));
2653 bit_clear(set->asid_set, asid);
2655 mtx_unlock_spin(&set->asid_set_mutex);
2658 m = PHYS_TO_VM_PAGE(pmap->pm_l0_paddr);
2659 vm_page_unwire_noq(m);
2660 vm_page_free_zero(m);
2664 kvm_size(SYSCTL_HANDLER_ARGS)
2666 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2668 return sysctl_handle_long(oidp, &ksize, 0, req);
2670 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
2671 0, 0, kvm_size, "LU",
2675 kvm_free(SYSCTL_HANDLER_ARGS)
2677 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2679 return sysctl_handle_long(oidp, &kfree, 0, req);
2681 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
2682 0, 0, kvm_free, "LU",
2683 "Amount of KVM free");
2686 * grow the number of kernel page table entries, if needed
2689 pmap_growkernel(vm_offset_t addr)
2693 pd_entry_t *l0, *l1, *l2;
2695 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2697 addr = roundup2(addr, L2_SIZE);
2698 if (addr - 1 >= vm_map_max(kernel_map))
2699 addr = vm_map_max(kernel_map);
2700 if (kernel_vm_end < addr)
2701 kasan_shadow_map(kernel_vm_end, addr - kernel_vm_end);
2702 while (kernel_vm_end < addr) {
2703 l0 = pmap_l0(kernel_pmap, kernel_vm_end);
2704 KASSERT(pmap_load(l0) != 0,
2705 ("pmap_growkernel: No level 0 kernel entry"));
2707 l1 = pmap_l0_to_l1(l0, kernel_vm_end);
2708 if (pmap_load(l1) == 0) {
2709 /* We need a new PDP entry */
2710 nkpg = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT |
2711 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2713 panic("pmap_growkernel: no memory to grow kernel");
2714 nkpg->pindex = kernel_vm_end >> L1_SHIFT;
2715 /* See the dmb() in _pmap_alloc_l3(). */
2717 paddr = VM_PAGE_TO_PHYS(nkpg);
2718 pmap_store(l1, PHYS_TO_PTE(paddr) | L1_TABLE);
2719 continue; /* try again */
2721 l2 = pmap_l1_to_l2(l1, kernel_vm_end);
2722 if (pmap_load(l2) != 0) {
2723 kernel_vm_end = (kernel_vm_end + L2_SIZE) & ~L2_OFFSET;
2724 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
2725 kernel_vm_end = vm_map_max(kernel_map);
2731 nkpg = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED |
2734 panic("pmap_growkernel: no memory to grow kernel");
2735 nkpg->pindex = kernel_vm_end >> L2_SHIFT;
2736 /* See the dmb() in _pmap_alloc_l3(). */
2738 paddr = VM_PAGE_TO_PHYS(nkpg);
2739 pmap_store(l2, PHYS_TO_PTE(paddr) | L2_TABLE);
2741 kernel_vm_end = (kernel_vm_end + L2_SIZE) & ~L2_OFFSET;
2742 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
2743 kernel_vm_end = vm_map_max(kernel_map);
2749 /***************************************************
2750 * page management routines.
2751 ***************************************************/
2753 static const uint64_t pc_freemask[_NPCM] = {
2754 [0 ... _NPCM - 2] = PC_FREEN,
2755 [_NPCM - 1] = PC_FREEL
2759 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2761 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2762 "Current number of pv entry chunks");
2763 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2764 "Current number of pv entry chunks allocated");
2765 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2766 "Current number of pv entry chunks frees");
2767 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
2768 "Number of times tried to get a chunk page but failed.");
2770 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
2771 static int pv_entry_spare;
2773 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2774 "Current number of pv entry frees");
2775 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
2776 "Current number of pv entry allocs");
2777 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2778 "Current number of pv entries");
2779 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2780 "Current number of spare pv entries");
2784 * We are in a serious low memory condition. Resort to
2785 * drastic measures to free some pages so we can allocate
2786 * another pv entry chunk.
2788 * Returns NULL if PV entries were reclaimed from the specified pmap.
2790 * We do not, however, unmap 2mpages because subsequent accesses will
2791 * allocate per-page pv entries until repromotion occurs, thereby
2792 * exacerbating the shortage of free pv entries.
2795 reclaim_pv_chunk_domain(pmap_t locked_pmap, struct rwlock **lockp, int domain)
2797 struct pv_chunks_list *pvc;
2798 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
2799 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
2800 struct md_page *pvh;
2802 pmap_t next_pmap, pmap;
2803 pt_entry_t *pte, tpte;
2807 struct spglist free;
2809 int bit, field, freed, lvl;
2811 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2812 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
2817 bzero(&pc_marker_b, sizeof(pc_marker_b));
2818 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
2819 pc_marker = (struct pv_chunk *)&pc_marker_b;
2820 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
2822 pvc = &pv_chunks[domain];
2823 mtx_lock(&pvc->pvc_lock);
2824 pvc->active_reclaims++;
2825 TAILQ_INSERT_HEAD(&pvc->pvc_list, pc_marker, pc_lru);
2826 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc_marker_end, pc_lru);
2827 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
2828 SLIST_EMPTY(&free)) {
2829 next_pmap = pc->pc_pmap;
2830 if (next_pmap == NULL) {
2832 * The next chunk is a marker. However, it is
2833 * not our marker, so active_reclaims must be
2834 * > 1. Consequently, the next_chunk code
2835 * will not rotate the pv_chunks list.
2839 mtx_unlock(&pvc->pvc_lock);
2842 * A pv_chunk can only be removed from the pc_lru list
2843 * when both pvc->pvc_lock is owned and the
2844 * corresponding pmap is locked.
2846 if (pmap != next_pmap) {
2847 if (pmap != NULL && pmap != locked_pmap)
2850 /* Avoid deadlock and lock recursion. */
2851 if (pmap > locked_pmap) {
2852 RELEASE_PV_LIST_LOCK(lockp);
2854 mtx_lock(&pvc->pvc_lock);
2856 } else if (pmap != locked_pmap) {
2857 if (PMAP_TRYLOCK(pmap)) {
2858 mtx_lock(&pvc->pvc_lock);
2861 pmap = NULL; /* pmap is not locked */
2862 mtx_lock(&pvc->pvc_lock);
2863 pc = TAILQ_NEXT(pc_marker, pc_lru);
2865 pc->pc_pmap != next_pmap)
2873 * Destroy every non-wired, 4 KB page mapping in the chunk.
2876 for (field = 0; field < _NPCM; field++) {
2877 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2878 inuse != 0; inuse &= ~(1UL << bit)) {
2879 bit = ffsl(inuse) - 1;
2880 pv = &pc->pc_pventry[field * 64 + bit];
2882 pde = pmap_pde(pmap, va, &lvl);
2885 pte = pmap_l2_to_l3(pde, va);
2886 tpte = pmap_load(pte);
2887 if ((tpte & ATTR_SW_WIRED) != 0)
2889 tpte = pmap_load_clear(pte);
2890 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tpte));
2891 if (pmap_pte_dirty(pmap, tpte))
2893 if ((tpte & ATTR_AF) != 0) {
2894 pmap_s1_invalidate_page(pmap, va, true);
2895 vm_page_aflag_set(m, PGA_REFERENCED);
2897 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
2898 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
2900 if (TAILQ_EMPTY(&m->md.pv_list) &&
2901 (m->flags & PG_FICTITIOUS) == 0) {
2902 pvh = page_to_pvh(m);
2903 if (TAILQ_EMPTY(&pvh->pv_list)) {
2904 vm_page_aflag_clear(m,
2908 pc->pc_map[field] |= 1UL << bit;
2909 pmap_unuse_pt(pmap, va, pmap_load(pde), &free);
2914 mtx_lock(&pvc->pvc_lock);
2917 /* Every freed mapping is for a 4 KB page. */
2918 pmap_resident_count_dec(pmap, freed);
2919 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
2920 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
2921 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
2922 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2923 if (pc_is_free(pc)) {
2924 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
2925 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
2926 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
2927 /* Entire chunk is free; return it. */
2928 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
2929 dump_drop_page(m_pc->phys_addr);
2930 mtx_lock(&pvc->pvc_lock);
2931 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
2934 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2935 mtx_lock(&pvc->pvc_lock);
2936 /* One freed pv entry in locked_pmap is sufficient. */
2937 if (pmap == locked_pmap)
2941 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
2942 TAILQ_INSERT_AFTER(&pvc->pvc_list, pc, pc_marker, pc_lru);
2943 if (pvc->active_reclaims == 1 && pmap != NULL) {
2945 * Rotate the pv chunks list so that we do not
2946 * scan the same pv chunks that could not be
2947 * freed (because they contained a wired
2948 * and/or superpage mapping) on every
2949 * invocation of reclaim_pv_chunk().
2951 while ((pc = TAILQ_FIRST(&pvc->pvc_list)) != pc_marker){
2952 MPASS(pc->pc_pmap != NULL);
2953 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
2954 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
2958 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
2959 TAILQ_REMOVE(&pvc->pvc_list, pc_marker_end, pc_lru);
2960 pvc->active_reclaims--;
2961 mtx_unlock(&pvc->pvc_lock);
2962 if (pmap != NULL && pmap != locked_pmap)
2964 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
2965 m_pc = SLIST_FIRST(&free);
2966 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2967 /* Recycle a freed page table page. */
2968 m_pc->ref_count = 1;
2970 vm_page_free_pages_toq(&free, true);
2975 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
2980 domain = PCPU_GET(domain);
2981 for (i = 0; i < vm_ndomains; i++) {
2982 m = reclaim_pv_chunk_domain(locked_pmap, lockp, domain);
2985 domain = (domain + 1) % vm_ndomains;
2992 * free the pv_entry back to the free list
2995 free_pv_entry(pmap_t pmap, pv_entry_t pv)
2997 struct pv_chunk *pc;
2998 int idx, field, bit;
3000 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3001 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3002 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3003 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3004 pc = pv_to_chunk(pv);
3005 idx = pv - &pc->pc_pventry[0];
3008 pc->pc_map[field] |= 1ul << bit;
3009 if (!pc_is_free(pc)) {
3010 /* 98% of the time, pc is already at the head of the list. */
3011 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3012 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3013 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3017 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3022 free_pv_chunk_dequeued(struct pv_chunk *pc)
3026 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3027 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3028 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3029 /* entire chunk is free, return it */
3030 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3031 dump_drop_page(m->phys_addr);
3032 vm_page_unwire_noq(m);
3037 free_pv_chunk(struct pv_chunk *pc)
3039 struct pv_chunks_list *pvc;
3041 pvc = &pv_chunks[pc_to_domain(pc)];
3042 mtx_lock(&pvc->pvc_lock);
3043 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
3044 mtx_unlock(&pvc->pvc_lock);
3045 free_pv_chunk_dequeued(pc);
3049 free_pv_chunk_batch(struct pv_chunklist *batch)
3051 struct pv_chunks_list *pvc;
3052 struct pv_chunk *pc, *npc;
3055 for (i = 0; i < vm_ndomains; i++) {
3056 if (TAILQ_EMPTY(&batch[i]))
3058 pvc = &pv_chunks[i];
3059 mtx_lock(&pvc->pvc_lock);
3060 TAILQ_FOREACH(pc, &batch[i], pc_list) {
3061 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
3063 mtx_unlock(&pvc->pvc_lock);
3066 for (i = 0; i < vm_ndomains; i++) {
3067 TAILQ_FOREACH_SAFE(pc, &batch[i], pc_list, npc) {
3068 free_pv_chunk_dequeued(pc);
3074 * Returns a new PV entry, allocating a new PV chunk from the system when
3075 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3076 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3079 * The given PV list lock may be released.
3082 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3084 struct pv_chunks_list *pvc;
3087 struct pv_chunk *pc;
3090 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3091 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3093 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3095 for (field = 0; field < _NPCM; field++) {
3096 if (pc->pc_map[field]) {
3097 bit = ffsl(pc->pc_map[field]) - 1;
3101 if (field < _NPCM) {
3102 pv = &pc->pc_pventry[field * 64 + bit];
3103 pc->pc_map[field] &= ~(1ul << bit);
3104 /* If this was the last item, move it to tail */
3105 if (pc_is_full(pc)) {
3106 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3107 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3110 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3111 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3115 /* No free items, allocate another chunk */
3116 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
3118 if (lockp == NULL) {
3119 PV_STAT(pc_chunk_tryfail++);
3122 m = reclaim_pv_chunk(pmap, lockp);
3126 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3127 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3128 dump_add_page(m->phys_addr);
3129 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3131 memcpy(pc->pc_map, pc_freemask, sizeof(pc_freemask));
3132 pc->pc_map[0] &= ~1ul; /* preallocated bit 0 */
3133 pvc = &pv_chunks[vm_page_domain(m)];
3134 mtx_lock(&pvc->pvc_lock);
3135 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
3136 mtx_unlock(&pvc->pvc_lock);
3137 pv = &pc->pc_pventry[0];
3138 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3139 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3140 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3145 * Ensure that the number of spare PV entries in the specified pmap meets or
3146 * exceeds the given count, "needed".
3148 * The given PV list lock may be released.
3151 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3153 struct pv_chunks_list *pvc;
3154 struct pch new_tail[PMAP_MEMDOM];
3155 struct pv_chunk *pc;
3160 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3161 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3164 * Newly allocated PV chunks must be stored in a private list until
3165 * the required number of PV chunks have been allocated. Otherwise,
3166 * reclaim_pv_chunk() could recycle one of these chunks. In
3167 * contrast, these chunks must be added to the pmap upon allocation.
3169 for (i = 0; i < PMAP_MEMDOM; i++)
3170 TAILQ_INIT(&new_tail[i]);
3173 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3174 bit_count((bitstr_t *)pc->pc_map, 0,
3175 sizeof(pc->pc_map) * NBBY, &free);
3179 if (avail >= needed)
3182 for (reclaimed = false; avail < needed; avail += _NPCPV) {
3183 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
3185 m = reclaim_pv_chunk(pmap, lockp);
3190 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3191 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3192 dump_add_page(m->phys_addr);
3193 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3195 memcpy(pc->pc_map, pc_freemask, sizeof(pc_freemask));
3196 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3197 TAILQ_INSERT_TAIL(&new_tail[vm_page_domain(m)], pc, pc_lru);
3198 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3201 * The reclaim might have freed a chunk from the current pmap.
3202 * If that chunk contained available entries, we need to
3203 * re-count the number of available entries.
3208 for (i = 0; i < vm_ndomains; i++) {
3209 if (TAILQ_EMPTY(&new_tail[i]))
3211 pvc = &pv_chunks[i];
3212 mtx_lock(&pvc->pvc_lock);
3213 TAILQ_CONCAT(&pvc->pvc_list, &new_tail[i], pc_lru);
3214 mtx_unlock(&pvc->pvc_lock);
3219 * First find and then remove the pv entry for the specified pmap and virtual
3220 * address from the specified pv list. Returns the pv entry if found and NULL
3221 * otherwise. This operation can be performed on pv lists for either 4KB or
3222 * 2MB page mappings.
3224 static __inline pv_entry_t
3225 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3229 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3230 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3231 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3240 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3241 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3242 * entries for each of the 4KB page mappings.
3245 pmap_pv_demote_l2(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3246 struct rwlock **lockp)
3248 struct md_page *pvh;
3249 struct pv_chunk *pc;
3251 vm_offset_t va_last;
3255 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3256 KASSERT((va & L2_OFFSET) == 0,
3257 ("pmap_pv_demote_l2: va is not 2mpage aligned"));
3258 KASSERT((pa & L2_OFFSET) == 0,
3259 ("pmap_pv_demote_l2: pa is not 2mpage aligned"));
3260 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3263 * Transfer the 2mpage's pv entry for this mapping to the first
3264 * page's pv list. Once this transfer begins, the pv list lock
3265 * must not be released until the last pv entry is reinstantiated.
3267 pvh = pa_to_pvh(pa);
3268 pv = pmap_pvh_remove(pvh, pmap, va);
3269 KASSERT(pv != NULL, ("pmap_pv_demote_l2: pv not found"));
3270 m = PHYS_TO_VM_PAGE(pa);
3271 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3273 /* Instantiate the remaining Ln_ENTRIES - 1 pv entries. */
3274 PV_STAT(atomic_add_long(&pv_entry_allocs, Ln_ENTRIES - 1));
3275 va_last = va + L2_SIZE - PAGE_SIZE;
3277 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3278 KASSERT(!pc_is_full(pc), ("pmap_pv_demote_l2: missing spare"));
3279 for (field = 0; field < _NPCM; field++) {
3280 while (pc->pc_map[field]) {
3281 bit = ffsl(pc->pc_map[field]) - 1;
3282 pc->pc_map[field] &= ~(1ul << bit);
3283 pv = &pc->pc_pventry[field * 64 + bit];
3287 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3288 ("pmap_pv_demote_l2: page %p is not managed", m));
3289 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3295 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3296 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3299 if (pc_is_full(pc)) {
3300 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3301 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3303 PV_STAT(atomic_add_long(&pv_entry_count, Ln_ENTRIES - 1));
3304 PV_STAT(atomic_subtract_int(&pv_entry_spare, Ln_ENTRIES - 1));
3308 * First find and then destroy the pv entry for the specified pmap and virtual
3309 * address. This operation can be performed on pv lists for either 4KB or 2MB
3313 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3317 pv = pmap_pvh_remove(pvh, pmap, va);
3318 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3319 free_pv_entry(pmap, pv);
3323 * Conditionally create the PV entry for a 4KB page mapping if the required
3324 * memory can be allocated without resorting to reclamation.
3327 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3328 struct rwlock **lockp)
3332 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3333 /* Pass NULL instead of the lock pointer to disable reclamation. */
3334 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3336 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3337 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3345 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3346 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3347 * false if the PV entry cannot be allocated without resorting to reclamation.
3350 pmap_pv_insert_l2(pmap_t pmap, vm_offset_t va, pd_entry_t l2e, u_int flags,
3351 struct rwlock **lockp)
3353 struct md_page *pvh;
3357 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3358 /* Pass NULL instead of the lock pointer to disable reclamation. */
3359 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3360 NULL : lockp)) == NULL)
3363 pa = PTE_TO_PHYS(l2e);
3364 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3365 pvh = pa_to_pvh(pa);
3366 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3372 pmap_remove_kernel_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va)
3374 pt_entry_t newl2, oldl2 __diagused;
3378 KASSERT(!VIRT_IN_DMAP(va), ("removing direct mapping of %#lx", va));
3379 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3380 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3382 ml3 = pmap_remove_pt_page(pmap, va);
3384 panic("pmap_remove_kernel_l2: Missing pt page");
3386 ml3pa = VM_PAGE_TO_PHYS(ml3);
3387 newl2 = PHYS_TO_PTE(ml3pa) | L2_TABLE;
3390 * If this page table page was unmapped by a promotion, then it
3391 * contains valid mappings. Zero it to invalidate those mappings.
3393 if (vm_page_any_valid(ml3))
3394 pagezero((void *)PHYS_TO_DMAP(ml3pa));
3397 * Demote the mapping. The caller must have already invalidated the
3398 * mapping (i.e., the "break" in break-before-make).
3400 oldl2 = pmap_load_store(l2, newl2);
3401 KASSERT(oldl2 == 0, ("%s: found existing mapping at %p: %#lx",
3402 __func__, l2, oldl2));
3406 * pmap_remove_l2: Do the things to unmap a level 2 superpage.
3409 pmap_remove_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva,
3410 pd_entry_t l1e, struct spglist *free, struct rwlock **lockp)
3412 struct md_page *pvh;
3414 vm_page_t m, ml3, mt;
3416 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3417 KASSERT((sva & L2_OFFSET) == 0, ("pmap_remove_l2: sva is not aligned"));
3418 old_l2 = pmap_load_clear(l2);
3419 KASSERT((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK,
3420 ("pmap_remove_l2: L2e %lx is not a block mapping", old_l2));
3423 * Since a promotion must break the 4KB page mappings before making
3424 * the 2MB page mapping, a pmap_s1_invalidate_page() suffices.
3426 pmap_s1_invalidate_page(pmap, sva, true);
3428 if (old_l2 & ATTR_SW_WIRED)
3429 pmap->pm_stats.wired_count -= L2_SIZE / PAGE_SIZE;
3430 pmap_resident_count_dec(pmap, L2_SIZE / PAGE_SIZE);
3431 if (old_l2 & ATTR_SW_MANAGED) {
3432 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(old_l2));
3433 pvh = page_to_pvh(m);
3434 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3435 pmap_pvh_free(pvh, pmap, sva);
3436 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++) {
3437 if (pmap_pte_dirty(pmap, old_l2))
3439 if (old_l2 & ATTR_AF)
3440 vm_page_aflag_set(mt, PGA_REFERENCED);
3441 if (TAILQ_EMPTY(&mt->md.pv_list) &&
3442 TAILQ_EMPTY(&pvh->pv_list))
3443 vm_page_aflag_clear(mt, PGA_WRITEABLE);
3446 if (pmap == kernel_pmap) {
3447 pmap_remove_kernel_l2(pmap, l2, sva);
3449 ml3 = pmap_remove_pt_page(pmap, sva);
3451 KASSERT(vm_page_any_valid(ml3),
3452 ("pmap_remove_l2: l3 page not promoted"));
3453 pmap_resident_count_dec(pmap, 1);
3454 KASSERT(ml3->ref_count == NL3PG,
3455 ("pmap_remove_l2: l3 page ref count error"));
3457 pmap_add_delayed_free_list(ml3, free, FALSE);
3460 return (pmap_unuse_pt(pmap, sva, l1e, free));
3464 * pmap_remove_l3: do the things to unmap a page in a process
3467 pmap_remove_l3(pmap_t pmap, pt_entry_t *l3, vm_offset_t va,
3468 pd_entry_t l2e, struct spglist *free, struct rwlock **lockp)
3470 struct md_page *pvh;
3474 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3475 old_l3 = pmap_load_clear(l3);
3476 pmap_s1_invalidate_page(pmap, va, true);
3477 if (old_l3 & ATTR_SW_WIRED)
3478 pmap->pm_stats.wired_count -= 1;
3479 pmap_resident_count_dec(pmap, 1);
3480 if (old_l3 & ATTR_SW_MANAGED) {
3481 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(old_l3));
3482 if (pmap_pte_dirty(pmap, old_l3))
3484 if (old_l3 & ATTR_AF)
3485 vm_page_aflag_set(m, PGA_REFERENCED);
3486 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3487 pmap_pvh_free(&m->md, pmap, va);
3488 if (TAILQ_EMPTY(&m->md.pv_list) &&
3489 (m->flags & PG_FICTITIOUS) == 0) {
3490 pvh = page_to_pvh(m);
3491 if (TAILQ_EMPTY(&pvh->pv_list))
3492 vm_page_aflag_clear(m, PGA_WRITEABLE);
3495 return (pmap_unuse_pt(pmap, va, l2e, free));
3499 * Remove the specified range of addresses from the L3 page table that is
3500 * identified by the given L2 entry.
3503 pmap_remove_l3_range(pmap_t pmap, pd_entry_t l2e, vm_offset_t sva,
3504 vm_offset_t eva, struct spglist *free, struct rwlock **lockp)
3506 struct md_page *pvh;
3507 struct rwlock *new_lock;
3508 pt_entry_t *l3, old_l3;
3512 KASSERT(ADDR_IS_CANONICAL(sva),
3513 ("%s: Start address not in canonical form: %lx", __func__, sva));
3514 KASSERT(ADDR_IS_CANONICAL(eva) || eva == VM_MAX_USER_ADDRESS,
3515 ("%s: End address not in canonical form: %lx", __func__, eva));
3517 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3518 KASSERT(rounddown2(sva, L2_SIZE) + L2_SIZE == roundup2(eva, L2_SIZE),
3519 ("pmap_remove_l3_range: range crosses an L3 page table boundary"));
3520 l3pg = !ADDR_IS_KERNEL(sva) ? PHYS_TO_VM_PAGE(PTE_TO_PHYS(l2e)) : NULL;
3522 for (l3 = pmap_l2_to_l3(&l2e, sva); sva != eva; l3++, sva += L3_SIZE) {
3523 if (!pmap_l3_valid(pmap_load(l3))) {
3525 pmap_invalidate_range(pmap, va, sva, true);
3530 old_l3 = pmap_load_clear(l3);
3531 if ((old_l3 & ATTR_SW_WIRED) != 0)
3532 pmap->pm_stats.wired_count--;
3533 pmap_resident_count_dec(pmap, 1);
3534 if ((old_l3 & ATTR_SW_MANAGED) != 0) {
3535 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(old_l3));
3536 if (pmap_pte_dirty(pmap, old_l3))
3538 if ((old_l3 & ATTR_AF) != 0)
3539 vm_page_aflag_set(m, PGA_REFERENCED);
3540 new_lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3541 if (new_lock != *lockp) {
3542 if (*lockp != NULL) {
3544 * Pending TLB invalidations must be
3545 * performed before the PV list lock is
3546 * released. Otherwise, a concurrent
3547 * pmap_remove_all() on a physical page
3548 * could return while a stale TLB entry
3549 * still provides access to that page.
3552 pmap_invalidate_range(pmap, va,
3561 pmap_pvh_free(&m->md, pmap, sva);
3562 if (TAILQ_EMPTY(&m->md.pv_list) &&
3563 (m->flags & PG_FICTITIOUS) == 0) {
3564 pvh = page_to_pvh(m);
3565 if (TAILQ_EMPTY(&pvh->pv_list))
3566 vm_page_aflag_clear(m, PGA_WRITEABLE);
3569 if (l3pg != NULL && pmap_unwire_l3(pmap, sva, l3pg, free)) {
3571 * _pmap_unwire_l3() has already invalidated the TLB
3572 * entries at all levels for "sva". So, we need not
3573 * perform "sva += L3_SIZE;" here. Moreover, we need
3574 * not perform "va = sva;" if "sva" is at the start
3575 * of a new valid range consisting of a single page.
3583 pmap_invalidate_range(pmap, va, sva, true);
3587 * Remove the given range of addresses from the specified map.
3589 * It is assumed that the start and end are properly
3590 * rounded to the page size.
3593 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3595 struct rwlock *lock;
3596 vm_offset_t va_next;
3597 pd_entry_t *l0, *l1, *l2;
3598 pt_entry_t l3_paddr;
3599 struct spglist free;
3602 * Perform an unsynchronized read. This is, however, safe.
3604 if (pmap->pm_stats.resident_count == 0)
3612 for (; sva < eva; sva = va_next) {
3613 if (pmap->pm_stats.resident_count == 0)
3616 l0 = pmap_l0(pmap, sva);
3617 if (pmap_load(l0) == 0) {
3618 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
3624 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
3627 l1 = pmap_l0_to_l1(l0, sva);
3628 if (pmap_load(l1) == 0)
3630 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
3631 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
3632 KASSERT(va_next <= eva,
3633 ("partial update of non-transparent 1G page "
3634 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
3635 pmap_load(l1), sva, eva, va_next));
3636 MPASS(pmap != kernel_pmap);
3637 MPASS((pmap_load(l1) & ATTR_SW_MANAGED) == 0);
3639 pmap_s1_invalidate_page(pmap, sva, true);
3640 pmap_resident_count_dec(pmap, L1_SIZE / PAGE_SIZE);
3641 pmap_unuse_pt(pmap, sva, pmap_load(l0), &free);
3646 * Calculate index for next page table.
3648 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
3652 l2 = pmap_l1_to_l2(l1, sva);
3656 l3_paddr = pmap_load(l2);
3658 if ((l3_paddr & ATTR_DESCR_MASK) == L2_BLOCK) {
3659 if (sva + L2_SIZE == va_next && eva >= va_next) {
3660 pmap_remove_l2(pmap, l2, sva, pmap_load(l1),
3663 } else if (pmap_demote_l2_locked(pmap, l2, sva,
3666 l3_paddr = pmap_load(l2);
3670 * Weed out invalid mappings.
3672 if ((l3_paddr & ATTR_DESCR_MASK) != L2_TABLE)
3676 * Limit our scan to either the end of the va represented
3677 * by the current page table page, or to the end of the
3678 * range being removed.
3683 pmap_remove_l3_range(pmap, l3_paddr, sva, va_next, &free,
3689 vm_page_free_pages_toq(&free, true);
3693 * Remove the given range of addresses as part of a logical unmap
3694 * operation. This has the effect of calling pmap_remove(), but
3695 * also clears any metadata that should persist for the lifetime
3696 * of a logical mapping.
3699 pmap_map_delete(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3701 pmap_remove(pmap, sva, eva);
3705 * Routine: pmap_remove_all
3707 * Removes this physical page from
3708 * all physical maps in which it resides.
3709 * Reflects back modify bits to the pager.
3712 * Original versions of this routine were very
3713 * inefficient because they iteratively called
3714 * pmap_remove (slow...)
3718 pmap_remove_all(vm_page_t m)
3720 struct md_page *pvh;
3723 struct rwlock *lock;
3724 pd_entry_t *pde, tpde;
3725 pt_entry_t *pte, tpte;
3727 struct spglist free;
3728 int lvl, pvh_gen, md_gen;
3730 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3731 ("pmap_remove_all: page %p is not managed", m));
3733 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3734 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
3737 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
3739 if (!PMAP_TRYLOCK(pmap)) {
3740 pvh_gen = pvh->pv_gen;
3744 if (pvh_gen != pvh->pv_gen) {
3750 pte = pmap_pte_exists(pmap, va, 2, __func__);
3751 pmap_demote_l2_locked(pmap, pte, va, &lock);
3754 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3756 if (!PMAP_TRYLOCK(pmap)) {
3757 pvh_gen = pvh->pv_gen;
3758 md_gen = m->md.pv_gen;
3762 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
3767 pmap_resident_count_dec(pmap, 1);
3769 pde = pmap_pde(pmap, pv->pv_va, &lvl);
3770 KASSERT(pde != NULL,
3771 ("pmap_remove_all: no page directory entry found"));
3773 ("pmap_remove_all: invalid pde level %d", lvl));
3774 tpde = pmap_load(pde);
3776 pte = pmap_l2_to_l3(pde, pv->pv_va);
3777 tpte = pmap_load_clear(pte);
3778 if (tpte & ATTR_SW_WIRED)
3779 pmap->pm_stats.wired_count--;
3780 if ((tpte & ATTR_AF) != 0) {
3781 pmap_invalidate_page(pmap, pv->pv_va, true);
3782 vm_page_aflag_set(m, PGA_REFERENCED);
3786 * Update the vm_page_t clean and reference bits.
3788 if (pmap_pte_dirty(pmap, tpte))
3790 pmap_unuse_pt(pmap, pv->pv_va, tpde, &free);
3791 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3793 free_pv_entry(pmap, pv);
3796 vm_page_aflag_clear(m, PGA_WRITEABLE);
3798 vm_page_free_pages_toq(&free, true);
3802 * Masks and sets bits in a level 2 page table entries in the specified pmap
3805 pmap_protect_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva, pt_entry_t mask,
3811 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3812 PMAP_ASSERT_STAGE1(pmap);
3813 KASSERT((sva & L2_OFFSET) == 0,
3814 ("pmap_protect_l2: sva is not 2mpage aligned"));
3815 old_l2 = pmap_load(l2);
3816 KASSERT((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK,
3817 ("pmap_protect_l2: L2e %lx is not a block mapping", old_l2));
3820 * Return if the L2 entry already has the desired access restrictions
3823 if ((old_l2 & mask) == nbits)
3826 while (!atomic_fcmpset_64(l2, &old_l2, (old_l2 & ~mask) | nbits))
3830 * When a dirty read/write superpage mapping is write protected,
3831 * update the dirty field of each of the superpage's constituent 4KB
3834 if ((old_l2 & ATTR_SW_MANAGED) != 0 &&
3835 (nbits & ATTR_S1_AP(ATTR_S1_AP_RO)) != 0 &&
3836 pmap_pte_dirty(pmap, old_l2)) {
3837 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(old_l2));
3838 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
3843 * Since a promotion must break the 4KB page mappings before making
3844 * the 2MB page mapping, a pmap_s1_invalidate_page() suffices.
3846 pmap_s1_invalidate_page(pmap, sva, true);
3850 * Masks and sets bits in last level page table entries in the specified
3854 pmap_mask_set_locked(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, pt_entry_t mask,
3855 pt_entry_t nbits, bool invalidate)
3857 vm_offset_t va, va_next;
3858 pd_entry_t *l0, *l1, *l2;
3859 pt_entry_t *l3p, l3;
3861 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3862 for (; sva < eva; sva = va_next) {
3863 l0 = pmap_l0(pmap, sva);
3864 if (pmap_load(l0) == 0) {
3865 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
3871 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
3874 l1 = pmap_l0_to_l1(l0, sva);
3875 if (pmap_load(l1) == 0)
3877 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
3878 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
3879 KASSERT(va_next <= eva,
3880 ("partial update of non-transparent 1G page "
3881 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
3882 pmap_load(l1), sva, eva, va_next));
3883 MPASS((pmap_load(l1) & ATTR_SW_MANAGED) == 0);
3884 if ((pmap_load(l1) & mask) != nbits) {
3885 pmap_store(l1, (pmap_load(l1) & ~mask) | nbits);
3887 pmap_s1_invalidate_page(pmap, sva, true);
3892 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
3896 l2 = pmap_l1_to_l2(l1, sva);
3897 if (pmap_load(l2) == 0)
3900 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK) {
3901 if (sva + L2_SIZE == va_next && eva >= va_next) {
3902 pmap_protect_l2(pmap, l2, sva, mask, nbits);
3904 } else if (pmap_demote_l2(pmap, l2, sva) == NULL)
3907 KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
3908 ("pmap_protect: Invalid L2 entry after demotion"));
3914 for (l3p = pmap_l2_to_l3(l2, sva); sva != va_next; l3p++,
3916 l3 = pmap_load(l3p);
3919 * Go to the next L3 entry if the current one is
3920 * invalid or already has the desired access
3921 * restrictions in place. (The latter case occurs
3922 * frequently. For example, in a "buildworld"
3923 * workload, almost 1 out of 4 L3 entries already
3924 * have the desired restrictions.)
3926 if (!pmap_l3_valid(l3) || (l3 & mask) == nbits) {
3927 if (va != va_next) {
3929 pmap_s1_invalidate_range(pmap,
3936 while (!atomic_fcmpset_64(l3p, &l3, (l3 & ~mask) |
3941 * When a dirty read/write mapping is write protected,
3942 * update the page's dirty field.
3944 if ((l3 & ATTR_SW_MANAGED) != 0 &&
3945 (nbits & ATTR_S1_AP(ATTR_S1_AP_RO)) != 0 &&
3946 pmap_pte_dirty(pmap, l3))
3947 vm_page_dirty(PHYS_TO_VM_PAGE(PTE_TO_PHYS(l3)));
3952 if (va != va_next && invalidate)
3953 pmap_s1_invalidate_range(pmap, va, sva, true);
3958 pmap_mask_set(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, pt_entry_t mask,
3959 pt_entry_t nbits, bool invalidate)
3962 pmap_mask_set_locked(pmap, sva, eva, mask, nbits, invalidate);
3967 * Set the physical protection on the
3968 * specified range of this map as requested.
3971 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
3973 pt_entry_t mask, nbits;
3975 PMAP_ASSERT_STAGE1(pmap);
3976 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
3977 if (prot == VM_PROT_NONE) {
3978 pmap_remove(pmap, sva, eva);
3983 if ((prot & VM_PROT_WRITE) == 0) {
3984 mask |= ATTR_S1_AP_RW_BIT | ATTR_SW_DBM;
3985 nbits |= ATTR_S1_AP(ATTR_S1_AP_RO);
3987 if ((prot & VM_PROT_EXECUTE) == 0) {
3989 nbits |= ATTR_S1_XN;
3994 pmap_mask_set(pmap, sva, eva, mask, nbits, true);
3998 pmap_disable_promotion(vm_offset_t sva, vm_size_t size)
4001 MPASS((sva & L3_OFFSET) == 0);
4002 MPASS(((sva + size) & L3_OFFSET) == 0);
4004 pmap_mask_set(kernel_pmap, sva, sva + size, ATTR_SW_NO_PROMOTE,
4005 ATTR_SW_NO_PROMOTE, false);
4009 * Inserts the specified page table page into the specified pmap's collection
4010 * of idle page table pages. Each of a pmap's page table pages is responsible
4011 * for mapping a distinct range of virtual addresses. The pmap's collection is
4012 * ordered by this virtual address range.
4014 * If "promoted" is false, then the page table page "mpte" must be zero filled;
4015 * "mpte"'s valid field will be set to 0.
4017 * If "promoted" is true and "all_l3e_AF_set" is false, then "mpte" must
4018 * contain valid mappings with identical attributes except for ATTR_AF;
4019 * "mpte"'s valid field will be set to 1.
4021 * If "promoted" and "all_l3e_AF_set" are both true, then "mpte" must contain
4022 * valid mappings with identical attributes including ATTR_AF; "mpte"'s valid
4023 * field will be set to VM_PAGE_BITS_ALL.
4026 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted,
4027 bool all_l3e_AF_set)
4030 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4031 KASSERT(promoted || !all_l3e_AF_set,
4032 ("a zero-filled PTP can't have ATTR_AF set in every PTE"));
4033 mpte->valid = promoted ? (all_l3e_AF_set ? VM_PAGE_BITS_ALL : 1) : 0;
4034 return (vm_radix_insert(&pmap->pm_root, mpte));
4038 * Removes the page table page mapping the specified virtual address from the
4039 * specified pmap's collection of idle page table pages, and returns it.
4040 * Otherwise, returns NULL if there is no page table page corresponding to the
4041 * specified virtual address.
4043 static __inline vm_page_t
4044 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
4047 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4048 return (vm_radix_remove(&pmap->pm_root, pmap_l2_pindex(va)));
4052 * Performs a break-before-make update of a pmap entry. This is needed when
4053 * either promoting or demoting pages to ensure the TLB doesn't get into an
4054 * inconsistent state.
4057 pmap_update_entry(pmap_t pmap, pd_entry_t *pte, pd_entry_t newpte,
4058 vm_offset_t va, vm_size_t size)
4062 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4064 if ((newpte & ATTR_SW_NO_PROMOTE) != 0)
4065 panic("%s: Updating non-promote pte", __func__);
4068 * Ensure we don't get switched out with the page table in an
4069 * inconsistent state. We also need to ensure no interrupts fire
4070 * as they may make use of an address we are about to invalidate.
4072 intr = intr_disable();
4075 * Clear the old mapping's valid bit, but leave the rest of the entry
4076 * unchanged, so that a lockless, concurrent pmap_kextract() can still
4077 * lookup the physical address.
4079 pmap_clear_bits(pte, ATTR_DESCR_VALID);
4082 * When promoting, the L{1,2}_TABLE entry that is being replaced might
4083 * be cached, so we invalidate intermediate entries as well as final
4086 pmap_s1_invalidate_range(pmap, va, va + size, false);
4088 /* Create the new mapping */
4089 pmap_store(pte, newpte);
4095 #if VM_NRESERVLEVEL > 0
4097 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
4098 * replace the many pv entries for the 4KB page mappings by a single pv entry
4099 * for the 2MB page mapping.
4102 pmap_pv_promote_l2(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
4103 struct rwlock **lockp)
4105 struct md_page *pvh;
4107 vm_offset_t va_last;
4110 KASSERT((pa & L2_OFFSET) == 0,
4111 ("pmap_pv_promote_l2: pa is not 2mpage aligned"));
4112 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
4115 * Transfer the first page's pv entry for this mapping to the 2mpage's
4116 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
4117 * a transfer avoids the possibility that get_pv_entry() calls
4118 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
4119 * mappings that is being promoted.
4121 m = PHYS_TO_VM_PAGE(pa);
4122 va = va & ~L2_OFFSET;
4123 pv = pmap_pvh_remove(&m->md, pmap, va);
4124 KASSERT(pv != NULL, ("pmap_pv_promote_l2: pv not found"));
4125 pvh = page_to_pvh(m);
4126 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
4128 /* Free the remaining NPTEPG - 1 pv entries. */
4129 va_last = va + L2_SIZE - PAGE_SIZE;
4133 pmap_pvh_free(&m->md, pmap, va);
4134 } while (va < va_last);
4138 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4139 * single level 2 table entry to a single 2MB page mapping. For promotion
4140 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4141 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4142 * identical characteristics.
4145 pmap_promote_l2(pmap_t pmap, pd_entry_t *l2, vm_offset_t va, vm_page_t mpte,
4146 struct rwlock **lockp)
4148 pt_entry_t all_l3e_AF, *firstl3, *l3, newl2, oldl3, pa;
4150 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4151 PMAP_ASSERT_STAGE1(pmap);
4154 * Examine the first L3E in the specified PTP. Abort if this L3E is
4155 * ineligible for promotion...
4157 firstl3 = (pt_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(pmap_load(l2)));
4158 newl2 = pmap_load(firstl3);
4159 if ((newl2 & ATTR_SW_NO_PROMOTE) != 0)
4161 /* ... is not the first physical page within an L2 block */
4162 if ((PTE_TO_PHYS(newl2) & L2_OFFSET) != 0 ||
4163 ((newl2 & ATTR_DESCR_MASK) != L3_PAGE)) { /* ... or is invalid */
4164 atomic_add_long(&pmap_l2_p_failures, 1);
4165 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
4166 " in pmap %p", va, pmap);
4171 * Both here and in the below "for" loop, to allow for repromotion
4172 * after MADV_FREE, conditionally write protect a clean L3E before
4173 * possibly aborting the promotion due to other L3E attributes. Why?
4174 * Suppose that MADV_FREE is applied to a part of a superpage, the
4175 * address range [S, E). pmap_advise() will demote the superpage
4176 * mapping, destroy the 4KB page mapping at the end of [S, E), and
4177 * set AP_RO and clear AF in the L3Es for the rest of [S, E). Later,
4178 * imagine that the memory in [S, E) is recycled, but the last 4KB
4179 * page in [S, E) is not the last to be rewritten, or simply accessed.
4180 * In other words, there is still a 4KB page in [S, E), call it P,
4181 * that is writeable but AP_RO is set and AF is clear in P's L3E.
4182 * Unless we write protect P before aborting the promotion, if and
4183 * when P is finally rewritten, there won't be a page fault to trigger
4187 if ((newl2 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
4188 (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM)) {
4190 * When the mapping is clean, i.e., ATTR_S1_AP_RO is set,
4191 * ATTR_SW_DBM can be cleared without a TLB invalidation.
4193 if (!atomic_fcmpset_64(firstl3, &newl2, newl2 & ~ATTR_SW_DBM))
4195 newl2 &= ~ATTR_SW_DBM;
4196 CTR2(KTR_PMAP, "pmap_promote_l2: protect for va %#lx"
4197 " in pmap %p", va & ~L2_OFFSET, pmap);
4201 * Examine each of the other L3Es in the specified PTP. Abort if this
4202 * L3E maps an unexpected 4KB physical page or does not have identical
4203 * characteristics to the first L3E. If ATTR_AF is not set in every
4204 * PTE, then request that the PTP be refilled on demotion.
4206 all_l3e_AF = newl2 & ATTR_AF;
4207 pa = (PTE_TO_PHYS(newl2) | (newl2 & ATTR_DESCR_MASK))
4208 + L2_SIZE - PAGE_SIZE;
4209 for (l3 = firstl3 + NL3PG - 1; l3 > firstl3; l3--) {
4210 oldl3 = pmap_load(l3);
4211 if ((PTE_TO_PHYS(oldl3) | (oldl3 & ATTR_DESCR_MASK)) != pa) {
4212 atomic_add_long(&pmap_l2_p_failures, 1);
4213 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
4214 " in pmap %p", va, pmap);
4218 if ((oldl3 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
4219 (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM)) {
4221 * When the mapping is clean, i.e., ATTR_S1_AP_RO is
4222 * set, ATTR_SW_DBM can be cleared without a TLB
4225 if (!atomic_fcmpset_64(l3, &oldl3, oldl3 &
4228 oldl3 &= ~ATTR_SW_DBM;
4230 if ((oldl3 & (ATTR_MASK & ~ATTR_AF)) != (newl2 & (ATTR_MASK &
4232 atomic_add_long(&pmap_l2_p_failures, 1);
4233 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
4234 " in pmap %p", va, pmap);
4237 all_l3e_AF &= oldl3;
4242 * Unless all PTEs have ATTR_AF set, clear it from the superpage
4243 * mapping, so that promotions triggered by speculative mappings,
4244 * such as pmap_enter_quick(), don't automatically mark the
4245 * underlying pages as referenced.
4247 newl2 &= ~ATTR_AF | all_l3e_AF;
4250 * Save the page table page in its current state until the L2
4251 * mapping the superpage is demoted by pmap_demote_l2() or
4252 * destroyed by pmap_remove_l3().
4255 mpte = PHYS_TO_VM_PAGE(PTE_TO_PHYS(pmap_load(l2)));
4256 KASSERT(mpte >= vm_page_array &&
4257 mpte < &vm_page_array[vm_page_array_size],
4258 ("pmap_promote_l2: page table page is out of range"));
4259 KASSERT(mpte->pindex == pmap_l2_pindex(va),
4260 ("pmap_promote_l2: page table page's pindex is wrong"));
4261 if (pmap_insert_pt_page(pmap, mpte, true, all_l3e_AF != 0)) {
4262 atomic_add_long(&pmap_l2_p_failures, 1);
4264 "pmap_promote_l2: failure for va %#lx in pmap %p", va,
4269 if ((newl2 & ATTR_SW_MANAGED) != 0)
4270 pmap_pv_promote_l2(pmap, va, PTE_TO_PHYS(newl2), lockp);
4272 newl2 &= ~ATTR_DESCR_MASK;
4275 pmap_update_entry(pmap, l2, newl2, va & ~L2_OFFSET, L2_SIZE);
4277 atomic_add_long(&pmap_l2_promotions, 1);
4278 CTR2(KTR_PMAP, "pmap_promote_l2: success for va %#lx in pmap %p", va,
4281 #endif /* VM_NRESERVLEVEL > 0 */
4284 pmap_enter_largepage(pmap_t pmap, vm_offset_t va, pt_entry_t newpte, int flags,
4287 pd_entry_t *l0p, *l1p, *l2p, origpte;
4290 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4291 KASSERT(psind > 0 && psind < MAXPAGESIZES,
4292 ("psind %d unexpected", psind));
4293 KASSERT((PTE_TO_PHYS(newpte) & (pagesizes[psind] - 1)) == 0,
4294 ("unaligned phys address %#lx newpte %#lx psind %d",
4295 PTE_TO_PHYS(newpte), newpte, psind));
4299 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
4301 l0p = pmap_l0(pmap, va);
4302 if ((pmap_load(l0p) & ATTR_DESCR_VALID) == 0) {
4303 mp = _pmap_alloc_l3(pmap, pmap_l0_pindex(va), NULL);
4305 if ((flags & PMAP_ENTER_NOSLEEP) != 0)
4306 return (KERN_RESOURCE_SHORTAGE);
4312 l1p = pmap_l0_to_l1(l0p, va);
4313 KASSERT(l1p != NULL, ("va %#lx lost l1 entry", va));
4314 origpte = pmap_load(l1p);
4316 l1p = pmap_l0_to_l1(l0p, va);
4317 KASSERT(l1p != NULL, ("va %#lx lost l1 entry", va));
4318 origpte = pmap_load(l1p);
4319 if ((origpte & ATTR_DESCR_VALID) == 0) {
4320 mp = PHYS_TO_VM_PAGE(
4321 PTE_TO_PHYS(pmap_load(l0p)));
4325 KASSERT((PTE_TO_PHYS(origpte) == PTE_TO_PHYS(newpte) &&
4326 (origpte & ATTR_DESCR_MASK) == L1_BLOCK) ||
4327 (origpte & ATTR_DESCR_VALID) == 0,
4328 ("va %#lx changing 1G phys page l1 %#lx newpte %#lx",
4329 va, origpte, newpte));
4330 pmap_store(l1p, newpte);
4331 } else /* (psind == 1) */ {
4332 l2p = pmap_l2(pmap, va);
4334 mp = _pmap_alloc_l3(pmap, pmap_l1_pindex(va), NULL);
4336 if ((flags & PMAP_ENTER_NOSLEEP) != 0)
4337 return (KERN_RESOURCE_SHORTAGE);
4343 l2p = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
4344 l2p = &l2p[pmap_l2_index(va)];
4345 origpte = pmap_load(l2p);
4347 l1p = pmap_l1(pmap, va);
4348 origpte = pmap_load(l2p);
4349 if ((origpte & ATTR_DESCR_VALID) == 0) {
4350 mp = PHYS_TO_VM_PAGE(
4351 PTE_TO_PHYS(pmap_load(l1p)));
4355 KASSERT((origpte & ATTR_DESCR_VALID) == 0 ||
4356 ((origpte & ATTR_DESCR_MASK) == L2_BLOCK &&
4357 PTE_TO_PHYS(origpte) == PTE_TO_PHYS(newpte)),
4358 ("va %#lx changing 2M phys page l2 %#lx newpte %#lx",
4359 va, origpte, newpte));
4360 pmap_store(l2p, newpte);
4364 if ((origpte & ATTR_DESCR_VALID) == 0)
4365 pmap_resident_count_inc(pmap, pagesizes[psind] / PAGE_SIZE);
4366 if ((newpte & ATTR_SW_WIRED) != 0 && (origpte & ATTR_SW_WIRED) == 0)
4367 pmap->pm_stats.wired_count += pagesizes[psind] / PAGE_SIZE;
4368 else if ((newpte & ATTR_SW_WIRED) == 0 &&
4369 (origpte & ATTR_SW_WIRED) != 0)
4370 pmap->pm_stats.wired_count -= pagesizes[psind] / PAGE_SIZE;
4372 return (KERN_SUCCESS);
4376 * Insert the given physical page (p) at
4377 * the specified virtual address (v) in the
4378 * target physical map with the protection requested.
4380 * If specified, the page will be wired down, meaning
4381 * that the related pte can not be reclaimed.
4383 * NB: This is the only routine which MAY NOT lazy-evaluate
4384 * or lose information. That is, this routine must actually
4385 * insert this page into the given map NOW.
4388 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4389 u_int flags, int8_t psind)
4391 struct rwlock *lock;
4393 pt_entry_t new_l3, orig_l3;
4394 pt_entry_t *l2, *l3;
4401 KASSERT(ADDR_IS_CANONICAL(va),
4402 ("%s: Address not in canonical form: %lx", __func__, va));
4404 va = trunc_page(va);
4405 if ((m->oflags & VPO_UNMANAGED) == 0)
4406 VM_PAGE_OBJECT_BUSY_ASSERT(m);
4407 pa = VM_PAGE_TO_PHYS(m);
4408 new_l3 = (pt_entry_t)(PHYS_TO_PTE(pa) | ATTR_DEFAULT | L3_PAGE);
4409 new_l3 |= pmap_pte_memattr(pmap, m->md.pv_memattr);
4410 new_l3 |= pmap_pte_prot(pmap, prot);
4412 if ((flags & PMAP_ENTER_WIRED) != 0)
4413 new_l3 |= ATTR_SW_WIRED;
4414 if (pmap->pm_stage == PM_STAGE1) {
4415 if (!ADDR_IS_KERNEL(va))
4416 new_l3 |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
4418 new_l3 |= ATTR_S1_UXN;
4419 if (pmap != kernel_pmap)
4420 new_l3 |= ATTR_S1_nG;
4423 * Clear the access flag on executable mappings, this will be
4424 * set later when the page is accessed. The fault handler is
4425 * required to invalidate the I-cache.
4427 * TODO: Switch to the valid flag to allow hardware management
4428 * of the access flag. Much of the pmap code assumes the
4429 * valid flag is set and fails to destroy the old page tables
4430 * correctly if it is clear.
4432 if (prot & VM_PROT_EXECUTE)
4435 if ((m->oflags & VPO_UNMANAGED) == 0) {
4436 new_l3 |= ATTR_SW_MANAGED;
4437 if ((prot & VM_PROT_WRITE) != 0) {
4438 new_l3 |= ATTR_SW_DBM;
4439 if ((flags & VM_PROT_WRITE) == 0) {
4440 if (pmap->pm_stage == PM_STAGE1)
4441 new_l3 |= ATTR_S1_AP(ATTR_S1_AP_RO);
4444 ~ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
4449 CTR2(KTR_PMAP, "pmap_enter: %.16lx -> %.16lx", va, pa);
4453 if ((flags & PMAP_ENTER_LARGEPAGE) != 0) {
4454 KASSERT((m->oflags & VPO_UNMANAGED) != 0,
4455 ("managed largepage va %#lx flags %#x", va, flags));
4458 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
4460 } else /* (psind == 1) */
4462 rv = pmap_enter_largepage(pmap, va, new_l3, flags, psind);
4466 /* Assert the required virtual and physical alignment. */
4467 KASSERT((va & L2_OFFSET) == 0, ("pmap_enter: va unaligned"));
4468 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4469 rv = pmap_enter_l2(pmap, va, (new_l3 & ~L3_PAGE) | L2_BLOCK,
4476 * In the case that a page table page is not
4477 * resident, we are creating it here.
4480 pde = pmap_pde(pmap, va, &lvl);
4481 if (pde != NULL && lvl == 2) {
4482 l3 = pmap_l2_to_l3(pde, va);
4483 if (!ADDR_IS_KERNEL(va) && mpte == NULL) {
4484 mpte = PHYS_TO_VM_PAGE(PTE_TO_PHYS(pmap_load(pde)));
4488 } else if (pde != NULL && lvl == 1) {
4489 l2 = pmap_l1_to_l2(pde, va);
4490 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK &&
4491 (l3 = pmap_demote_l2_locked(pmap, l2, va, &lock)) != NULL) {
4492 l3 = &l3[pmap_l3_index(va)];
4493 if (!ADDR_IS_KERNEL(va)) {
4494 mpte = PHYS_TO_VM_PAGE(
4495 PTE_TO_PHYS(pmap_load(l2)));
4500 /* We need to allocate an L3 table. */
4502 if (!ADDR_IS_KERNEL(va)) {
4503 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4506 * We use _pmap_alloc_l3() instead of pmap_alloc_l3() in order
4507 * to handle the possibility that a superpage mapping for "va"
4508 * was created while we slept.
4510 mpte = _pmap_alloc_l3(pmap, pmap_l2_pindex(va),
4511 nosleep ? NULL : &lock);
4512 if (mpte == NULL && nosleep) {
4513 CTR0(KTR_PMAP, "pmap_enter: mpte == NULL");
4514 rv = KERN_RESOURCE_SHORTAGE;
4519 panic("pmap_enter: missing L3 table for kernel va %#lx", va);
4522 orig_l3 = pmap_load(l3);
4523 opa = PTE_TO_PHYS(orig_l3);
4527 * Is the specified virtual address already mapped?
4529 if (pmap_l3_valid(orig_l3)) {
4531 * Wiring change, just update stats. We don't worry about
4532 * wiring PT pages as they remain resident as long as there
4533 * are valid mappings in them. Hence, if a user page is wired,
4534 * the PT page will be also.
4536 if ((flags & PMAP_ENTER_WIRED) != 0 &&
4537 (orig_l3 & ATTR_SW_WIRED) == 0)
4538 pmap->pm_stats.wired_count++;
4539 else if ((flags & PMAP_ENTER_WIRED) == 0 &&
4540 (orig_l3 & ATTR_SW_WIRED) != 0)
4541 pmap->pm_stats.wired_count--;
4544 * Remove the extra PT page reference.
4548 KASSERT(mpte->ref_count > 0,
4549 ("pmap_enter: missing reference to page table page,"
4554 * Has the physical page changed?
4558 * No, might be a protection or wiring change.
4560 if ((orig_l3 & ATTR_SW_MANAGED) != 0 &&
4561 (new_l3 & ATTR_SW_DBM) != 0)
4562 vm_page_aflag_set(m, PGA_WRITEABLE);
4567 * The physical page has changed. Temporarily invalidate
4570 orig_l3 = pmap_load_clear(l3);
4571 KASSERT(PTE_TO_PHYS(orig_l3) == opa,
4572 ("pmap_enter: unexpected pa update for %#lx", va));
4573 if ((orig_l3 & ATTR_SW_MANAGED) != 0) {
4574 om = PHYS_TO_VM_PAGE(opa);
4577 * The pmap lock is sufficient to synchronize with
4578 * concurrent calls to pmap_page_test_mappings() and
4579 * pmap_ts_referenced().
4581 if (pmap_pte_dirty(pmap, orig_l3))
4583 if ((orig_l3 & ATTR_AF) != 0) {
4584 pmap_invalidate_page(pmap, va, true);
4585 vm_page_aflag_set(om, PGA_REFERENCED);
4587 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, om);
4588 pv = pmap_pvh_remove(&om->md, pmap, va);
4589 if ((m->oflags & VPO_UNMANAGED) != 0)
4590 free_pv_entry(pmap, pv);
4591 if ((om->a.flags & PGA_WRITEABLE) != 0 &&
4592 TAILQ_EMPTY(&om->md.pv_list) &&
4593 ((om->flags & PG_FICTITIOUS) != 0 ||
4594 TAILQ_EMPTY(&page_to_pvh(om)->pv_list)))
4595 vm_page_aflag_clear(om, PGA_WRITEABLE);
4597 KASSERT((orig_l3 & ATTR_AF) != 0,
4598 ("pmap_enter: unmanaged mapping lacks ATTR_AF"));
4599 pmap_invalidate_page(pmap, va, true);
4604 * Increment the counters.
4606 if ((new_l3 & ATTR_SW_WIRED) != 0)
4607 pmap->pm_stats.wired_count++;
4608 pmap_resident_count_inc(pmap, 1);
4611 * Enter on the PV list if part of our managed memory.
4613 if ((m->oflags & VPO_UNMANAGED) == 0) {
4615 pv = get_pv_entry(pmap, &lock);
4618 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
4619 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4621 if ((new_l3 & ATTR_SW_DBM) != 0)
4622 vm_page_aflag_set(m, PGA_WRITEABLE);
4626 if (pmap->pm_stage == PM_STAGE1) {
4628 * Sync icache if exec permission and attribute
4629 * VM_MEMATTR_WRITE_BACK is set. Do it now, before the mapping
4630 * is stored and made valid for hardware table walk. If done
4631 * later, then other can access this page before caches are
4632 * properly synced. Don't do it for kernel memory which is
4633 * mapped with exec permission even if the memory isn't going
4634 * to hold executable code. The only time when icache sync is
4635 * needed is after kernel module is loaded and the relocation
4636 * info is processed. And it's done in elf_cpu_load_file().
4638 if ((prot & VM_PROT_EXECUTE) && pmap != kernel_pmap &&
4639 m->md.pv_memattr == VM_MEMATTR_WRITE_BACK &&
4640 (opa != pa || (orig_l3 & ATTR_S1_XN))) {
4641 PMAP_ASSERT_STAGE1(pmap);
4642 cpu_icache_sync_range(PHYS_TO_DMAP(pa), PAGE_SIZE);
4645 cpu_dcache_wb_range(PHYS_TO_DMAP(pa), PAGE_SIZE);
4649 * Update the L3 entry
4651 if (pmap_l3_valid(orig_l3)) {
4652 KASSERT(opa == pa, ("pmap_enter: invalid update"));
4653 if ((orig_l3 & ~ATTR_AF) != (new_l3 & ~ATTR_AF)) {
4654 /* same PA, different attributes */
4655 orig_l3 = pmap_load_store(l3, new_l3);
4656 pmap_invalidate_page(pmap, va, true);
4657 if ((orig_l3 & ATTR_SW_MANAGED) != 0 &&
4658 pmap_pte_dirty(pmap, orig_l3))
4663 * This can happens if multiple threads simultaneously
4664 * access not yet mapped page. This bad for performance
4665 * since this can cause full demotion-NOP-promotion
4667 * Another possible reasons are:
4668 * - VM and pmap memory layout are diverged
4669 * - tlb flush is missing somewhere and CPU doesn't see
4672 CTR4(KTR_PMAP, "%s: already mapped page - "
4673 "pmap %p va 0x%#lx pte 0x%lx",
4674 __func__, pmap, va, new_l3);
4678 pmap_store(l3, new_l3);
4682 #if VM_NRESERVLEVEL > 0
4684 * Try to promote from level 3 pages to a level 2 superpage. This
4685 * currently only works on stage 1 pmaps as pmap_promote_l2 looks at
4686 * stage 1 specific fields and performs a break-before-make sequence
4687 * that is incorrect a stage 2 pmap.
4689 if ((mpte == NULL || mpte->ref_count == NL3PG) &&
4690 pmap_ps_enabled(pmap) && pmap->pm_stage == PM_STAGE1 &&
4691 (m->flags & PG_FICTITIOUS) == 0 &&
4692 vm_reserv_level_iffullpop(m) == 0) {
4693 pmap_promote_l2(pmap, pde, va, mpte, &lock);
4706 * Tries to create a read- and/or execute-only 2MB page mapping. Returns
4707 * KERN_SUCCESS if the mapping was created. Otherwise, returns an error
4708 * value. See pmap_enter_l2() for the possible error values when "no sleep",
4709 * "no replace", and "no reclaim" are specified.
4712 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4713 struct rwlock **lockp)
4717 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4718 PMAP_ASSERT_STAGE1(pmap);
4719 KASSERT(ADDR_IS_CANONICAL(va),
4720 ("%s: Address not in canonical form: %lx", __func__, va));
4722 new_l2 = (pd_entry_t)(PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) | ATTR_DEFAULT |
4723 ATTR_S1_IDX(m->md.pv_memattr) | ATTR_S1_AP(ATTR_S1_AP_RO) |
4725 if ((m->oflags & VPO_UNMANAGED) == 0) {
4726 new_l2 |= ATTR_SW_MANAGED;
4729 if ((prot & VM_PROT_EXECUTE) == 0 ||
4730 m->md.pv_memattr == VM_MEMATTR_DEVICE)
4731 new_l2 |= ATTR_S1_XN;
4732 if (!ADDR_IS_KERNEL(va))
4733 new_l2 |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
4735 new_l2 |= ATTR_S1_UXN;
4736 if (pmap != kernel_pmap)
4737 new_l2 |= ATTR_S1_nG;
4738 return (pmap_enter_l2(pmap, va, new_l2, PMAP_ENTER_NOSLEEP |
4739 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, m, lockp));
4743 * Returns true if every page table entry in the specified page table is
4747 pmap_every_pte_zero(vm_paddr_t pa)
4749 pt_entry_t *pt_end, *pte;
4751 KASSERT((pa & PAGE_MASK) == 0, ("pa is misaligned"));
4752 pte = (pt_entry_t *)PHYS_TO_DMAP(pa);
4753 for (pt_end = pte + Ln_ENTRIES; pte < pt_end; pte++) {
4761 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
4762 * the mapping was created, and one of KERN_FAILURE, KERN_NO_SPACE, or
4763 * KERN_RESOURCE_SHORTAGE otherwise. Returns KERN_FAILURE if
4764 * PMAP_ENTER_NOREPLACE was specified and a 4KB page mapping already exists
4765 * within the 2MB virtual address range starting at the specified virtual
4766 * address. Returns KERN_NO_SPACE if PMAP_ENTER_NOREPLACE was specified and a
4767 * 2MB page mapping already exists at the specified virtual address. Returns
4768 * KERN_RESOURCE_SHORTAGE if either (1) PMAP_ENTER_NOSLEEP was specified and a
4769 * page table page allocation failed or (2) PMAP_ENTER_NORECLAIM was specified
4770 * and a PV entry allocation failed.
4773 pmap_enter_l2(pmap_t pmap, vm_offset_t va, pd_entry_t new_l2, u_int flags,
4774 vm_page_t m, struct rwlock **lockp)
4776 struct spglist free;
4777 pd_entry_t *l2, old_l2;
4780 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4781 KASSERT(ADDR_IS_CANONICAL(va),
4782 ("%s: Address not in canonical form: %lx", __func__, va));
4784 if ((l2 = pmap_alloc_l2(pmap, va, &l2pg, (flags &
4785 PMAP_ENTER_NOSLEEP) != 0 ? NULL : lockp)) == NULL) {
4786 CTR2(KTR_PMAP, "pmap_enter_l2: failure for va %#lx in pmap %p",
4788 return (KERN_RESOURCE_SHORTAGE);
4792 * If there are existing mappings, either abort or remove them.
4794 if ((old_l2 = pmap_load(l2)) != 0) {
4795 KASSERT(l2pg == NULL || l2pg->ref_count > 1,
4796 ("pmap_enter_l2: l2pg's ref count is too low"));
4797 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
4798 if ((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK) {
4802 "pmap_enter_l2: no space for va %#lx"
4803 " in pmap %p", va, pmap);
4804 return (KERN_NO_SPACE);
4805 } else if (!ADDR_IS_KERNEL(va) ||
4806 !pmap_every_pte_zero(PTE_TO_PHYS(old_l2))) {
4810 "pmap_enter_l2: failure for va %#lx"
4811 " in pmap %p", va, pmap);
4812 return (KERN_FAILURE);
4816 if ((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK)
4817 (void)pmap_remove_l2(pmap, l2, va,
4818 pmap_load(pmap_l1(pmap, va)), &free, lockp);
4820 pmap_remove_l3_range(pmap, old_l2, va, va + L2_SIZE,
4822 if (!ADDR_IS_KERNEL(va)) {
4823 vm_page_free_pages_toq(&free, true);
4824 KASSERT(pmap_load(l2) == 0,
4825 ("pmap_enter_l2: non-zero L2 entry %p", l2));
4827 KASSERT(SLIST_EMPTY(&free),
4828 ("pmap_enter_l2: freed kernel page table page"));
4831 * Both pmap_remove_l2() and pmap_remove_l3_range()
4832 * will leave the kernel page table page zero filled.
4833 * Nonetheless, the TLB could have an intermediate
4834 * entry for the kernel page table page, so request
4835 * an invalidation at all levels after clearing
4836 * the L2_TABLE entry.
4838 mt = PHYS_TO_VM_PAGE(PTE_TO_PHYS(pmap_load(l2)));
4839 if (pmap_insert_pt_page(pmap, mt, false, false))
4840 panic("pmap_enter_l2: trie insert failed");
4842 pmap_s1_invalidate_page(pmap, va, false);
4846 if ((new_l2 & ATTR_SW_MANAGED) != 0) {
4848 * Abort this mapping if its PV entry could not be created.
4850 if (!pmap_pv_insert_l2(pmap, va, new_l2, flags, lockp)) {
4852 pmap_abort_ptp(pmap, va, l2pg);
4854 "pmap_enter_l2: failure for va %#lx in pmap %p",
4856 return (KERN_RESOURCE_SHORTAGE);
4858 if ((new_l2 & ATTR_SW_DBM) != 0)
4859 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
4860 vm_page_aflag_set(mt, PGA_WRITEABLE);
4864 * Increment counters.
4866 if ((new_l2 & ATTR_SW_WIRED) != 0)
4867 pmap->pm_stats.wired_count += L2_SIZE / PAGE_SIZE;
4868 pmap->pm_stats.resident_count += L2_SIZE / PAGE_SIZE;
4871 * Conditionally sync the icache. See pmap_enter() for details.
4873 if ((new_l2 & ATTR_S1_XN) == 0 && (PTE_TO_PHYS(new_l2) !=
4874 PTE_TO_PHYS(old_l2) || (old_l2 & ATTR_S1_XN) != 0) &&
4875 pmap != kernel_pmap && m->md.pv_memattr == VM_MEMATTR_WRITE_BACK) {
4876 cpu_icache_sync_range(PHYS_TO_DMAP(PTE_TO_PHYS(new_l2)),
4881 * Map the superpage.
4883 pmap_store(l2, new_l2);
4886 atomic_add_long(&pmap_l2_mappings, 1);
4887 CTR2(KTR_PMAP, "pmap_enter_l2: success for va %#lx in pmap %p",
4890 return (KERN_SUCCESS);
4894 * Maps a sequence of resident pages belonging to the same object.
4895 * The sequence begins with the given page m_start. This page is
4896 * mapped at the given virtual address start. Each subsequent page is
4897 * mapped at a virtual address that is offset from start by the same
4898 * amount as the page is offset from m_start within the object. The
4899 * last page in the sequence is the page with the largest offset from
4900 * m_start that can be mapped at a virtual address less than the given
4901 * virtual address end. Not every virtual page between start and end
4902 * is mapped; only those for which a resident page exists with the
4903 * corresponding offset from m_start are mapped.
4906 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
4907 vm_page_t m_start, vm_prot_t prot)
4909 struct rwlock *lock;
4912 vm_pindex_t diff, psize;
4915 VM_OBJECT_ASSERT_LOCKED(m_start->object);
4917 psize = atop(end - start);
4922 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
4923 va = start + ptoa(diff);
4924 if ((va & L2_OFFSET) == 0 && va + L2_SIZE <= end &&
4925 m->psind == 1 && pmap_ps_enabled(pmap) &&
4926 ((rv = pmap_enter_2mpage(pmap, va, m, prot, &lock)) ==
4927 KERN_SUCCESS || rv == KERN_NO_SPACE))
4928 m = &m[L2_SIZE / PAGE_SIZE - 1];
4930 mpte = pmap_enter_quick_locked(pmap, va, m, prot, mpte,
4932 m = TAILQ_NEXT(m, listq);
4940 * this code makes some *MAJOR* assumptions:
4941 * 1. Current pmap & pmap exists.
4944 * 4. No page table pages.
4945 * but is *MUCH* faster than pmap_enter...
4949 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
4951 struct rwlock *lock;
4955 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
4962 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
4963 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
4966 pt_entry_t *l1, *l2, *l3, l3_val;
4970 KASSERT(!VA_IS_CLEANMAP(va) ||
4971 (m->oflags & VPO_UNMANAGED) != 0,
4972 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
4973 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4974 PMAP_ASSERT_STAGE1(pmap);
4975 KASSERT(ADDR_IS_CANONICAL(va),
4976 ("%s: Address not in canonical form: %lx", __func__, va));
4979 CTR2(KTR_PMAP, "pmap_enter_quick_locked: %p %lx", pmap, va);
4981 * In the case that a page table page is not
4982 * resident, we are creating it here.
4984 if (!ADDR_IS_KERNEL(va)) {
4985 vm_pindex_t l2pindex;
4988 * Calculate pagetable page index
4990 l2pindex = pmap_l2_pindex(va);
4991 if (mpte && (mpte->pindex == l2pindex)) {
4995 * If the page table page is mapped, we just increment
4996 * the hold count, and activate it. Otherwise, we
4997 * attempt to allocate a page table page, passing NULL
4998 * instead of the PV list lock pointer because we don't
4999 * intend to sleep. If this attempt fails, we don't
5000 * retry. Instead, we give up.
5002 l1 = pmap_l1(pmap, va);
5003 if (l1 != NULL && pmap_load(l1) != 0) {
5004 if ((pmap_load(l1) & ATTR_DESCR_MASK) ==
5007 l2 = pmap_l1_to_l2(l1, va);
5008 if (pmap_load(l2) != 0) {
5009 if ((pmap_load(l2) & ATTR_DESCR_MASK) ==
5012 mpte = PHYS_TO_VM_PAGE(
5013 PTE_TO_PHYS(pmap_load(l2)));
5016 mpte = _pmap_alloc_l3(pmap, l2pindex,
5022 mpte = _pmap_alloc_l3(pmap, l2pindex, NULL);
5027 l3 = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
5028 l3 = &l3[pmap_l3_index(va)];
5031 pde = pmap_pde(kernel_pmap, va, &lvl);
5032 KASSERT(pde != NULL,
5033 ("pmap_enter_quick_locked: Invalid page entry, va: 0x%lx",
5036 ("pmap_enter_quick_locked: Invalid level %d", lvl));
5037 l3 = pmap_l2_to_l3(pde, va);
5041 * Abort if a mapping already exists.
5043 if (pmap_load(l3) != 0) {
5050 * Enter on the PV list if part of our managed memory.
5052 if ((m->oflags & VPO_UNMANAGED) == 0 &&
5053 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
5055 pmap_abort_ptp(pmap, va, mpte);
5060 * Increment counters
5062 pmap_resident_count_inc(pmap, 1);
5064 pa = VM_PAGE_TO_PHYS(m);
5065 l3_val = PHYS_TO_PTE(pa) | ATTR_DEFAULT | ATTR_S1_IDX(m->md.pv_memattr) |
5066 ATTR_S1_AP(ATTR_S1_AP_RO) | L3_PAGE;
5067 if ((prot & VM_PROT_EXECUTE) == 0 ||
5068 m->md.pv_memattr == VM_MEMATTR_DEVICE)
5069 l3_val |= ATTR_S1_XN;
5070 if (!ADDR_IS_KERNEL(va))
5071 l3_val |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
5073 l3_val |= ATTR_S1_UXN;
5074 if (pmap != kernel_pmap)
5075 l3_val |= ATTR_S1_nG;
5078 * Now validate mapping with RO protection
5080 if ((m->oflags & VPO_UNMANAGED) == 0) {
5081 l3_val |= ATTR_SW_MANAGED;
5085 /* Sync icache before the mapping is stored to PTE */
5086 if ((prot & VM_PROT_EXECUTE) && pmap != kernel_pmap &&
5087 m->md.pv_memattr == VM_MEMATTR_WRITE_BACK)
5088 cpu_icache_sync_range(PHYS_TO_DMAP(pa), PAGE_SIZE);
5090 pmap_store(l3, l3_val);
5093 #if VM_NRESERVLEVEL > 0
5095 * If both the PTP and the reservation are fully populated, then
5096 * attempt promotion.
5098 if ((mpte == NULL || mpte->ref_count == NL3PG) &&
5099 pmap_ps_enabled(pmap) && pmap->pm_stage == PM_STAGE1 &&
5100 (m->flags & PG_FICTITIOUS) == 0 &&
5101 vm_reserv_level_iffullpop(m) == 0) {
5103 l2 = pmap_pde(pmap, va, &lvl);
5104 pmap_promote_l2(pmap, l2, va, mpte, lockp);
5107 * If promotion succeeds, then the next call to this function
5108 * should not be given the unmapped PTP as a hint.
5118 * This code maps large physical mmap regions into the
5119 * processor address space. Note that some shortcuts
5120 * are taken, but the code works.
5123 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
5124 vm_pindex_t pindex, vm_size_t size)
5127 VM_OBJECT_ASSERT_WLOCKED(object);
5128 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
5129 ("pmap_object_init_pt: non-device object"));
5133 * Clear the wired attribute from the mappings for the specified range of
5134 * addresses in the given pmap. Every valid mapping within that range
5135 * must have the wired attribute set. In contrast, invalid mappings
5136 * cannot have the wired attribute set, so they are ignored.
5138 * The wired attribute of the page table entry is not a hardware feature,
5139 * so there is no need to invalidate any TLB entries.
5142 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5144 vm_offset_t va_next;
5145 pd_entry_t *l0, *l1, *l2;
5149 for (; sva < eva; sva = va_next) {
5150 l0 = pmap_l0(pmap, sva);
5151 if (pmap_load(l0) == 0) {
5152 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
5158 l1 = pmap_l0_to_l1(l0, sva);
5159 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
5162 if (pmap_load(l1) == 0)
5165 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
5166 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
5167 KASSERT(va_next <= eva,
5168 ("partial update of non-transparent 1G page "
5169 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
5170 pmap_load(l1), sva, eva, va_next));
5171 MPASS(pmap != kernel_pmap);
5172 MPASS((pmap_load(l1) & (ATTR_SW_MANAGED |
5173 ATTR_SW_WIRED)) == ATTR_SW_WIRED);
5174 pmap_clear_bits(l1, ATTR_SW_WIRED);
5175 pmap->pm_stats.wired_count -= L1_SIZE / PAGE_SIZE;
5179 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
5183 l2 = pmap_l1_to_l2(l1, sva);
5184 if (pmap_load(l2) == 0)
5187 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK) {
5188 if ((pmap_load(l2) & ATTR_SW_WIRED) == 0)
5189 panic("pmap_unwire: l2 %#jx is missing "
5190 "ATTR_SW_WIRED", (uintmax_t)pmap_load(l2));
5193 * Are we unwiring the entire large page? If not,
5194 * demote the mapping and fall through.
5196 if (sva + L2_SIZE == va_next && eva >= va_next) {
5197 pmap_clear_bits(l2, ATTR_SW_WIRED);
5198 pmap->pm_stats.wired_count -= L2_SIZE /
5201 } else if (pmap_demote_l2(pmap, l2, sva) == NULL)
5202 panic("pmap_unwire: demotion failed");
5204 KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
5205 ("pmap_unwire: Invalid l2 entry after demotion"));
5209 for (l3 = pmap_l2_to_l3(l2, sva); sva != va_next; l3++,
5211 if (pmap_load(l3) == 0)
5213 if ((pmap_load(l3) & ATTR_SW_WIRED) == 0)
5214 panic("pmap_unwire: l3 %#jx is missing "
5215 "ATTR_SW_WIRED", (uintmax_t)pmap_load(l3));
5218 * ATTR_SW_WIRED must be cleared atomically. Although
5219 * the pmap lock synchronizes access to ATTR_SW_WIRED,
5220 * the System MMU may write to the entry concurrently.
5222 pmap_clear_bits(l3, ATTR_SW_WIRED);
5223 pmap->pm_stats.wired_count--;
5230 * Copy the range specified by src_addr/len
5231 * from the source map to the range dst_addr/len
5232 * in the destination map.
5234 * This routine is only advisory and need not do anything.
5236 * Because the executable mappings created by this routine are copied,
5237 * it should not have to flush the instruction cache.
5240 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5241 vm_offset_t src_addr)
5243 struct rwlock *lock;
5244 pd_entry_t *l0, *l1, *l2, srcptepaddr;
5245 pt_entry_t *dst_pte, mask, nbits, ptetemp, *src_pte;
5246 vm_offset_t addr, end_addr, va_next;
5247 vm_page_t dst_m, dstmpte, srcmpte;
5249 PMAP_ASSERT_STAGE1(dst_pmap);
5250 PMAP_ASSERT_STAGE1(src_pmap);
5252 if (dst_addr != src_addr)
5254 end_addr = src_addr + len;
5256 if (dst_pmap < src_pmap) {
5257 PMAP_LOCK(dst_pmap);
5258 PMAP_LOCK(src_pmap);
5260 PMAP_LOCK(src_pmap);
5261 PMAP_LOCK(dst_pmap);
5263 for (addr = src_addr; addr < end_addr; addr = va_next) {
5264 l0 = pmap_l0(src_pmap, addr);
5265 if (pmap_load(l0) == 0) {
5266 va_next = (addr + L0_SIZE) & ~L0_OFFSET;
5272 va_next = (addr + L1_SIZE) & ~L1_OFFSET;
5275 l1 = pmap_l0_to_l1(l0, addr);
5276 if (pmap_load(l1) == 0)
5278 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
5279 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
5280 KASSERT(va_next <= end_addr,
5281 ("partial update of non-transparent 1G page "
5282 "l1 %#lx addr %#lx end_addr %#lx va_next %#lx",
5283 pmap_load(l1), addr, end_addr, va_next));
5284 srcptepaddr = pmap_load(l1);
5285 l1 = pmap_l1(dst_pmap, addr);
5287 if (_pmap_alloc_l3(dst_pmap,
5288 pmap_l0_pindex(addr), NULL) == NULL)
5290 l1 = pmap_l1(dst_pmap, addr);
5292 l0 = pmap_l0(dst_pmap, addr);
5293 dst_m = PHYS_TO_VM_PAGE(
5294 PTE_TO_PHYS(pmap_load(l0)));
5297 KASSERT(pmap_load(l1) == 0,
5298 ("1G mapping present in dst pmap "
5299 "l1 %#lx addr %#lx end_addr %#lx va_next %#lx",
5300 pmap_load(l1), addr, end_addr, va_next));
5301 pmap_store(l1, srcptepaddr & ~ATTR_SW_WIRED);
5302 pmap_resident_count_inc(dst_pmap, L1_SIZE / PAGE_SIZE);
5306 va_next = (addr + L2_SIZE) & ~L2_OFFSET;
5309 l2 = pmap_l1_to_l2(l1, addr);
5310 srcptepaddr = pmap_load(l2);
5311 if (srcptepaddr == 0)
5313 if ((srcptepaddr & ATTR_DESCR_MASK) == L2_BLOCK) {
5315 * We can only virtual copy whole superpages.
5317 if ((addr & L2_OFFSET) != 0 ||
5318 addr + L2_SIZE > end_addr)
5320 l2 = pmap_alloc_l2(dst_pmap, addr, &dst_m, NULL);
5323 if (pmap_load(l2) == 0 &&
5324 ((srcptepaddr & ATTR_SW_MANAGED) == 0 ||
5325 pmap_pv_insert_l2(dst_pmap, addr, srcptepaddr,
5326 PMAP_ENTER_NORECLAIM, &lock))) {
5328 * We leave the dirty bit unchanged because
5329 * managed read/write superpage mappings are
5330 * required to be dirty. However, managed
5331 * superpage mappings are not required to
5332 * have their accessed bit set, so we clear
5333 * it because we don't know if this mapping
5336 srcptepaddr &= ~ATTR_SW_WIRED;
5337 if ((srcptepaddr & ATTR_SW_MANAGED) != 0)
5338 srcptepaddr &= ~ATTR_AF;
5339 pmap_store(l2, srcptepaddr);
5340 pmap_resident_count_inc(dst_pmap, L2_SIZE /
5342 atomic_add_long(&pmap_l2_mappings, 1);
5344 pmap_abort_ptp(dst_pmap, addr, dst_m);
5347 KASSERT((srcptepaddr & ATTR_DESCR_MASK) == L2_TABLE,
5348 ("pmap_copy: invalid L2 entry"));
5349 srcmpte = PHYS_TO_VM_PAGE(PTE_TO_PHYS(srcptepaddr));
5350 KASSERT(srcmpte->ref_count > 0,
5351 ("pmap_copy: source page table page is unused"));
5352 if (va_next > end_addr)
5354 src_pte = (pt_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(srcptepaddr));
5355 src_pte = &src_pte[pmap_l3_index(addr)];
5357 for (; addr < va_next; addr += PAGE_SIZE, src_pte++) {
5358 ptetemp = pmap_load(src_pte);
5361 * We only virtual copy managed pages.
5363 if ((ptetemp & ATTR_SW_MANAGED) == 0)
5366 if (dstmpte != NULL) {
5367 KASSERT(dstmpte->pindex == pmap_l2_pindex(addr),
5368 ("dstmpte pindex/addr mismatch"));
5369 dstmpte->ref_count++;
5370 } else if ((dstmpte = pmap_alloc_l3(dst_pmap, addr,
5373 dst_pte = (pt_entry_t *)
5374 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5375 dst_pte = &dst_pte[pmap_l3_index(addr)];
5376 if (pmap_load(dst_pte) == 0 &&
5377 pmap_try_insert_pv_entry(dst_pmap, addr,
5378 PHYS_TO_VM_PAGE(PTE_TO_PHYS(ptetemp)), &lock)) {
5380 * Clear the wired, modified, and accessed
5381 * (referenced) bits during the copy.
5383 mask = ATTR_AF | ATTR_SW_WIRED;
5385 if ((ptetemp & ATTR_SW_DBM) != 0)
5386 nbits |= ATTR_S1_AP_RW_BIT;
5387 pmap_store(dst_pte, (ptetemp & ~mask) | nbits);
5388 pmap_resident_count_inc(dst_pmap, 1);
5390 pmap_abort_ptp(dst_pmap, addr, dstmpte);
5393 /* Have we copied all of the valid mappings? */
5394 if (dstmpte->ref_count >= srcmpte->ref_count)
5400 * XXX This barrier may not be needed because the destination pmap is
5407 PMAP_UNLOCK(src_pmap);
5408 PMAP_UNLOCK(dst_pmap);
5412 * pmap_zero_page zeros the specified hardware page by mapping
5413 * the page into KVM and using bzero to clear its contents.
5416 pmap_zero_page(vm_page_t m)
5418 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5420 pagezero((void *)va);
5424 * pmap_zero_page_area zeros the specified hardware page by mapping
5425 * the page into KVM and using bzero to clear its contents.
5427 * off and size may not cover an area beyond a single hardware page.
5430 pmap_zero_page_area(vm_page_t m, int off, int size)
5432 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5434 if (off == 0 && size == PAGE_SIZE)
5435 pagezero((void *)va);
5437 bzero((char *)va + off, size);
5441 * pmap_copy_page copies the specified (machine independent)
5442 * page by mapping the page into virtual memory and using
5443 * bcopy to copy the page, one machine dependent page at a
5447 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5449 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5450 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5452 pagecopy((void *)src, (void *)dst);
5455 int unmapped_buf_allowed = 1;
5458 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5459 vm_offset_t b_offset, int xfersize)
5463 vm_paddr_t p_a, p_b;
5464 vm_offset_t a_pg_offset, b_pg_offset;
5467 while (xfersize > 0) {
5468 a_pg_offset = a_offset & PAGE_MASK;
5469 m_a = ma[a_offset >> PAGE_SHIFT];
5470 p_a = m_a->phys_addr;
5471 b_pg_offset = b_offset & PAGE_MASK;
5472 m_b = mb[b_offset >> PAGE_SHIFT];
5473 p_b = m_b->phys_addr;
5474 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5475 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5476 if (__predict_false(!PHYS_IN_DMAP(p_a))) {
5477 panic("!DMAP a %lx", p_a);
5479 a_cp = (char *)PHYS_TO_DMAP(p_a) + a_pg_offset;
5481 if (__predict_false(!PHYS_IN_DMAP(p_b))) {
5482 panic("!DMAP b %lx", p_b);
5484 b_cp = (char *)PHYS_TO_DMAP(p_b) + b_pg_offset;
5486 bcopy(a_cp, b_cp, cnt);
5494 pmap_quick_enter_page(vm_page_t m)
5497 return (PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)));
5501 pmap_quick_remove_page(vm_offset_t addr)
5506 * Returns true if the pmap's pv is one of the first
5507 * 16 pvs linked to from this page. This count may
5508 * be changed upwards or downwards in the future; it
5509 * is only necessary that true be returned for a small
5510 * subset of pmaps for proper page aging.
5513 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5515 struct md_page *pvh;
5516 struct rwlock *lock;
5521 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5522 ("pmap_page_exists_quick: page %p is not managed", m));
5524 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5526 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5527 if (PV_PMAP(pv) == pmap) {
5535 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5536 pvh = page_to_pvh(m);
5537 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5538 if (PV_PMAP(pv) == pmap) {
5552 * pmap_page_wired_mappings:
5554 * Return the number of managed mappings to the given physical page
5558 pmap_page_wired_mappings(vm_page_t m)
5560 struct rwlock *lock;
5561 struct md_page *pvh;
5565 int count, md_gen, pvh_gen;
5567 if ((m->oflags & VPO_UNMANAGED) != 0)
5569 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5573 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5575 if (!PMAP_TRYLOCK(pmap)) {
5576 md_gen = m->md.pv_gen;
5580 if (md_gen != m->md.pv_gen) {
5585 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
5586 if ((pmap_load(pte) & ATTR_SW_WIRED) != 0)
5590 if ((m->flags & PG_FICTITIOUS) == 0) {
5591 pvh = page_to_pvh(m);
5592 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5594 if (!PMAP_TRYLOCK(pmap)) {
5595 md_gen = m->md.pv_gen;
5596 pvh_gen = pvh->pv_gen;
5600 if (md_gen != m->md.pv_gen ||
5601 pvh_gen != pvh->pv_gen) {
5606 pte = pmap_pte_exists(pmap, pv->pv_va, 2, __func__);
5607 if ((pmap_load(pte) & ATTR_SW_WIRED) != 0)
5617 * Returns true if the given page is mapped individually or as part of
5618 * a 2mpage. Otherwise, returns false.
5621 pmap_page_is_mapped(vm_page_t m)
5623 struct rwlock *lock;
5626 if ((m->oflags & VPO_UNMANAGED) != 0)
5628 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5630 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5631 ((m->flags & PG_FICTITIOUS) == 0 &&
5632 !TAILQ_EMPTY(&page_to_pvh(m)->pv_list));
5638 * Destroy all managed, non-wired mappings in the given user-space
5639 * pmap. This pmap cannot be active on any processor besides the
5642 * This function cannot be applied to the kernel pmap. Moreover, it
5643 * is not intended for general use. It is only to be used during
5644 * process termination. Consequently, it can be implemented in ways
5645 * that make it faster than pmap_remove(). First, it can more quickly
5646 * destroy mappings by iterating over the pmap's collection of PV
5647 * entries, rather than searching the page table. Second, it doesn't
5648 * have to test and clear the page table entries atomically, because
5649 * no processor is currently accessing the user address space. In
5650 * particular, a page table entry's dirty bit won't change state once
5651 * this function starts.
5654 pmap_remove_pages(pmap_t pmap)
5657 pt_entry_t *pte, tpte;
5658 struct spglist free;
5659 struct pv_chunklist free_chunks[PMAP_MEMDOM];
5660 vm_page_t m, ml3, mt;
5662 struct md_page *pvh;
5663 struct pv_chunk *pc, *npc;
5664 struct rwlock *lock;
5666 uint64_t inuse, bitmask;
5667 int allfree, field, i, idx, lvl;
5673 for (i = 0; i < PMAP_MEMDOM; i++)
5674 TAILQ_INIT(&free_chunks[i]);
5677 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5680 for (field = 0; field < _NPCM; field++) {
5681 inuse = ~pc->pc_map[field] & pc_freemask[field];
5682 while (inuse != 0) {
5683 bit = ffsl(inuse) - 1;
5684 bitmask = 1UL << bit;
5685 idx = field * 64 + bit;
5686 pv = &pc->pc_pventry[idx];
5689 pde = pmap_pde(pmap, pv->pv_va, &lvl);
5690 KASSERT(pde != NULL,
5691 ("Attempting to remove an unmapped page"));
5695 pte = pmap_l1_to_l2(pde, pv->pv_va);
5696 tpte = pmap_load(pte);
5697 KASSERT((tpte & ATTR_DESCR_MASK) ==
5699 ("Attempting to remove an invalid "
5700 "block: %lx", tpte));
5703 pte = pmap_l2_to_l3(pde, pv->pv_va);
5704 tpte = pmap_load(pte);
5705 KASSERT((tpte & ATTR_DESCR_MASK) ==
5707 ("Attempting to remove an invalid "
5708 "page: %lx", tpte));
5712 "Invalid page directory level: %d",
5717 * We cannot remove wired pages from a process' mapping at this time
5719 if (tpte & ATTR_SW_WIRED) {
5725 pc->pc_map[field] |= bitmask;
5728 * Because this pmap is not active on other
5729 * processors, the dirty bit cannot have
5730 * changed state since we last loaded pte.
5734 pa = PTE_TO_PHYS(tpte);
5736 m = PHYS_TO_VM_PAGE(pa);
5737 KASSERT(m->phys_addr == pa,
5738 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5739 m, (uintmax_t)m->phys_addr,
5742 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5743 m < &vm_page_array[vm_page_array_size],
5744 ("pmap_remove_pages: bad pte %#jx",
5748 * Update the vm_page_t clean/reference bits.
5750 if (pmap_pte_dirty(pmap, tpte)) {
5753 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
5762 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5766 pmap_resident_count_dec(pmap,
5767 L2_SIZE / PAGE_SIZE);
5768 pvh = page_to_pvh(m);
5769 TAILQ_REMOVE(&pvh->pv_list, pv,pv_next);
5771 if (TAILQ_EMPTY(&pvh->pv_list)) {
5772 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
5773 if ((mt->a.flags & PGA_WRITEABLE) != 0 &&
5774 TAILQ_EMPTY(&mt->md.pv_list))
5775 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5777 ml3 = pmap_remove_pt_page(pmap,
5780 KASSERT(vm_page_any_valid(ml3),
5781 ("pmap_remove_pages: l3 page not promoted"));
5782 pmap_resident_count_dec(pmap,1);
5783 KASSERT(ml3->ref_count == NL3PG,
5784 ("pmap_remove_pages: l3 page ref count error"));
5786 pmap_add_delayed_free_list(ml3,
5791 pmap_resident_count_dec(pmap, 1);
5792 TAILQ_REMOVE(&m->md.pv_list, pv,
5795 if ((m->a.flags & PGA_WRITEABLE) != 0 &&
5796 TAILQ_EMPTY(&m->md.pv_list) &&
5797 (m->flags & PG_FICTITIOUS) == 0) {
5798 pvh = page_to_pvh(m);
5799 if (TAILQ_EMPTY(&pvh->pv_list))
5800 vm_page_aflag_clear(m,
5805 pmap_unuse_pt(pmap, pv->pv_va, pmap_load(pde),
5810 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5811 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5812 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5814 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5815 TAILQ_INSERT_TAIL(&free_chunks[pc_to_domain(pc)], pc,
5821 pmap_invalidate_all(pmap);
5822 free_pv_chunk_batch(free_chunks);
5824 vm_page_free_pages_toq(&free, true);
5828 * This is used to check if a page has been accessed or modified.
5831 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
5833 struct rwlock *lock;
5835 struct md_page *pvh;
5836 pt_entry_t *pte, mask, value;
5838 int md_gen, pvh_gen;
5842 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5845 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5847 PMAP_ASSERT_STAGE1(pmap);
5848 if (!PMAP_TRYLOCK(pmap)) {
5849 md_gen = m->md.pv_gen;
5853 if (md_gen != m->md.pv_gen) {
5858 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
5862 mask |= ATTR_S1_AP_RW_BIT;
5863 value |= ATTR_S1_AP(ATTR_S1_AP_RW);
5866 mask |= ATTR_AF | ATTR_DESCR_MASK;
5867 value |= ATTR_AF | L3_PAGE;
5869 rv = (pmap_load(pte) & mask) == value;
5874 if ((m->flags & PG_FICTITIOUS) == 0) {
5875 pvh = page_to_pvh(m);
5876 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5878 PMAP_ASSERT_STAGE1(pmap);
5879 if (!PMAP_TRYLOCK(pmap)) {
5880 md_gen = m->md.pv_gen;
5881 pvh_gen = pvh->pv_gen;
5885 if (md_gen != m->md.pv_gen ||
5886 pvh_gen != pvh->pv_gen) {
5891 pte = pmap_pte_exists(pmap, pv->pv_va, 2, __func__);
5895 mask |= ATTR_S1_AP_RW_BIT;
5896 value |= ATTR_S1_AP(ATTR_S1_AP_RW);
5899 mask |= ATTR_AF | ATTR_DESCR_MASK;
5900 value |= ATTR_AF | L2_BLOCK;
5902 rv = (pmap_load(pte) & mask) == value;
5916 * Return whether or not the specified physical page was modified
5917 * in any physical maps.
5920 pmap_is_modified(vm_page_t m)
5923 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5924 ("pmap_is_modified: page %p is not managed", m));
5927 * If the page is not busied then this check is racy.
5929 if (!pmap_page_is_write_mapped(m))
5931 return (pmap_page_test_mappings(m, FALSE, TRUE));
5935 * pmap_is_prefaultable:
5937 * Return whether or not the specified virtual address is eligible
5941 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
5949 * Return TRUE if and only if the L3 entry for the specified virtual
5950 * address is allocated but invalid.
5954 pde = pmap_pde(pmap, addr, &lvl);
5955 if (pde != NULL && lvl == 2) {
5956 pte = pmap_l2_to_l3(pde, addr);
5957 rv = pmap_load(pte) == 0;
5964 * pmap_is_referenced:
5966 * Return whether or not the specified physical page was referenced
5967 * in any physical maps.
5970 pmap_is_referenced(vm_page_t m)
5973 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5974 ("pmap_is_referenced: page %p is not managed", m));
5975 return (pmap_page_test_mappings(m, TRUE, FALSE));
5979 * Clear the write and modified bits in each of the given page's mappings.
5982 pmap_remove_write(vm_page_t m)
5984 struct md_page *pvh;
5986 struct rwlock *lock;
5987 pv_entry_t next_pv, pv;
5988 pt_entry_t oldpte, *pte, set, clear, mask, val;
5990 int md_gen, pvh_gen;
5992 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5993 ("pmap_remove_write: page %p is not managed", m));
5994 vm_page_assert_busied(m);
5996 if (!pmap_page_is_write_mapped(m))
5998 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5999 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
6002 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6004 PMAP_ASSERT_STAGE1(pmap);
6005 if (!PMAP_TRYLOCK(pmap)) {
6006 pvh_gen = pvh->pv_gen;
6010 if (pvh_gen != pvh->pv_gen) {
6016 pte = pmap_pte_exists(pmap, va, 2, __func__);
6017 if ((pmap_load(pte) & ATTR_SW_DBM) != 0)
6018 (void)pmap_demote_l2_locked(pmap, pte, va, &lock);
6019 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6020 ("inconsistent pv lock %p %p for page %p",
6021 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6024 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6026 if (!PMAP_TRYLOCK(pmap)) {
6027 pvh_gen = pvh->pv_gen;
6028 md_gen = m->md.pv_gen;
6032 if (pvh_gen != pvh->pv_gen ||
6033 md_gen != m->md.pv_gen) {
6038 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
6039 oldpte = pmap_load(pte);
6040 if ((oldpte & ATTR_SW_DBM) != 0) {
6041 if (pmap->pm_stage == PM_STAGE1) {
6042 set = ATTR_S1_AP_RW_BIT;
6044 mask = ATTR_S1_AP_RW_BIT;
6045 val = ATTR_S1_AP(ATTR_S1_AP_RW);
6048 clear = ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
6049 mask = ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
6050 val = ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
6052 clear |= ATTR_SW_DBM;
6053 while (!atomic_fcmpset_64(pte, &oldpte,
6054 (oldpte | set) & ~clear))
6057 if ((oldpte & mask) == val)
6059 pmap_invalidate_page(pmap, pv->pv_va, true);
6064 vm_page_aflag_clear(m, PGA_WRITEABLE);
6068 * pmap_ts_referenced:
6070 * Return a count of reference bits for a page, clearing those bits.
6071 * It is not necessary for every reference bit to be cleared, but it
6072 * is necessary that 0 only be returned when there are truly no
6073 * reference bits set.
6075 * As an optimization, update the page's dirty field if a modified bit is
6076 * found while counting reference bits. This opportunistic update can be
6077 * performed at low cost and can eliminate the need for some future calls
6078 * to pmap_is_modified(). However, since this function stops after
6079 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
6080 * dirty pages. Those dirty pages will only be detected by a future call
6081 * to pmap_is_modified().
6084 pmap_ts_referenced(vm_page_t m)
6086 struct md_page *pvh;
6089 struct rwlock *lock;
6090 pt_entry_t *pte, tpte;
6093 int cleared, md_gen, not_cleared, pvh_gen;
6094 struct spglist free;
6096 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6097 ("pmap_ts_referenced: page %p is not managed", m));
6100 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
6101 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6105 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6106 goto small_mappings;
6112 if (!PMAP_TRYLOCK(pmap)) {
6113 pvh_gen = pvh->pv_gen;
6117 if (pvh_gen != pvh->pv_gen) {
6123 pte = pmap_pte_exists(pmap, va, 2, __func__);
6124 tpte = pmap_load(pte);
6125 if (pmap_pte_dirty(pmap, tpte)) {
6127 * Although "tpte" is mapping a 2MB page, because
6128 * this function is called at a 4KB page granularity,
6129 * we only update the 4KB page under test.
6133 if ((tpte & ATTR_AF) != 0) {
6134 pa = VM_PAGE_TO_PHYS(m);
6137 * Since this reference bit is shared by 512 4KB pages,
6138 * it should not be cleared every time it is tested.
6139 * Apply a simple "hash" function on the physical page
6140 * number, the virtual superpage number, and the pmap
6141 * address to select one 4KB page out of the 512 on
6142 * which testing the reference bit will result in
6143 * clearing that reference bit. This function is
6144 * designed to avoid the selection of the same 4KB page
6145 * for every 2MB page mapping.
6147 * On demotion, a mapping that hasn't been referenced
6148 * is simply destroyed. To avoid the possibility of a
6149 * subsequent page fault on a demoted wired mapping,
6150 * always leave its reference bit set. Moreover,
6151 * since the superpage is wired, the current state of
6152 * its reference bit won't affect page replacement.
6154 if ((((pa >> PAGE_SHIFT) ^ (va >> L2_SHIFT) ^
6155 (uintptr_t)pmap) & (Ln_ENTRIES - 1)) == 0 &&
6156 (tpte & ATTR_SW_WIRED) == 0) {
6157 pmap_clear_bits(pte, ATTR_AF);
6158 pmap_invalidate_page(pmap, va, true);
6164 /* Rotate the PV list if it has more than one entry. */
6165 if (TAILQ_NEXT(pv, pv_next) != NULL) {
6166 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6167 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6170 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6172 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6174 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6181 if (!PMAP_TRYLOCK(pmap)) {
6182 pvh_gen = pvh->pv_gen;
6183 md_gen = m->md.pv_gen;
6187 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6192 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
6193 tpte = pmap_load(pte);
6194 if (pmap_pte_dirty(pmap, tpte))
6196 if ((tpte & ATTR_AF) != 0) {
6197 if ((tpte & ATTR_SW_WIRED) == 0) {
6198 pmap_clear_bits(pte, ATTR_AF);
6199 pmap_invalidate_page(pmap, pv->pv_va, true);
6205 /* Rotate the PV list if it has more than one entry. */
6206 if (TAILQ_NEXT(pv, pv_next) != NULL) {
6207 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6208 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6211 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6212 not_cleared < PMAP_TS_REFERENCED_MAX);
6215 vm_page_free_pages_toq(&free, true);
6216 return (cleared + not_cleared);
6220 * Apply the given advice to the specified range of addresses within the
6221 * given pmap. Depending on the advice, clear the referenced and/or
6222 * modified flags in each mapping and set the mapped page's dirty field.
6225 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6227 struct rwlock *lock;
6228 vm_offset_t va, va_next;
6230 pd_entry_t *l0, *l1, *l2, oldl2;
6231 pt_entry_t *l3, oldl3;
6233 PMAP_ASSERT_STAGE1(pmap);
6235 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6239 for (; sva < eva; sva = va_next) {
6240 l0 = pmap_l0(pmap, sva);
6241 if (pmap_load(l0) == 0) {
6242 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
6248 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
6251 l1 = pmap_l0_to_l1(l0, sva);
6252 if (pmap_load(l1) == 0)
6254 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
6255 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
6259 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
6262 l2 = pmap_l1_to_l2(l1, sva);
6263 oldl2 = pmap_load(l2);
6266 if ((oldl2 & ATTR_DESCR_MASK) == L2_BLOCK) {
6267 if ((oldl2 & ATTR_SW_MANAGED) == 0)
6270 if (!pmap_demote_l2_locked(pmap, l2, sva, &lock)) {
6275 * The 2MB page mapping was destroyed.
6281 * Unless the page mappings are wired, remove the
6282 * mapping to a single page so that a subsequent
6283 * access may repromote. Choosing the last page
6284 * within the address range [sva, min(va_next, eva))
6285 * generally results in more repromotions. Since the
6286 * underlying page table page is fully populated, this
6287 * removal never frees a page table page.
6289 if ((oldl2 & ATTR_SW_WIRED) == 0) {
6295 ("pmap_advise: no address gap"));
6296 l3 = pmap_l2_to_l3(l2, va);
6297 KASSERT(pmap_load(l3) != 0,
6298 ("pmap_advise: invalid PTE"));
6299 pmap_remove_l3(pmap, l3, va, pmap_load(l2),
6305 KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
6306 ("pmap_advise: invalid L2 entry after demotion"));
6310 for (l3 = pmap_l2_to_l3(l2, sva); sva != va_next; l3++,
6312 oldl3 = pmap_load(l3);
6313 if ((oldl3 & (ATTR_SW_MANAGED | ATTR_DESCR_MASK)) !=
6314 (ATTR_SW_MANAGED | L3_PAGE))
6316 else if (pmap_pte_dirty(pmap, oldl3)) {
6317 if (advice == MADV_DONTNEED) {
6319 * Future calls to pmap_is_modified()
6320 * can be avoided by making the page
6323 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(oldl3));
6326 while (!atomic_fcmpset_long(l3, &oldl3,
6327 (oldl3 & ~ATTR_AF) |
6328 ATTR_S1_AP(ATTR_S1_AP_RO)))
6330 } else if ((oldl3 & ATTR_AF) != 0)
6331 pmap_clear_bits(l3, ATTR_AF);
6338 if (va != va_next) {
6339 pmap_s1_invalidate_range(pmap, va, sva, true);
6344 pmap_s1_invalidate_range(pmap, va, sva, true);
6350 * Clear the modify bits on the specified physical page.
6353 pmap_clear_modify(vm_page_t m)
6355 struct md_page *pvh;
6356 struct rwlock *lock;
6358 pv_entry_t next_pv, pv;
6359 pd_entry_t *l2, oldl2;
6360 pt_entry_t *l3, oldl3;
6362 int md_gen, pvh_gen;
6364 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6365 ("pmap_clear_modify: page %p is not managed", m));
6366 vm_page_assert_busied(m);
6368 if (!pmap_page_is_write_mapped(m))
6370 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
6371 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6374 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6376 PMAP_ASSERT_STAGE1(pmap);
6377 if (!PMAP_TRYLOCK(pmap)) {
6378 pvh_gen = pvh->pv_gen;
6382 if (pvh_gen != pvh->pv_gen) {
6388 l2 = pmap_l2(pmap, va);
6389 oldl2 = pmap_load(l2);
6390 /* If oldl2 has ATTR_SW_DBM set, then it is also dirty. */
6391 if ((oldl2 & ATTR_SW_DBM) != 0 &&
6392 pmap_demote_l2_locked(pmap, l2, va, &lock) &&
6393 (oldl2 & ATTR_SW_WIRED) == 0) {
6395 * Write protect the mapping to a single page so that
6396 * a subsequent write access may repromote.
6398 va += VM_PAGE_TO_PHYS(m) - PTE_TO_PHYS(oldl2);
6399 l3 = pmap_l2_to_l3(l2, va);
6400 oldl3 = pmap_load(l3);
6401 while (!atomic_fcmpset_long(l3, &oldl3,
6402 (oldl3 & ~ATTR_SW_DBM) | ATTR_S1_AP(ATTR_S1_AP_RO)))
6405 pmap_s1_invalidate_page(pmap, va, true);
6409 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6411 PMAP_ASSERT_STAGE1(pmap);
6412 if (!PMAP_TRYLOCK(pmap)) {
6413 md_gen = m->md.pv_gen;
6414 pvh_gen = pvh->pv_gen;
6418 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6423 l2 = pmap_l2(pmap, pv->pv_va);
6424 l3 = pmap_l2_to_l3(l2, pv->pv_va);
6425 oldl3 = pmap_load(l3);
6426 if ((oldl3 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) == ATTR_SW_DBM){
6427 pmap_set_bits(l3, ATTR_S1_AP(ATTR_S1_AP_RO));
6428 pmap_s1_invalidate_page(pmap, pv->pv_va, true);
6436 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6438 struct pmap_preinit_mapping *ppim;
6439 vm_offset_t va, offset;
6442 int i, lvl, l2_blocks, free_l2_count, start_idx;
6444 if (!vm_initialized) {
6446 * No L3 ptables so map entire L2 blocks where start VA is:
6447 * preinit_map_va + start_idx * L2_SIZE
6448 * There may be duplicate mappings (multiple VA -> same PA) but
6449 * ARM64 dcache is always PIPT so that's acceptable.
6454 /* Calculate how many L2 blocks are needed for the mapping */
6455 l2_blocks = (roundup2(pa + size, L2_SIZE) -
6456 rounddown2(pa, L2_SIZE)) >> L2_SHIFT;
6458 offset = pa & L2_OFFSET;
6460 if (preinit_map_va == 0)
6463 /* Map 2MiB L2 blocks from reserved VA space */
6467 /* Find enough free contiguous VA space */
6468 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6469 ppim = pmap_preinit_mapping + i;
6470 if (free_l2_count > 0 && ppim->pa != 0) {
6471 /* Not enough space here */
6477 if (ppim->pa == 0) {
6479 if (start_idx == -1)
6482 if (free_l2_count == l2_blocks)
6486 if (free_l2_count != l2_blocks)
6487 panic("%s: too many preinit mappings", __func__);
6489 va = preinit_map_va + (start_idx * L2_SIZE);
6490 for (i = start_idx; i < start_idx + l2_blocks; i++) {
6491 /* Mark entries as allocated */
6492 ppim = pmap_preinit_mapping + i;
6494 ppim->va = va + offset;
6499 pa = rounddown2(pa, L2_SIZE);
6500 for (i = 0; i < l2_blocks; i++) {
6501 pde = pmap_pde(kernel_pmap, va, &lvl);
6502 KASSERT(pde != NULL,
6503 ("pmap_mapbios: Invalid page entry, va: 0x%lx",
6506 ("pmap_mapbios: Invalid level %d", lvl));
6508 /* Insert L2_BLOCK */
6509 l2 = pmap_l1_to_l2(pde, va);
6511 PHYS_TO_PTE(pa) | ATTR_DEFAULT | ATTR_S1_XN |
6512 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) | L2_BLOCK);
6517 pmap_s1_invalidate_all(kernel_pmap);
6519 va = preinit_map_va + (start_idx * L2_SIZE);
6522 /* kva_alloc may be used to map the pages */
6523 offset = pa & PAGE_MASK;
6524 size = round_page(offset + size);
6526 va = kva_alloc(size);
6528 panic("%s: Couldn't allocate KVA", __func__);
6530 pde = pmap_pde(kernel_pmap, va, &lvl);
6531 KASSERT(lvl == 2, ("pmap_mapbios: Invalid level %d", lvl));
6533 /* L3 table is linked */
6534 va = trunc_page(va);
6535 pa = trunc_page(pa);
6536 pmap_kenter(va, size, pa, memory_mapping_mode(pa));
6539 return ((void *)(va + offset));
6543 pmap_unmapbios(void *p, vm_size_t size)
6545 struct pmap_preinit_mapping *ppim;
6546 vm_offset_t offset, tmpsize, va, va_trunc;
6549 int i, lvl, l2_blocks, block;
6552 va = (vm_offset_t)p;
6554 (roundup2(va + size, L2_SIZE) - rounddown2(va, L2_SIZE)) >> L2_SHIFT;
6555 KASSERT(l2_blocks > 0, ("pmap_unmapbios: invalid size %lx", size));
6557 /* Remove preinit mapping */
6558 preinit_map = false;
6560 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6561 ppim = pmap_preinit_mapping + i;
6562 if (ppim->va == va) {
6563 KASSERT(ppim->size == size,
6564 ("pmap_unmapbios: size mismatch"));
6569 offset = block * L2_SIZE;
6570 va_trunc = rounddown2(va, L2_SIZE) + offset;
6572 /* Remove L2_BLOCK */
6573 pde = pmap_pde(kernel_pmap, va_trunc, &lvl);
6574 KASSERT(pde != NULL,
6575 ("pmap_unmapbios: Invalid page entry, va: 0x%lx",
6577 l2 = pmap_l1_to_l2(pde, va_trunc);
6580 if (block == (l2_blocks - 1))
6586 pmap_s1_invalidate_all(kernel_pmap);
6590 /* Unmap the pages reserved with kva_alloc. */
6591 if (vm_initialized) {
6592 offset = va & PAGE_MASK;
6593 size = round_page(offset + size);
6594 va = trunc_page(va);
6596 pde = pmap_pde(kernel_pmap, va, &lvl);
6597 KASSERT(pde != NULL,
6598 ("pmap_unmapbios: Invalid page entry, va: 0x%lx", va));
6599 KASSERT(lvl == 2, ("pmap_unmapbios: Invalid level %d", lvl));
6601 /* Unmap and invalidate the pages */
6602 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6603 pmap_kremove(va + tmpsize);
6610 * Sets the memory attribute for the specified page.
6613 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6616 m->md.pv_memattr = ma;
6619 * If "m" is a normal page, update its direct mapping. This update
6620 * can be relied upon to perform any cache operations that are
6621 * required for data coherence.
6623 if ((m->flags & PG_FICTITIOUS) == 0 &&
6624 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6625 m->md.pv_memattr) != 0)
6626 panic("memory attribute change on the direct map failed");
6630 * Changes the specified virtual address range's memory type to that given by
6631 * the parameter "mode". The specified virtual address range must be
6632 * completely contained within either the direct map or the kernel map. If
6633 * the virtual address range is contained within the kernel map, then the
6634 * memory type for each of the corresponding ranges of the direct map is also
6635 * changed. (The corresponding ranges of the direct map are those ranges that
6636 * map the same physical pages as the specified virtual address range.) These
6637 * changes to the direct map are necessary because Intel describes the
6638 * behavior of their processors as "undefined" if two or more mappings to the
6639 * same physical page have different memory types.
6641 * Returns zero if the change completed successfully, and either EINVAL or
6642 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6643 * of the virtual address range was not mapped, and ENOMEM is returned if
6644 * there was insufficient memory available to complete the change. In the
6645 * latter case, the memory type may have been changed on some part of the
6646 * virtual address range or the direct map.
6649 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6653 PMAP_LOCK(kernel_pmap);
6654 error = pmap_change_props_locked(va, size, PROT_NONE, mode, false);
6655 PMAP_UNLOCK(kernel_pmap);
6660 * Changes the specified virtual address range's protections to those
6661 * specified by "prot". Like pmap_change_attr(), protections for aliases
6662 * in the direct map are updated as well. Protections on aliasing mappings may
6663 * be a subset of the requested protections; for example, mappings in the direct
6664 * map are never executable.
6667 pmap_change_prot(vm_offset_t va, vm_size_t size, vm_prot_t prot)
6671 /* Only supported within the kernel map. */
6672 if (va < VM_MIN_KERNEL_ADDRESS)
6675 PMAP_LOCK(kernel_pmap);
6676 error = pmap_change_props_locked(va, size, prot, -1, false);
6677 PMAP_UNLOCK(kernel_pmap);
6682 pmap_change_props_locked(vm_offset_t va, vm_size_t size, vm_prot_t prot,
6683 int mode, bool skip_unmapped)
6685 vm_offset_t base, offset, tmpva;
6688 pt_entry_t pte, *ptep, *newpte;
6689 pt_entry_t bits, mask;
6692 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6693 base = trunc_page(va);
6694 offset = va & PAGE_MASK;
6695 size = round_page(offset + size);
6697 if (!VIRT_IN_DMAP(base) &&
6698 !(base >= VM_MIN_KERNEL_ADDRESS && base < VM_MAX_KERNEL_ADDRESS))
6704 bits = ATTR_S1_IDX(mode);
6705 mask = ATTR_S1_IDX_MASK;
6706 if (mode == VM_MEMATTR_DEVICE) {
6711 if (prot != VM_PROT_NONE) {
6712 /* Don't mark the DMAP as executable. It never is on arm64. */
6713 if (VIRT_IN_DMAP(base)) {
6714 prot &= ~VM_PROT_EXECUTE;
6716 * XXX Mark the DMAP as writable for now. We rely
6717 * on this in ddb & dtrace to insert breakpoint
6720 prot |= VM_PROT_WRITE;
6723 if ((prot & VM_PROT_WRITE) == 0) {
6724 bits |= ATTR_S1_AP(ATTR_S1_AP_RO);
6726 if ((prot & VM_PROT_EXECUTE) == 0) {
6727 bits |= ATTR_S1_PXN;
6729 bits |= ATTR_S1_UXN;
6730 mask |= ATTR_S1_AP_MASK | ATTR_S1_XN;
6733 for (tmpva = base; tmpva < base + size; ) {
6734 ptep = pmap_pte(kernel_pmap, tmpva, &lvl);
6735 if (ptep == NULL && !skip_unmapped) {
6737 } else if ((ptep == NULL && skip_unmapped) ||
6738 (pmap_load(ptep) & mask) == bits) {
6740 * We already have the correct attribute or there
6741 * is no memory mapped at this address and we are
6742 * skipping unmapped memory.
6746 panic("Invalid DMAP table level: %d\n", lvl);
6748 tmpva = (tmpva & ~L1_OFFSET) + L1_SIZE;
6751 tmpva = (tmpva & ~L2_OFFSET) + L2_SIZE;
6758 /* We can't demote/promote this entry */
6759 MPASS((pmap_load(ptep) & ATTR_SW_NO_PROMOTE) == 0);
6762 * Split the entry to an level 3 table, then
6763 * set the new attribute.
6767 panic("Invalid DMAP table level: %d\n", lvl);
6769 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
6770 if ((tmpva & L1_OFFSET) == 0 &&
6771 (base + size - tmpva) >= L1_SIZE) {
6775 newpte = pmap_demote_l1(kernel_pmap, ptep,
6776 tmpva & ~L1_OFFSET);
6779 ptep = pmap_l1_to_l2(ptep, tmpva);
6782 if ((tmpva & L2_OFFSET) == 0 &&
6783 (base + size - tmpva) >= L2_SIZE) {
6787 newpte = pmap_demote_l2(kernel_pmap, ptep,
6791 ptep = pmap_l2_to_l3(ptep, tmpva);
6794 pte_size = PAGE_SIZE;
6798 /* Update the entry */
6799 pte = pmap_load(ptep);
6803 pmap_update_entry(kernel_pmap, ptep, pte, tmpva,
6806 pa = PTE_TO_PHYS(pte);
6807 if (!VIRT_IN_DMAP(tmpva) && PHYS_IN_DMAP(pa)) {
6809 * Keep the DMAP memory in sync.
6811 rv = pmap_change_props_locked(
6812 PHYS_TO_DMAP(pa), pte_size,
6819 * If moving to a non-cacheable entry flush
6822 if (mode == VM_MEMATTR_UNCACHEABLE)
6823 cpu_dcache_wbinv_range(tmpva, pte_size);
6832 * Create an L2 table to map all addresses within an L1 mapping.
6835 pmap_demote_l1(pmap_t pmap, pt_entry_t *l1, vm_offset_t va)
6837 pt_entry_t *l2, newl2, oldl1;
6839 vm_paddr_t l2phys, phys;
6843 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6844 oldl1 = pmap_load(l1);
6845 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
6846 KASSERT((oldl1 & ATTR_DESCR_MASK) == L1_BLOCK,
6847 ("pmap_demote_l1: Demoting a non-block entry"));
6848 KASSERT((va & L1_OFFSET) == 0,
6849 ("pmap_demote_l1: Invalid virtual address %#lx", va));
6850 KASSERT((oldl1 & ATTR_SW_MANAGED) == 0,
6851 ("pmap_demote_l1: Level 1 table shouldn't be managed"));
6852 KASSERT((oldl1 & ATTR_SW_NO_PROMOTE) == 0,
6853 ("pmap_demote_l1: Demoting entry with no-demote flag set"));
6856 if (va <= (vm_offset_t)l1 && va + L1_SIZE > (vm_offset_t)l1) {
6857 tmpl1 = kva_alloc(PAGE_SIZE);
6862 if ((ml2 = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED)) ==
6864 CTR2(KTR_PMAP, "pmap_demote_l1: failure for va %#lx"
6865 " in pmap %p", va, pmap);
6870 l2phys = VM_PAGE_TO_PHYS(ml2);
6871 l2 = (pt_entry_t *)PHYS_TO_DMAP(l2phys);
6873 /* Address the range points at */
6874 phys = PTE_TO_PHYS(oldl1);
6875 /* The attributed from the old l1 table to be copied */
6876 newl2 = oldl1 & ATTR_MASK;
6878 /* Create the new entries */
6879 for (i = 0; i < Ln_ENTRIES; i++) {
6880 l2[i] = newl2 | phys;
6883 KASSERT(l2[0] == ((oldl1 & ~ATTR_DESCR_MASK) | L2_BLOCK),
6884 ("Invalid l2 page (%lx != %lx)", l2[0],
6885 (oldl1 & ~ATTR_DESCR_MASK) | L2_BLOCK));
6888 pmap_kenter(tmpl1, PAGE_SIZE,
6889 DMAP_TO_PHYS((vm_offset_t)l1) & ~L3_OFFSET,
6890 VM_MEMATTR_WRITE_BACK);
6891 l1 = (pt_entry_t *)(tmpl1 + ((vm_offset_t)l1 & PAGE_MASK));
6894 pmap_update_entry(pmap, l1, l2phys | L1_TABLE, va, PAGE_SIZE);
6898 pmap_kremove(tmpl1);
6899 kva_free(tmpl1, PAGE_SIZE);
6906 pmap_fill_l3(pt_entry_t *firstl3, pt_entry_t newl3)
6910 for (l3 = firstl3; l3 - firstl3 < Ln_ENTRIES; l3++) {
6917 pmap_demote_l2_check(pt_entry_t *firstl3p __unused, pt_entry_t newl3e __unused)
6921 pt_entry_t *xl3p, *yl3p;
6923 for (xl3p = firstl3p; xl3p < firstl3p + Ln_ENTRIES;
6924 xl3p++, newl3e += PAGE_SIZE) {
6925 if (PTE_TO_PHYS(pmap_load(xl3p)) != PTE_TO_PHYS(newl3e)) {
6926 printf("pmap_demote_l2: xl3e %zd and newl3e map "
6927 "different pages: found %#lx, expected %#lx\n",
6928 xl3p - firstl3p, pmap_load(xl3p), newl3e);
6929 printf("page table dump\n");
6930 for (yl3p = firstl3p; yl3p < firstl3p + Ln_ENTRIES;
6932 printf("%zd %#lx\n", yl3p - firstl3p,
6939 KASSERT(PTE_TO_PHYS(pmap_load(firstl3p)) == PTE_TO_PHYS(newl3e),
6940 ("pmap_demote_l2: firstl3 and newl3e map different physical"
6947 pmap_demote_l2_abort(pmap_t pmap, vm_offset_t va, pt_entry_t *l2,
6948 struct rwlock **lockp)
6950 struct spglist free;
6953 (void)pmap_remove_l2(pmap, l2, va, pmap_load(pmap_l1(pmap, va)), &free,
6955 vm_page_free_pages_toq(&free, true);
6959 * Create an L3 table to map all addresses within an L2 mapping.
6962 pmap_demote_l2_locked(pmap_t pmap, pt_entry_t *l2, vm_offset_t va,
6963 struct rwlock **lockp)
6965 pt_entry_t *l3, newl3, oldl2;
6970 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6971 PMAP_ASSERT_STAGE1(pmap);
6972 KASSERT(ADDR_IS_CANONICAL(va),
6973 ("%s: Address not in canonical form: %lx", __func__, va));
6976 oldl2 = pmap_load(l2);
6977 KASSERT((oldl2 & ATTR_DESCR_MASK) == L2_BLOCK,
6978 ("pmap_demote_l2: Demoting a non-block entry"));
6979 KASSERT((oldl2 & ATTR_SW_NO_PROMOTE) == 0,
6980 ("pmap_demote_l2: Demoting entry with no-demote flag set"));
6984 if (va <= (vm_offset_t)l2 && va + L2_SIZE > (vm_offset_t)l2) {
6985 tmpl2 = kva_alloc(PAGE_SIZE);
6991 * Invalidate the 2MB page mapping and return "failure" if the
6992 * mapping was never accessed.
6994 if ((oldl2 & ATTR_AF) == 0) {
6995 KASSERT((oldl2 & ATTR_SW_WIRED) == 0,
6996 ("pmap_demote_l2: a wired mapping is missing ATTR_AF"));
6997 pmap_demote_l2_abort(pmap, va, l2, lockp);
6998 CTR2(KTR_PMAP, "pmap_demote_l2: failure for va %#lx in pmap %p",
7003 if ((ml3 = pmap_remove_pt_page(pmap, va)) == NULL) {
7004 KASSERT((oldl2 & ATTR_SW_WIRED) == 0,
7005 ("pmap_demote_l2: page table page for a wired mapping"
7009 * If the page table page is missing and the mapping
7010 * is for a kernel address, the mapping must belong to
7011 * either the direct map or the early kernel memory.
7012 * Page table pages are preallocated for every other
7013 * part of the kernel address space, so the direct map
7014 * region and early kernel memory are the only parts of the
7015 * kernel address space that must be handled here.
7017 KASSERT(!ADDR_IS_KERNEL(va) || VIRT_IN_DMAP(va) ||
7018 (va >= VM_MIN_KERNEL_ADDRESS && va < kernel_vm_end),
7019 ("pmap_demote_l2: No saved mpte for va %#lx", va));
7022 * If the 2MB page mapping belongs to the direct map
7023 * region of the kernel's address space, then the page
7024 * allocation request specifies the highest possible
7025 * priority (VM_ALLOC_INTERRUPT). Otherwise, the
7026 * priority is normal.
7028 ml3 = vm_page_alloc_noobj(
7029 (VIRT_IN_DMAP(va) ? VM_ALLOC_INTERRUPT : 0) |
7033 * If the allocation of the new page table page fails,
7034 * invalidate the 2MB page mapping and return "failure".
7037 pmap_demote_l2_abort(pmap, va, l2, lockp);
7038 CTR2(KTR_PMAP, "pmap_demote_l2: failure for va %#lx"
7039 " in pmap %p", va, pmap);
7042 ml3->pindex = pmap_l2_pindex(va);
7044 if (!ADDR_IS_KERNEL(va)) {
7045 ml3->ref_count = NL3PG;
7046 pmap_resident_count_inc(pmap, 1);
7049 l3phys = VM_PAGE_TO_PHYS(ml3);
7050 l3 = (pt_entry_t *)PHYS_TO_DMAP(l3phys);
7051 newl3 = (oldl2 & ~ATTR_DESCR_MASK) | L3_PAGE;
7052 KASSERT((oldl2 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) !=
7053 (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM),
7054 ("pmap_demote_l2: L2 entry is writeable but not dirty"));
7057 * If the PTP is not leftover from an earlier promotion or it does not
7058 * have ATTR_AF set in every L3E, then fill it. The new L3Es will all
7061 * When pmap_update_entry() clears the old L2 mapping, it (indirectly)
7062 * performs a dsb(). That dsb() ensures that the stores for filling
7063 * "l3" are visible before "l3" is added to the page table.
7065 if (!vm_page_all_valid(ml3))
7066 pmap_fill_l3(l3, newl3);
7068 pmap_demote_l2_check(l3, newl3);
7071 * If the mapping has changed attributes, update the L3Es.
7073 if ((pmap_load(l3) & (ATTR_MASK & ~ATTR_AF)) != (newl3 & (ATTR_MASK &
7075 pmap_fill_l3(l3, newl3);
7078 * Map the temporary page so we don't lose access to the l2 table.
7081 pmap_kenter(tmpl2, PAGE_SIZE,
7082 DMAP_TO_PHYS((vm_offset_t)l2) & ~L3_OFFSET,
7083 VM_MEMATTR_WRITE_BACK);
7084 l2 = (pt_entry_t *)(tmpl2 + ((vm_offset_t)l2 & PAGE_MASK));
7088 * The spare PV entries must be reserved prior to demoting the
7089 * mapping, that is, prior to changing the PDE. Otherwise, the state
7090 * of the L2 and the PV lists will be inconsistent, which can result
7091 * in reclaim_pv_chunk() attempting to remove a PV entry from the
7092 * wrong PV list and pmap_pv_demote_l2() failing to find the expected
7093 * PV entry for the 2MB page mapping that is being demoted.
7095 if ((oldl2 & ATTR_SW_MANAGED) != 0)
7096 reserve_pv_entries(pmap, Ln_ENTRIES - 1, lockp);
7099 * Pass PAGE_SIZE so that a single TLB invalidation is performed on
7100 * the 2MB page mapping.
7102 pmap_update_entry(pmap, l2, l3phys | L2_TABLE, va, PAGE_SIZE);
7105 * Demote the PV entry.
7107 if ((oldl2 & ATTR_SW_MANAGED) != 0)
7108 pmap_pv_demote_l2(pmap, va, PTE_TO_PHYS(oldl2), lockp);
7110 atomic_add_long(&pmap_l2_demotions, 1);
7111 CTR3(KTR_PMAP, "pmap_demote_l2: success for va %#lx"
7112 " in pmap %p %lx", va, pmap, l3[0]);
7116 pmap_kremove(tmpl2);
7117 kva_free(tmpl2, PAGE_SIZE);
7125 pmap_demote_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va)
7127 struct rwlock *lock;
7131 l3 = pmap_demote_l2_locked(pmap, l2, va, &lock);
7138 * Perform the pmap work for mincore(2). If the page is not both referenced and
7139 * modified by this pmap, returns its physical address so that the caller can
7140 * find other mappings.
7143 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
7145 pt_entry_t *pte, tpte;
7146 vm_paddr_t mask, pa;
7150 PMAP_ASSERT_STAGE1(pmap);
7152 pte = pmap_pte(pmap, addr, &lvl);
7154 tpte = pmap_load(pte);
7167 panic("pmap_mincore: invalid level %d", lvl);
7170 managed = (tpte & ATTR_SW_MANAGED) != 0;
7171 val = MINCORE_INCORE;
7173 val |= MINCORE_PSIND(3 - lvl);
7174 if ((managed && pmap_pte_dirty(pmap, tpte)) || (!managed &&
7175 (tpte & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP(ATTR_S1_AP_RW)))
7176 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
7177 if ((tpte & ATTR_AF) == ATTR_AF)
7178 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
7180 pa = PTE_TO_PHYS(tpte) | (addr & mask);
7186 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
7187 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) && managed) {
7195 * Garbage collect every ASID that is neither active on a processor nor
7199 pmap_reset_asid_set(pmap_t pmap)
7202 int asid, cpuid, epoch;
7203 struct asid_set *set;
7204 enum pmap_stage stage;
7206 set = pmap->pm_asid_set;
7207 stage = pmap->pm_stage;
7209 set = pmap->pm_asid_set;
7210 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
7211 mtx_assert(&set->asid_set_mutex, MA_OWNED);
7214 * Ensure that the store to asid_epoch is globally visible before the
7215 * loads from pc_curpmap are performed.
7217 epoch = set->asid_epoch + 1;
7218 if (epoch == INT_MAX)
7220 set->asid_epoch = epoch;
7222 if (stage == PM_STAGE1) {
7223 __asm __volatile("tlbi vmalle1is");
7225 KASSERT(pmap_clean_stage2_tlbi != NULL,
7226 ("%s: Unset stage 2 tlb invalidation callback\n",
7228 pmap_clean_stage2_tlbi();
7231 bit_nclear(set->asid_set, ASID_FIRST_AVAILABLE,
7232 set->asid_set_size - 1);
7233 CPU_FOREACH(cpuid) {
7234 if (cpuid == curcpu)
7236 if (stage == PM_STAGE1) {
7237 curpmap = pcpu_find(cpuid)->pc_curpmap;
7238 PMAP_ASSERT_STAGE1(pmap);
7240 curpmap = pcpu_find(cpuid)->pc_curvmpmap;
7241 if (curpmap == NULL)
7243 PMAP_ASSERT_STAGE2(pmap);
7245 KASSERT(curpmap->pm_asid_set == set, ("Incorrect set"));
7246 asid = COOKIE_TO_ASID(curpmap->pm_cookie);
7249 bit_set(set->asid_set, asid);
7250 curpmap->pm_cookie = COOKIE_FROM(asid, epoch);
7255 * Allocate a new ASID for the specified pmap.
7258 pmap_alloc_asid(pmap_t pmap)
7260 struct asid_set *set;
7263 set = pmap->pm_asid_set;
7264 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
7266 mtx_lock_spin(&set->asid_set_mutex);
7269 * While this processor was waiting to acquire the asid set mutex,
7270 * pmap_reset_asid_set() running on another processor might have
7271 * updated this pmap's cookie to the current epoch. In which case, we
7272 * don't need to allocate a new ASID.
7274 if (COOKIE_TO_EPOCH(pmap->pm_cookie) == set->asid_epoch)
7277 bit_ffc_at(set->asid_set, set->asid_next, set->asid_set_size,
7279 if (new_asid == -1) {
7280 bit_ffc_at(set->asid_set, ASID_FIRST_AVAILABLE,
7281 set->asid_next, &new_asid);
7282 if (new_asid == -1) {
7283 pmap_reset_asid_set(pmap);
7284 bit_ffc_at(set->asid_set, ASID_FIRST_AVAILABLE,
7285 set->asid_set_size, &new_asid);
7286 KASSERT(new_asid != -1, ("ASID allocation failure"));
7289 bit_set(set->asid_set, new_asid);
7290 set->asid_next = new_asid + 1;
7291 pmap->pm_cookie = COOKIE_FROM(new_asid, set->asid_epoch);
7293 mtx_unlock_spin(&set->asid_set_mutex);
7296 static uint64_t __read_mostly ttbr_flags;
7299 * Compute the value that should be stored in ttbr0 to activate the specified
7300 * pmap. This value may change from time to time.
7303 pmap_to_ttbr0(pmap_t pmap)
7307 ttbr = pmap->pm_ttbr;
7308 ttbr |= ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
7315 pmap_set_cnp(void *arg)
7317 uint64_t ttbr0, ttbr1;
7320 cpuid = *(u_int *)arg;
7321 if (cpuid == curcpu) {
7323 * Set the flags while all CPUs are handling the
7324 * smp_rendezvous so will not call pmap_to_ttbr0. Any calls
7325 * to pmap_to_ttbr0 after this will have the CnP flag set.
7326 * The dsb after invalidating the TLB will act as a barrier
7327 * to ensure all CPUs can observe this change.
7329 ttbr_flags |= TTBR_CnP;
7332 ttbr0 = READ_SPECIALREG(ttbr0_el1);
7335 ttbr1 = READ_SPECIALREG(ttbr1_el1);
7338 /* Update ttbr{0,1}_el1 with the CnP flag */
7339 WRITE_SPECIALREG(ttbr0_el1, ttbr0);
7340 WRITE_SPECIALREG(ttbr1_el1, ttbr1);
7342 __asm __volatile("tlbi vmalle1is");
7348 * Defer enabling CnP until we have read the ID registers to know if it's
7349 * supported on all CPUs.
7352 pmap_init_cnp(void *dummy __unused)
7357 if (!get_kernel_reg(ID_AA64MMFR2_EL1, ®))
7360 if (ID_AA64MMFR2_CnP_VAL(reg) != ID_AA64MMFR2_CnP_NONE) {
7362 printf("Enabling CnP\n");
7364 smp_rendezvous(NULL, pmap_set_cnp, NULL, &cpuid);
7368 SYSINIT(pmap_init_cnp, SI_SUB_SMP, SI_ORDER_ANY, pmap_init_cnp, NULL);
7371 pmap_activate_int(pmap_t pmap)
7373 struct asid_set *set;
7376 KASSERT(PCPU_GET(curpmap) != NULL, ("no active pmap"));
7377 KASSERT(pmap != kernel_pmap, ("kernel pmap activation"));
7379 if ((pmap->pm_stage == PM_STAGE1 && pmap == PCPU_GET(curpmap)) ||
7380 (pmap->pm_stage == PM_STAGE2 && pmap == PCPU_GET(curvmpmap))) {
7382 * Handle the possibility that the old thread was preempted
7383 * after an "ic" or "tlbi" instruction but before it performed
7384 * a "dsb" instruction. If the old thread migrates to a new
7385 * processor, its completion of a "dsb" instruction on that
7386 * new processor does not guarantee that the "ic" or "tlbi"
7387 * instructions performed on the old processor have completed.
7393 set = pmap->pm_asid_set;
7394 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
7397 * Ensure that the store to curpmap is globally visible before the
7398 * load from asid_epoch is performed.
7400 if (pmap->pm_stage == PM_STAGE1)
7401 PCPU_SET(curpmap, pmap);
7403 PCPU_SET(curvmpmap, pmap);
7405 epoch = COOKIE_TO_EPOCH(pmap->pm_cookie);
7406 if (epoch >= 0 && epoch != set->asid_epoch)
7407 pmap_alloc_asid(pmap);
7409 if (pmap->pm_stage == PM_STAGE1) {
7410 set_ttbr0(pmap_to_ttbr0(pmap));
7411 if (PCPU_GET(bcast_tlbi_workaround) != 0)
7412 invalidate_local_icache();
7418 pmap_activate_vm(pmap_t pmap)
7421 PMAP_ASSERT_STAGE2(pmap);
7423 (void)pmap_activate_int(pmap);
7427 pmap_activate(struct thread *td)
7431 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7432 PMAP_ASSERT_STAGE1(pmap);
7434 (void)pmap_activate_int(pmap);
7439 * Activate the thread we are switching to.
7440 * To simplify the assembly in cpu_throw return the new threads pcb.
7443 pmap_switch(struct thread *new)
7445 pcpu_bp_harden bp_harden;
7448 /* Store the new curthread */
7449 PCPU_SET(curthread, new);
7451 /* And the new pcb */
7453 PCPU_SET(curpcb, pcb);
7456 * TODO: We may need to flush the cache here if switching
7457 * to a user process.
7460 if (pmap_activate_int(vmspace_pmap(new->td_proc->p_vmspace))) {
7462 * Stop userspace from training the branch predictor against
7463 * other processes. This will call into a CPU specific
7464 * function that clears the branch predictor state.
7466 bp_harden = PCPU_GET(bp_harden);
7467 if (bp_harden != NULL)
7475 pmap_sync_icache(pmap_t pmap, vm_offset_t va, vm_size_t sz)
7478 PMAP_ASSERT_STAGE1(pmap);
7479 KASSERT(ADDR_IS_CANONICAL(va),
7480 ("%s: Address not in canonical form: %lx", __func__, va));
7482 if (ADDR_IS_KERNEL(va)) {
7483 cpu_icache_sync_range(va, sz);
7488 /* Find the length of data in this page to flush */
7489 offset = va & PAGE_MASK;
7490 len = imin(PAGE_SIZE - offset, sz);
7493 /* Extract the physical address & find it in the DMAP */
7494 pa = pmap_extract(pmap, va);
7496 cpu_icache_sync_range(PHYS_TO_DMAP(pa), len);
7498 /* Move to the next page */
7501 /* Set the length for the next iteration */
7502 len = imin(PAGE_SIZE, sz);
7508 pmap_stage2_fault(pmap_t pmap, uint64_t esr, uint64_t far)
7511 pt_entry_t *ptep, pte;
7514 PMAP_ASSERT_STAGE2(pmap);
7517 /* Data and insn aborts use same encoding for FSC field. */
7518 dfsc = esr & ISS_DATA_DFSC_MASK;
7520 case ISS_DATA_DFSC_TF_L0:
7521 case ISS_DATA_DFSC_TF_L1:
7522 case ISS_DATA_DFSC_TF_L2:
7523 case ISS_DATA_DFSC_TF_L3:
7525 pdep = pmap_pde(pmap, far, &lvl);
7526 if (pdep == NULL || lvl != (dfsc - ISS_DATA_DFSC_TF_L1)) {
7533 ptep = pmap_l0_to_l1(pdep, far);
7536 ptep = pmap_l1_to_l2(pdep, far);
7539 ptep = pmap_l2_to_l3(pdep, far);
7542 panic("%s: Invalid pde level %d", __func__,lvl);
7546 case ISS_DATA_DFSC_AFF_L1:
7547 case ISS_DATA_DFSC_AFF_L2:
7548 case ISS_DATA_DFSC_AFF_L3:
7550 ptep = pmap_pte(pmap, far, &lvl);
7552 if (ptep != NULL && (pte = pmap_load(ptep)) != 0) {
7554 pmap_invalidate_vpipt_icache();
7557 * If accessing an executable page invalidate
7558 * the I-cache so it will be valid when we
7559 * continue execution in the guest. The D-cache
7560 * is assumed to already be clean to the Point
7563 if ((pte & ATTR_S2_XN_MASK) !=
7564 ATTR_S2_XN(ATTR_S2_XN_NONE)) {
7565 invalidate_icache();
7568 pmap_set_bits(ptep, ATTR_AF | ATTR_DESCR_VALID);
7579 pmap_fault(pmap_t pmap, uint64_t esr, uint64_t far)
7581 pt_entry_t pte, *ptep;
7588 ec = ESR_ELx_EXCEPTION(esr);
7590 case EXCP_INSN_ABORT_L:
7591 case EXCP_INSN_ABORT:
7592 case EXCP_DATA_ABORT_L:
7593 case EXCP_DATA_ABORT:
7599 if (pmap->pm_stage == PM_STAGE2)
7600 return (pmap_stage2_fault(pmap, esr, far));
7602 /* Data and insn aborts use same encoding for FSC field. */
7603 switch (esr & ISS_DATA_DFSC_MASK) {
7604 case ISS_DATA_DFSC_AFF_L1:
7605 case ISS_DATA_DFSC_AFF_L2:
7606 case ISS_DATA_DFSC_AFF_L3:
7608 ptep = pmap_pte(pmap, far, &lvl);
7610 pmap_set_bits(ptep, ATTR_AF);
7613 * XXXMJ as an optimization we could mark the entry
7614 * dirty if this is a write fault.
7619 case ISS_DATA_DFSC_PF_L1:
7620 case ISS_DATA_DFSC_PF_L2:
7621 case ISS_DATA_DFSC_PF_L3:
7622 if ((ec != EXCP_DATA_ABORT_L && ec != EXCP_DATA_ABORT) ||
7623 (esr & ISS_DATA_WnR) == 0)
7626 ptep = pmap_pte(pmap, far, &lvl);
7628 ((pte = pmap_load(ptep)) & ATTR_SW_DBM) != 0) {
7629 if ((pte & ATTR_S1_AP_RW_BIT) ==
7630 ATTR_S1_AP(ATTR_S1_AP_RO)) {
7631 pmap_clear_bits(ptep, ATTR_S1_AP_RW_BIT);
7632 pmap_s1_invalidate_page(pmap, far, true);
7638 case ISS_DATA_DFSC_TF_L0:
7639 case ISS_DATA_DFSC_TF_L1:
7640 case ISS_DATA_DFSC_TF_L2:
7641 case ISS_DATA_DFSC_TF_L3:
7643 * Retry the translation. A break-before-make sequence can
7644 * produce a transient fault.
7646 if (pmap == kernel_pmap) {
7648 * The translation fault may have occurred within a
7649 * critical section. Therefore, we must check the
7650 * address without acquiring the kernel pmap's lock.
7652 if (pmap_klookup(far, NULL))
7656 /* Ask the MMU to check the address. */
7657 intr = intr_disable();
7658 par = arm64_address_translate_s1e0r(far);
7663 * If the translation was successful, then we can
7664 * return success to the trap handler.
7666 if (PAR_SUCCESS(par))
7676 * Increase the starting virtual address of the given mapping if a
7677 * different alignment might result in more superpage mappings.
7680 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7681 vm_offset_t *addr, vm_size_t size)
7683 vm_offset_t superpage_offset;
7687 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7688 offset += ptoa(object->pg_color);
7689 superpage_offset = offset & L2_OFFSET;
7690 if (size - ((L2_SIZE - superpage_offset) & L2_OFFSET) < L2_SIZE ||
7691 (*addr & L2_OFFSET) == superpage_offset)
7693 if ((*addr & L2_OFFSET) < superpage_offset)
7694 *addr = (*addr & ~L2_OFFSET) + superpage_offset;
7696 *addr = ((*addr + L2_OFFSET) & ~L2_OFFSET) + superpage_offset;
7700 * Get the kernel virtual address of a set of physical pages. If there are
7701 * physical addresses not covered by the DMAP perform a transient mapping
7702 * that will be removed when calling pmap_unmap_io_transient.
7704 * \param page The pages the caller wishes to obtain the virtual
7705 * address on the kernel memory map.
7706 * \param vaddr On return contains the kernel virtual memory address
7707 * of the pages passed in the page parameter.
7708 * \param count Number of pages passed in.
7709 * \param can_fault true if the thread using the mapped pages can take
7710 * page faults, false otherwise.
7712 * \returns true if the caller must call pmap_unmap_io_transient when
7713 * finished or false otherwise.
7717 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7722 int error __diagused, i;
7725 * Allocate any KVA space that we need, this is done in a separate
7726 * loop to prevent calling vmem_alloc while pinned.
7728 needs_mapping = false;
7729 for (i = 0; i < count; i++) {
7730 paddr = VM_PAGE_TO_PHYS(page[i]);
7731 if (__predict_false(!PHYS_IN_DMAP(paddr))) {
7732 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7733 M_BESTFIT | M_WAITOK, &vaddr[i]);
7734 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7735 needs_mapping = true;
7737 vaddr[i] = PHYS_TO_DMAP(paddr);
7741 /* Exit early if everything is covered by the DMAP */
7747 for (i = 0; i < count; i++) {
7748 paddr = VM_PAGE_TO_PHYS(page[i]);
7749 if (!PHYS_IN_DMAP(paddr)) {
7751 "pmap_map_io_transient: TODO: Map out of DMAP data");
7755 return (needs_mapping);
7759 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7767 for (i = 0; i < count; i++) {
7768 paddr = VM_PAGE_TO_PHYS(page[i]);
7769 if (!PHYS_IN_DMAP(paddr)) {
7770 panic("ARM64TODO: pmap_unmap_io_transient: Unmap data");
7776 pmap_is_valid_memattr(pmap_t pmap __unused, vm_memattr_t mode)
7779 return (mode >= VM_MEMATTR_DEVICE && mode <= VM_MEMATTR_WRITE_THROUGH);
7783 static vm_paddr_t pmap_san_early_kernstart;
7784 static pd_entry_t *pmap_san_early_l2;
7786 void __nosanitizeaddress
7787 pmap_san_bootstrap(struct arm64_bootparams *abp)
7790 pmap_san_early_kernstart = KERNBASE - abp->kern_delta;
7791 kasan_init_early(abp->kern_stack, KSTACK_PAGES * PAGE_SIZE);
7794 #define SAN_BOOTSTRAP_L2_SIZE (1 * L2_SIZE)
7795 #define SAN_BOOTSTRAP_SIZE (2 * PAGE_SIZE)
7796 static vm_offset_t __nosanitizeaddress
7797 pmap_san_enter_bootstrap_alloc_l2(void)
7799 static uint8_t bootstrap_data[SAN_BOOTSTRAP_L2_SIZE] __aligned(L2_SIZE);
7800 static size_t offset = 0;
7803 if (offset + L2_SIZE > sizeof(bootstrap_data)) {
7804 panic("%s: out of memory for the bootstrap shadow map L2 entries",
7808 addr = (uintptr_t)&bootstrap_data[offset];
7814 * SAN L1 + L2 pages, maybe L3 entries later?
7816 static vm_offset_t __nosanitizeaddress
7817 pmap_san_enter_bootstrap_alloc_pages(int npages)
7819 static uint8_t bootstrap_data[SAN_BOOTSTRAP_SIZE] __aligned(PAGE_SIZE);
7820 static size_t offset = 0;
7823 if (offset + (npages * PAGE_SIZE) > sizeof(bootstrap_data)) {
7824 panic("%s: out of memory for the bootstrap shadow map",
7828 addr = (uintptr_t)&bootstrap_data[offset];
7829 offset += (npages * PAGE_SIZE);
7833 static void __nosanitizeaddress
7834 pmap_san_enter_bootstrap(void)
7836 vm_offset_t freemempos;
7839 freemempos = pmap_san_enter_bootstrap_alloc_pages(2);
7840 bs_state.freemempos = freemempos;
7841 bs_state.va = KASAN_MIN_ADDRESS;
7842 pmap_bootstrap_l1_table(&bs_state);
7843 pmap_san_early_l2 = bs_state.l2;
7847 pmap_san_enter_alloc_l3(void)
7851 m = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED |
7854 panic("%s: no memory to grow shadow map", __func__);
7859 pmap_san_enter_alloc_l2(void)
7861 return (vm_page_alloc_noobj_contig(VM_ALLOC_WIRED | VM_ALLOC_ZERO,
7862 Ln_ENTRIES, 0, ~0ul, L2_SIZE, 0, VM_MEMATTR_DEFAULT));
7865 void __nosanitizeaddress
7866 pmap_san_enter(vm_offset_t va)
7868 pd_entry_t *l1, *l2;
7872 if (virtual_avail == 0) {
7877 /* Temporary shadow map prior to pmap_bootstrap(). */
7878 first = pmap_san_early_l2 == NULL;
7880 pmap_san_enter_bootstrap();
7882 l2 = pmap_san_early_l2;
7883 slot = pmap_l2_index(va);
7885 if ((pmap_load(&l2[slot]) & ATTR_DESCR_VALID) == 0) {
7887 block = pmap_san_enter_bootstrap_alloc_l2();
7888 pmap_store(&l2[slot],
7889 PHYS_TO_PTE(pmap_early_vtophys(block)) |
7890 PMAP_SAN_PTE_BITS | L2_BLOCK);
7897 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
7898 l1 = pmap_l1(kernel_pmap, va);
7900 if ((pmap_load(l1) & ATTR_DESCR_VALID) == 0) {
7901 m = pmap_san_enter_alloc_l3();
7902 pmap_store(l1, PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) | L1_TABLE);
7904 l2 = pmap_l1_to_l2(l1, va);
7905 if ((pmap_load(l2) & ATTR_DESCR_VALID) == 0) {
7906 m = pmap_san_enter_alloc_l2();
7908 pmap_store(l2, PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) |
7909 PMAP_SAN_PTE_BITS | L2_BLOCK);
7911 m = pmap_san_enter_alloc_l3();
7912 pmap_store(l2, PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) |
7917 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK)
7919 l3 = pmap_l2_to_l3(l2, va);
7920 if ((pmap_load(l3) & ATTR_DESCR_VALID) != 0)
7922 m = pmap_san_enter_alloc_l3();
7923 pmap_store(l3, PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) |
7924 PMAP_SAN_PTE_BITS | L3_PAGE);
7930 * Track a range of the kernel's virtual address space that is contiguous
7931 * in various mapping attributes.
7933 struct pmap_kernel_map_range {
7943 sysctl_kmaps_dump(struct sbuf *sb, struct pmap_kernel_map_range *range,
7949 if (eva <= range->sva)
7952 index = range->attrs & ATTR_S1_IDX_MASK;
7954 case ATTR_S1_IDX(VM_MEMATTR_DEVICE_NP):
7957 case ATTR_S1_IDX(VM_MEMATTR_DEVICE):
7960 case ATTR_S1_IDX(VM_MEMATTR_UNCACHEABLE):
7963 case ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK):
7966 case ATTR_S1_IDX(VM_MEMATTR_WRITE_THROUGH):
7971 "%s: unknown memory type %x for range 0x%016lx-0x%016lx\n",
7972 __func__, index, range->sva, eva);
7977 sbuf_printf(sb, "0x%016lx-0x%016lx r%c%c%c%c %6s %d %d %d %d\n",
7979 (range->attrs & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP_RW ? 'w' : '-',
7980 (range->attrs & ATTR_S1_PXN) != 0 ? '-' : 'x',
7981 (range->attrs & ATTR_S1_UXN) != 0 ? '-' : 'X',
7982 (range->attrs & ATTR_S1_AP(ATTR_S1_AP_USER)) != 0 ? 'u' : 's',
7983 mode, range->l1blocks, range->l2blocks, range->l3contig,
7986 /* Reset to sentinel value. */
7987 range->sva = 0xfffffffffffffffful;
7991 * Determine whether the attributes specified by a page table entry match those
7992 * being tracked by the current range.
7995 sysctl_kmaps_match(struct pmap_kernel_map_range *range, pt_entry_t attrs)
7998 return (range->attrs == attrs);
8002 sysctl_kmaps_reinit(struct pmap_kernel_map_range *range, vm_offset_t va,
8006 memset(range, 0, sizeof(*range));
8008 range->attrs = attrs;
8011 /* Get the block/page attributes that correspond to the table attributes */
8013 sysctl_kmaps_table_attrs(pd_entry_t table)
8018 if ((table & TATTR_UXN_TABLE) != 0)
8019 attrs |= ATTR_S1_UXN;
8020 if ((table & TATTR_PXN_TABLE) != 0)
8021 attrs |= ATTR_S1_PXN;
8022 if ((table & TATTR_AP_TABLE_RO) != 0)
8023 attrs |= ATTR_S1_AP(ATTR_S1_AP_RO);
8028 /* Read the block/page attributes we care about */
8030 sysctl_kmaps_block_attrs(pt_entry_t block)
8032 return (block & (ATTR_S1_AP_MASK | ATTR_S1_XN | ATTR_S1_IDX_MASK));
8036 * Given a leaf PTE, derive the mapping's attributes. If they do not match
8037 * those of the current run, dump the address range and its attributes, and
8041 sysctl_kmaps_check(struct sbuf *sb, struct pmap_kernel_map_range *range,
8042 vm_offset_t va, pd_entry_t l0e, pd_entry_t l1e, pd_entry_t l2e,
8047 attrs = sysctl_kmaps_table_attrs(l0e);
8049 if ((l1e & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
8050 attrs |= sysctl_kmaps_block_attrs(l1e);
8053 attrs |= sysctl_kmaps_table_attrs(l1e);
8055 if ((l2e & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
8056 attrs |= sysctl_kmaps_block_attrs(l2e);
8059 attrs |= sysctl_kmaps_table_attrs(l2e);
8060 attrs |= sysctl_kmaps_block_attrs(l3e);
8063 if (range->sva > va || !sysctl_kmaps_match(range, attrs)) {
8064 sysctl_kmaps_dump(sb, range, va);
8065 sysctl_kmaps_reinit(range, va, attrs);
8070 sysctl_kmaps(SYSCTL_HANDLER_ARGS)
8072 struct pmap_kernel_map_range range;
8073 struct sbuf sbuf, *sb;
8074 pd_entry_t l0e, *l1, l1e, *l2, l2e;
8075 pt_entry_t *l3, l3e;
8078 int error, i, j, k, l;
8080 error = sysctl_wire_old_buffer(req, 0);
8084 sbuf_new_for_sysctl(sb, NULL, PAGE_SIZE, req);
8086 /* Sentinel value. */
8087 range.sva = 0xfffffffffffffffful;
8090 * Iterate over the kernel page tables without holding the kernel pmap
8091 * lock. Kernel page table pages are never freed, so at worst we will
8092 * observe inconsistencies in the output.
8094 for (sva = 0xffff000000000000ul, i = pmap_l0_index(sva); i < Ln_ENTRIES;
8096 if (i == pmap_l0_index(DMAP_MIN_ADDRESS))
8097 sbuf_printf(sb, "\nDirect map:\n");
8098 else if (i == pmap_l0_index(VM_MIN_KERNEL_ADDRESS))
8099 sbuf_printf(sb, "\nKernel map:\n");
8101 else if (i == pmap_l0_index(KASAN_MIN_ADDRESS))
8102 sbuf_printf(sb, "\nKASAN shadow map:\n");
8105 l0e = kernel_pmap->pm_l0[i];
8106 if ((l0e & ATTR_DESCR_VALID) == 0) {
8107 sysctl_kmaps_dump(sb, &range, sva);
8111 pa = PTE_TO_PHYS(l0e);
8112 l1 = (pd_entry_t *)PHYS_TO_DMAP(pa);
8114 for (j = pmap_l1_index(sva); j < Ln_ENTRIES; j++) {
8116 if ((l1e & ATTR_DESCR_VALID) == 0) {
8117 sysctl_kmaps_dump(sb, &range, sva);
8121 if ((l1e & ATTR_DESCR_MASK) == L1_BLOCK) {
8122 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
8123 sysctl_kmaps_check(sb, &range, sva, l0e, l1e,
8129 pa = PTE_TO_PHYS(l1e);
8130 l2 = (pd_entry_t *)PHYS_TO_DMAP(pa);
8132 for (k = pmap_l2_index(sva); k < Ln_ENTRIES; k++) {
8134 if ((l2e & ATTR_DESCR_VALID) == 0) {
8135 sysctl_kmaps_dump(sb, &range, sva);
8139 if ((l2e & ATTR_DESCR_MASK) == L2_BLOCK) {
8140 sysctl_kmaps_check(sb, &range, sva,
8146 pa = PTE_TO_PHYS(l2e);
8147 l3 = (pt_entry_t *)PHYS_TO_DMAP(pa);
8149 for (l = pmap_l3_index(sva); l < Ln_ENTRIES;
8150 l++, sva += L3_SIZE) {
8152 if ((l3e & ATTR_DESCR_VALID) == 0) {
8153 sysctl_kmaps_dump(sb, &range,
8157 sysctl_kmaps_check(sb, &range, sva,
8158 l0e, l1e, l2e, l3e);
8159 if ((l3e & ATTR_CONTIGUOUS) != 0)
8160 range.l3contig += l % 16 == 0 ?
8169 error = sbuf_finish(sb);
8173 SYSCTL_OID(_vm_pmap, OID_AUTO, kernel_maps,
8174 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
8175 NULL, 0, sysctl_kmaps, "A",
8176 "Dump kernel address layout");