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>
88 * Manages physical address maps.
90 * Since the information managed by this module is
91 * also stored by the logical address mapping module,
92 * this module may throw away valid virtual-to-physical
93 * mappings at almost any time. However, invalidations
94 * of virtual-to-physical mappings must be done as
97 * In order to cope with hardware architectures which
98 * make virtual-to-physical map invalidates expensive,
99 * this module may delay invalidate or reduced protection
100 * operations until such time as they are actually
101 * necessary. This module is given full information as
102 * to which processors are currently using which maps,
103 * and to when physical maps must be made correct.
108 #include <sys/param.h>
109 #include <sys/asan.h>
110 #include <sys/bitstring.h>
112 #include <sys/systm.h>
113 #include <sys/kernel.h>
115 #include <sys/limits.h>
116 #include <sys/lock.h>
117 #include <sys/malloc.h>
118 #include <sys/mman.h>
119 #include <sys/msgbuf.h>
120 #include <sys/mutex.h>
121 #include <sys/physmem.h>
122 #include <sys/proc.h>
123 #include <sys/rwlock.h>
124 #include <sys/sbuf.h>
126 #include <sys/vmem.h>
127 #include <sys/vmmeter.h>
128 #include <sys/sched.h>
129 #include <sys/sysctl.h>
130 #include <sys/_unrhdr.h>
134 #include <vm/vm_param.h>
135 #include <vm/vm_kern.h>
136 #include <vm/vm_page.h>
137 #include <vm/vm_map.h>
138 #include <vm/vm_object.h>
139 #include <vm/vm_extern.h>
140 #include <vm/vm_pageout.h>
141 #include <vm/vm_pager.h>
142 #include <vm/vm_phys.h>
143 #include <vm/vm_radix.h>
144 #include <vm/vm_reserv.h>
145 #include <vm/vm_dumpset.h>
148 #include <machine/asan.h>
149 #include <machine/machdep.h>
150 #include <machine/md_var.h>
151 #include <machine/pcb.h>
154 #define PMAP_MEMDOM MAXMEMDOM
156 #define PMAP_MEMDOM 1
159 #define PMAP_ASSERT_STAGE1(pmap) MPASS((pmap)->pm_stage == PM_STAGE1)
160 #define PMAP_ASSERT_STAGE2(pmap) MPASS((pmap)->pm_stage == PM_STAGE2)
162 #define NL0PG (PAGE_SIZE/(sizeof (pd_entry_t)))
163 #define NL1PG (PAGE_SIZE/(sizeof (pd_entry_t)))
164 #define NL2PG (PAGE_SIZE/(sizeof (pd_entry_t)))
165 #define NL3PG (PAGE_SIZE/(sizeof (pt_entry_t)))
167 #define NUL0E L0_ENTRIES
168 #define NUL1E (NUL0E * NL1PG)
169 #define NUL2E (NUL1E * NL2PG)
172 #define PV_STAT(x) do { x ; } while (0)
175 #define PV_STAT(x) do { } while (0)
176 #define __pvused __unused
179 #define pmap_l0_pindex(v) (NUL2E + NUL1E + ((v) >> L0_SHIFT))
180 #define pmap_l1_pindex(v) (NUL2E + ((v) >> L1_SHIFT))
181 #define pmap_l2_pindex(v) ((v) >> L2_SHIFT)
183 #define PMAP_SAN_PTE_BITS (ATTR_DEFAULT | ATTR_S1_XN | \
184 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) | ATTR_S1_AP(ATTR_S1_AP_RW))
186 struct pmap_large_md_page {
187 struct rwlock pv_lock;
188 struct md_page pv_page;
189 /* Pad to a power of 2, see pmap_init_pv_table(). */
193 __exclusive_cache_line static struct pmap_large_md_page pv_dummy_large;
194 #define pv_dummy pv_dummy_large.pv_page
195 __read_mostly static struct pmap_large_md_page *pv_table;
197 static struct pmap_large_md_page *
198 _pa_to_pmdp(vm_paddr_t pa)
200 struct vm_phys_seg *seg;
202 if ((seg = vm_phys_paddr_to_seg(pa)) != NULL)
203 return ((struct pmap_large_md_page *)seg->md_first +
204 pmap_l2_pindex(pa) - pmap_l2_pindex(seg->start));
208 static struct pmap_large_md_page *
209 pa_to_pmdp(vm_paddr_t pa)
211 struct pmap_large_md_page *pvd;
213 pvd = _pa_to_pmdp(pa);
215 panic("pa 0x%jx not within vm_phys_segs", (uintmax_t)pa);
219 static struct pmap_large_md_page *
220 page_to_pmdp(vm_page_t m)
222 struct vm_phys_seg *seg;
224 seg = &vm_phys_segs[m->segind];
225 return ((struct pmap_large_md_page *)seg->md_first +
226 pmap_l2_pindex(VM_PAGE_TO_PHYS(m)) - pmap_l2_pindex(seg->start));
229 #define pa_to_pvh(pa) (&(pa_to_pmdp(pa)->pv_page))
230 #define page_to_pvh(m) (&(page_to_pmdp(m)->pv_page))
232 #define PHYS_TO_PV_LIST_LOCK(pa) ({ \
233 struct pmap_large_md_page *_pvd; \
234 struct rwlock *_lock; \
235 _pvd = _pa_to_pmdp(pa); \
236 if (__predict_false(_pvd == NULL)) \
237 _lock = &pv_dummy_large.pv_lock; \
239 _lock = &(_pvd->pv_lock); \
243 static struct rwlock *
244 VM_PAGE_TO_PV_LIST_LOCK(vm_page_t m)
246 if ((m->flags & PG_FICTITIOUS) == 0)
247 return (&page_to_pmdp(m)->pv_lock);
249 return (&pv_dummy_large.pv_lock);
252 #define CHANGE_PV_LIST_LOCK(lockp, new_lock) do { \
253 struct rwlock **_lockp = (lockp); \
254 struct rwlock *_new_lock = (new_lock); \
256 if (_new_lock != *_lockp) { \
257 if (*_lockp != NULL) \
258 rw_wunlock(*_lockp); \
259 *_lockp = _new_lock; \
264 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) \
265 CHANGE_PV_LIST_LOCK(lockp, PHYS_TO_PV_LIST_LOCK(pa))
267 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
268 CHANGE_PV_LIST_LOCK(lockp, VM_PAGE_TO_PV_LIST_LOCK(m))
270 #define RELEASE_PV_LIST_LOCK(lockp) do { \
271 struct rwlock **_lockp = (lockp); \
273 if (*_lockp != NULL) { \
274 rw_wunlock(*_lockp); \
280 * The presence of this flag indicates that the mapping is writeable.
281 * If the ATTR_S1_AP_RO bit is also set, then the mapping is clean, otherwise
282 * it is dirty. This flag may only be set on managed mappings.
284 * The DBM bit is reserved on ARMv8.0 but it seems we can safely treat it
285 * as a software managed bit.
287 #define ATTR_SW_DBM ATTR_DBM
289 struct pmap kernel_pmap_store;
291 /* Used for mapping ACPI memory before VM is initialized */
292 #define PMAP_PREINIT_MAPPING_COUNT 32
293 #define PMAP_PREINIT_MAPPING_SIZE (PMAP_PREINIT_MAPPING_COUNT * L2_SIZE)
294 static vm_offset_t preinit_map_va; /* Start VA of pre-init mapping space */
295 static int vm_initialized = 0; /* No need to use pre-init maps when set */
298 * Reserve a few L2 blocks starting from 'preinit_map_va' pointer.
299 * Always map entire L2 block for simplicity.
300 * VA of L2 block = preinit_map_va + i * L2_SIZE
302 static struct pmap_preinit_mapping {
306 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
308 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
309 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
310 vm_offset_t kernel_vm_end = 0;
313 * Data for the pv entry allocation mechanism.
317 pc_to_domain(struct pv_chunk *pc)
319 return (vm_phys_domain(DMAP_TO_PHYS((vm_offset_t)pc)));
323 pc_to_domain(struct pv_chunk *pc __unused)
329 struct pv_chunks_list {
331 TAILQ_HEAD(pch, pv_chunk) pvc_list;
333 } __aligned(CACHE_LINE_SIZE);
335 struct pv_chunks_list __exclusive_cache_line pv_chunks[PMAP_MEMDOM];
337 vm_paddr_t dmap_phys_base; /* The start of the dmap region */
338 vm_paddr_t dmap_phys_max; /* The limit of the dmap region */
339 vm_offset_t dmap_max_addr; /* The virtual address limit of the dmap */
341 extern pt_entry_t pagetable_l0_ttbr1[];
343 #define PHYSMAP_SIZE (2 * (VM_PHYSSEG_MAX - 1))
344 static vm_paddr_t physmap[PHYSMAP_SIZE];
345 static u_int physmap_idx;
347 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
348 "VM/pmap parameters");
350 #if PAGE_SIZE == PAGE_SIZE_4K
351 #define L1_BLOCKS_SUPPORTED 1
353 /* TODO: Make this dynamic when we support FEAT_LPA2 (TCR_EL1.DS == 1) */
354 #define L1_BLOCKS_SUPPORTED 0
357 #define PMAP_ASSERT_L1_BLOCKS_SUPPORTED MPASS(L1_BLOCKS_SUPPORTED)
360 * This ASID allocator uses a bit vector ("asid_set") to remember which ASIDs
361 * that it has currently allocated to a pmap, a cursor ("asid_next") to
362 * optimize its search for a free ASID in the bit vector, and an epoch number
363 * ("asid_epoch") to indicate when it has reclaimed all previously allocated
364 * ASIDs that are not currently active on a processor.
366 * The current epoch number is always in the range [0, INT_MAX). Negative
367 * numbers and INT_MAX are reserved for special cases that are described
376 struct mtx asid_set_mutex;
379 static struct asid_set asids;
380 static struct asid_set vmids;
382 static SYSCTL_NODE(_vm_pmap, OID_AUTO, asid, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
384 SYSCTL_INT(_vm_pmap_asid, OID_AUTO, bits, CTLFLAG_RD, &asids.asid_bits, 0,
385 "The number of bits in an ASID");
386 SYSCTL_INT(_vm_pmap_asid, OID_AUTO, next, CTLFLAG_RD, &asids.asid_next, 0,
387 "The last allocated ASID plus one");
388 SYSCTL_INT(_vm_pmap_asid, OID_AUTO, epoch, CTLFLAG_RD, &asids.asid_epoch, 0,
389 "The current epoch number");
391 static SYSCTL_NODE(_vm_pmap, OID_AUTO, vmid, CTLFLAG_RD, 0, "VMID allocator");
392 SYSCTL_INT(_vm_pmap_vmid, OID_AUTO, bits, CTLFLAG_RD, &vmids.asid_bits, 0,
393 "The number of bits in an VMID");
394 SYSCTL_INT(_vm_pmap_vmid, OID_AUTO, next, CTLFLAG_RD, &vmids.asid_next, 0,
395 "The last allocated VMID plus one");
396 SYSCTL_INT(_vm_pmap_vmid, OID_AUTO, epoch, CTLFLAG_RD, &vmids.asid_epoch, 0,
397 "The current epoch number");
399 void (*pmap_clean_stage2_tlbi)(void);
400 void (*pmap_invalidate_vpipt_icache)(void);
401 void (*pmap_stage2_invalidate_range)(uint64_t, vm_offset_t, vm_offset_t, bool);
402 void (*pmap_stage2_invalidate_all)(uint64_t);
405 * A pmap's cookie encodes an ASID and epoch number. Cookies for reserved
406 * ASIDs have a negative epoch number, specifically, INT_MIN. Cookies for
407 * dynamically allocated ASIDs have a non-negative epoch number.
409 * An invalid ASID is represented by -1.
411 * There are two special-case cookie values: (1) COOKIE_FROM(-1, INT_MIN),
412 * which indicates that an ASID should never be allocated to the pmap, and
413 * (2) COOKIE_FROM(-1, INT_MAX), which indicates that an ASID should be
414 * allocated when the pmap is next activated.
416 #define COOKIE_FROM(asid, epoch) ((long)((u_int)(asid) | \
417 ((u_long)(epoch) << 32)))
418 #define COOKIE_TO_ASID(cookie) ((int)(cookie))
419 #define COOKIE_TO_EPOCH(cookie) ((int)((u_long)(cookie) >> 32))
421 #define TLBI_VA_SHIFT 12
422 #define TLBI_VA_MASK ((1ul << 44) - 1)
423 #define TLBI_VA(addr) (((addr) >> TLBI_VA_SHIFT) & TLBI_VA_MASK)
424 #define TLBI_VA_L3_INCR (L3_SIZE >> TLBI_VA_SHIFT)
426 static int __read_frequently superpages_enabled = 1;
427 SYSCTL_INT(_vm_pmap, OID_AUTO, superpages_enabled,
428 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &superpages_enabled, 0,
429 "Are large page mappings enabled?");
432 * Internal flags for pmap_enter()'s helper functions.
434 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
435 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
437 TAILQ_HEAD(pv_chunklist, pv_chunk);
439 static void free_pv_chunk(struct pv_chunk *pc);
440 static void free_pv_chunk_batch(struct pv_chunklist *batch);
441 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
442 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
443 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
444 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
445 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
448 static void pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte);
449 static bool pmap_activate_int(pmap_t pmap);
450 static void pmap_alloc_asid(pmap_t pmap);
451 static int pmap_change_props_locked(vm_offset_t va, vm_size_t size,
452 vm_prot_t prot, int mode, bool skip_unmapped);
453 static pt_entry_t *pmap_demote_l1(pmap_t pmap, pt_entry_t *l1, vm_offset_t va);
454 static pt_entry_t *pmap_demote_l2_locked(pmap_t pmap, pt_entry_t *l2,
455 vm_offset_t va, struct rwlock **lockp);
456 static pt_entry_t *pmap_demote_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va);
457 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
458 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
459 static int pmap_enter_l2(pmap_t pmap, vm_offset_t va, pd_entry_t new_l2,
460 u_int flags, vm_page_t m, struct rwlock **lockp);
461 static int pmap_remove_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva,
462 pd_entry_t l1e, struct spglist *free, struct rwlock **lockp);
463 static int pmap_remove_l3(pmap_t pmap, pt_entry_t *l3, vm_offset_t sva,
464 pd_entry_t l2e, struct spglist *free, struct rwlock **lockp);
465 static void pmap_reset_asid_set(pmap_t pmap);
466 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
467 vm_page_t m, struct rwlock **lockp);
469 static vm_page_t _pmap_alloc_l3(pmap_t pmap, vm_pindex_t ptepindex,
470 struct rwlock **lockp);
472 static void _pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m,
473 struct spglist *free);
474 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
475 static __inline vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
478 * These load the old table data and store the new value.
479 * They need to be atomic as the System MMU may write to the table at
480 * the same time as the CPU.
482 #define pmap_clear(table) atomic_store_64(table, 0)
483 #define pmap_clear_bits(table, bits) atomic_clear_64(table, bits)
484 #define pmap_load(table) (*table)
485 #define pmap_load_clear(table) atomic_swap_64(table, 0)
486 #define pmap_load_store(table, entry) atomic_swap_64(table, entry)
487 #define pmap_set_bits(table, bits) atomic_set_64(table, bits)
488 #define pmap_store(table, entry) atomic_store_64(table, entry)
490 /********************/
491 /* Inline functions */
492 /********************/
495 pagecopy(void *s, void *d)
498 memcpy(d, s, PAGE_SIZE);
501 static __inline pd_entry_t *
502 pmap_l0(pmap_t pmap, vm_offset_t va)
505 return (&pmap->pm_l0[pmap_l0_index(va)]);
508 static __inline pd_entry_t *
509 pmap_l0_to_l1(pd_entry_t *l0, vm_offset_t va)
513 l1 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(pmap_load(l0)));
514 return (&l1[pmap_l1_index(va)]);
517 static __inline pd_entry_t *
518 pmap_l1(pmap_t pmap, vm_offset_t va)
522 l0 = pmap_l0(pmap, va);
523 if ((pmap_load(l0) & ATTR_DESCR_MASK) != L0_TABLE)
526 return (pmap_l0_to_l1(l0, va));
529 static __inline pd_entry_t *
530 pmap_l1_to_l2(pd_entry_t *l1p, vm_offset_t va)
536 KASSERT(ADDR_IS_CANONICAL(va),
537 ("%s: Address not in canonical form: %lx", __func__, va));
539 * The valid bit may be clear if pmap_update_entry() is concurrently
540 * modifying the entry, so for KVA only the entry type may be checked.
542 KASSERT(ADDR_IS_KERNEL(va) || (l1 & ATTR_DESCR_VALID) != 0,
543 ("%s: L1 entry %#lx for %#lx is invalid", __func__, l1, va));
544 KASSERT((l1 & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_TABLE,
545 ("%s: L1 entry %#lx for %#lx is a leaf", __func__, l1, va));
546 l2p = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(l1));
547 return (&l2p[pmap_l2_index(va)]);
550 static __inline pd_entry_t *
551 pmap_l2(pmap_t pmap, vm_offset_t va)
555 l1 = pmap_l1(pmap, va);
556 if ((pmap_load(l1) & ATTR_DESCR_MASK) != L1_TABLE)
559 return (pmap_l1_to_l2(l1, va));
562 static __inline pt_entry_t *
563 pmap_l2_to_l3(pd_entry_t *l2p, vm_offset_t va)
570 KASSERT(ADDR_IS_CANONICAL(va),
571 ("%s: Address not in canonical form: %lx", __func__, va));
573 * The valid bit may be clear if pmap_update_entry() is concurrently
574 * modifying the entry, so for KVA only the entry type may be checked.
576 KASSERT(ADDR_IS_KERNEL(va) || (l2 & ATTR_DESCR_VALID) != 0,
577 ("%s: L2 entry %#lx for %#lx is invalid", __func__, l2, va));
578 KASSERT((l2 & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_TABLE,
579 ("%s: L2 entry %#lx for %#lx is a leaf", __func__, l2, va));
580 l3p = (pt_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(l2));
581 return (&l3p[pmap_l3_index(va)]);
585 * Returns the lowest valid pde for a given virtual address.
586 * The next level may or may not point to a valid page or block.
588 static __inline pd_entry_t *
589 pmap_pde(pmap_t pmap, vm_offset_t va, int *level)
591 pd_entry_t *l0, *l1, *l2, desc;
593 l0 = pmap_l0(pmap, va);
594 desc = pmap_load(l0) & ATTR_DESCR_MASK;
595 if (desc != L0_TABLE) {
600 l1 = pmap_l0_to_l1(l0, va);
601 desc = pmap_load(l1) & ATTR_DESCR_MASK;
602 if (desc != L1_TABLE) {
607 l2 = pmap_l1_to_l2(l1, va);
608 desc = pmap_load(l2) & ATTR_DESCR_MASK;
609 if (desc != L2_TABLE) {
619 * Returns the lowest valid pte block or table entry for a given virtual
620 * address. If there are no valid entries return NULL and set the level to
621 * the first invalid level.
623 static __inline pt_entry_t *
624 pmap_pte(pmap_t pmap, vm_offset_t va, int *level)
626 pd_entry_t *l1, *l2, desc;
629 l1 = pmap_l1(pmap, va);
634 desc = pmap_load(l1) & ATTR_DESCR_MASK;
635 if (desc == L1_BLOCK) {
636 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
641 if (desc != L1_TABLE) {
646 l2 = pmap_l1_to_l2(l1, va);
647 desc = pmap_load(l2) & ATTR_DESCR_MASK;
648 if (desc == L2_BLOCK) {
653 if (desc != L2_TABLE) {
659 l3 = pmap_l2_to_l3(l2, va);
660 if ((pmap_load(l3) & ATTR_DESCR_MASK) != L3_PAGE)
667 * If the given pmap has an L{1,2}_BLOCK or L3_PAGE entry at the specified
668 * level that maps the specified virtual address, then a pointer to that entry
669 * is returned. Otherwise, NULL is returned, unless INVARIANTS are enabled
670 * and a diagnostic message is provided, in which case this function panics.
672 static __always_inline pt_entry_t *
673 pmap_pte_exists(pmap_t pmap, vm_offset_t va, int level, const char *diag)
675 pd_entry_t *l0p, *l1p, *l2p;
676 pt_entry_t desc, *l3p;
677 int walk_level __diagused;
679 KASSERT(level >= 0 && level < 4,
680 ("%s: %s passed an out-of-range level (%d)", __func__, diag,
682 l0p = pmap_l0(pmap, va);
683 desc = pmap_load(l0p) & ATTR_DESCR_MASK;
684 if (desc == L0_TABLE && level > 0) {
685 l1p = pmap_l0_to_l1(l0p, va);
686 desc = pmap_load(l1p) & ATTR_DESCR_MASK;
687 if (desc == L1_BLOCK && level == 1) {
688 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
691 if (desc == L1_TABLE && level > 1) {
692 l2p = pmap_l1_to_l2(l1p, va);
693 desc = pmap_load(l2p) & ATTR_DESCR_MASK;
694 if (desc == L2_BLOCK && level == 2)
696 else if (desc == L2_TABLE && level > 2) {
697 l3p = pmap_l2_to_l3(l2p, va);
698 desc = pmap_load(l3p) & ATTR_DESCR_MASK;
699 if (desc == L3_PAGE && level == 3)
709 KASSERT(diag == NULL,
710 ("%s: va %#lx not mapped at level %d, desc %ld at level %d",
711 diag, va, level, desc, walk_level));
716 pmap_ps_enabled(pmap_t pmap)
719 * Promotion requires a hypervisor call when the kernel is running
720 * in EL1. To stop this disable superpage support on non-stage 1
723 if (pmap->pm_stage != PM_STAGE1)
726 return (superpages_enabled != 0);
730 pmap_get_tables(pmap_t pmap, vm_offset_t va, pd_entry_t **l0, pd_entry_t **l1,
731 pd_entry_t **l2, pt_entry_t **l3)
733 pd_entry_t *l0p, *l1p, *l2p;
735 if (pmap->pm_l0 == NULL)
738 l0p = pmap_l0(pmap, va);
741 if ((pmap_load(l0p) & ATTR_DESCR_MASK) != L0_TABLE)
744 l1p = pmap_l0_to_l1(l0p, va);
747 if ((pmap_load(l1p) & ATTR_DESCR_MASK) == L1_BLOCK) {
748 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
754 if ((pmap_load(l1p) & ATTR_DESCR_MASK) != L1_TABLE)
757 l2p = pmap_l1_to_l2(l1p, va);
760 if ((pmap_load(l2p) & ATTR_DESCR_MASK) == L2_BLOCK) {
765 if ((pmap_load(l2p) & ATTR_DESCR_MASK) != L2_TABLE)
768 *l3 = pmap_l2_to_l3(l2p, va);
774 pmap_l3_valid(pt_entry_t l3)
777 return ((l3 & ATTR_DESCR_MASK) == L3_PAGE);
780 CTASSERT(L1_BLOCK == L2_BLOCK);
783 pmap_pte_memattr(pmap_t pmap, vm_memattr_t memattr)
787 if (pmap->pm_stage == PM_STAGE1) {
788 val = ATTR_S1_IDX(memattr);
789 if (memattr == VM_MEMATTR_DEVICE)
797 case VM_MEMATTR_DEVICE:
798 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_DEVICE_nGnRnE) |
799 ATTR_S2_XN(ATTR_S2_XN_ALL));
800 case VM_MEMATTR_UNCACHEABLE:
801 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_NC));
802 case VM_MEMATTR_WRITE_BACK:
803 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_WB));
804 case VM_MEMATTR_WRITE_THROUGH:
805 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_WT));
807 panic("%s: invalid memory attribute %x", __func__, memattr);
812 pmap_pte_prot(pmap_t pmap, vm_prot_t prot)
817 if (pmap->pm_stage == PM_STAGE1) {
818 if ((prot & VM_PROT_EXECUTE) == 0)
820 if ((prot & VM_PROT_WRITE) == 0)
821 val |= ATTR_S1_AP(ATTR_S1_AP_RO);
823 if ((prot & VM_PROT_WRITE) != 0)
824 val |= ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
825 if ((prot & VM_PROT_READ) != 0)
826 val |= ATTR_S2_S2AP(ATTR_S2_S2AP_READ);
827 if ((prot & VM_PROT_EXECUTE) == 0)
828 val |= ATTR_S2_XN(ATTR_S2_XN_ALL);
835 * Checks if the PTE is dirty.
838 pmap_pte_dirty(pmap_t pmap, pt_entry_t pte)
841 KASSERT((pte & ATTR_SW_MANAGED) != 0, ("pte %#lx is unmanaged", pte));
843 if (pmap->pm_stage == PM_STAGE1) {
844 KASSERT((pte & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) != 0,
845 ("pte %#lx is writeable and missing ATTR_SW_DBM", pte));
847 return ((pte & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
848 (ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_SW_DBM));
851 return ((pte & ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE)) ==
852 ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE));
856 pmap_resident_count_inc(pmap_t pmap, int count)
859 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
860 pmap->pm_stats.resident_count += count;
864 pmap_resident_count_dec(pmap_t pmap, int count)
867 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
868 KASSERT(pmap->pm_stats.resident_count >= count,
869 ("pmap %p resident count underflow %ld %d", pmap,
870 pmap->pm_stats.resident_count, count));
871 pmap->pm_stats.resident_count -= count;
875 pmap_early_vtophys(vm_offset_t va)
879 pa_page = arm64_address_translate_s1e1r(va) & PAR_PA_MASK;
880 return (pa_page | (va & PAR_LOW_MASK));
883 /* State of the bootstrapped DMAP page tables */
884 struct pmap_bootstrap_state {
888 vm_offset_t freemempos;
891 pt_entry_t table_attrs;
898 /* The bootstrap state */
899 static struct pmap_bootstrap_state bs_state = {
903 .table_attrs = TATTR_PXN_TABLE,
904 .l0_slot = L0_ENTRIES,
905 .l1_slot = Ln_ENTRIES,
906 .l2_slot = Ln_ENTRIES,
911 pmap_bootstrap_l0_table(struct pmap_bootstrap_state *state)
917 /* Link the level 0 table to a level 1 table */
918 l0_slot = pmap_l0_index(state->va);
919 if (l0_slot != state->l0_slot) {
921 * Make sure we move from a low address to high address
922 * before the DMAP region is ready. This ensures we never
923 * modify an existing mapping until we can map from a
924 * physical address to a virtual address.
926 MPASS(state->l0_slot < l0_slot ||
927 state->l0_slot == L0_ENTRIES ||
930 /* Reset lower levels */
933 state->l1_slot = Ln_ENTRIES;
934 state->l2_slot = Ln_ENTRIES;
936 /* Check the existing L0 entry */
937 state->l0_slot = l0_slot;
938 if (state->dmap_valid) {
939 l0e = pagetable_l0_ttbr1[l0_slot];
940 if ((l0e & ATTR_DESCR_VALID) != 0) {
941 MPASS((l0e & ATTR_DESCR_MASK) == L0_TABLE);
942 l1_pa = PTE_TO_PHYS(l0e);
943 state->l1 = (pt_entry_t *)PHYS_TO_DMAP(l1_pa);
948 /* Create a new L0 table entry */
949 state->l1 = (pt_entry_t *)state->freemempos;
950 memset(state->l1, 0, PAGE_SIZE);
951 state->freemempos += PAGE_SIZE;
953 l1_pa = pmap_early_vtophys((vm_offset_t)state->l1);
954 MPASS((l1_pa & Ln_TABLE_MASK) == 0);
955 MPASS(pagetable_l0_ttbr1[l0_slot] == 0);
956 pmap_store(&pagetable_l0_ttbr1[l0_slot], PHYS_TO_PTE(l1_pa) |
957 TATTR_UXN_TABLE | TATTR_AP_TABLE_NO_EL0 | L0_TABLE);
959 KASSERT(state->l1 != NULL, ("%s: NULL l1", __func__));
963 pmap_bootstrap_l1_table(struct pmap_bootstrap_state *state)
969 /* Make sure there is a valid L0 -> L1 table */
970 pmap_bootstrap_l0_table(state);
972 /* Link the level 1 table to a level 2 table */
973 l1_slot = pmap_l1_index(state->va);
974 if (l1_slot != state->l1_slot) {
975 /* See pmap_bootstrap_l0_table for a description */
976 MPASS(state->l1_slot < l1_slot ||
977 state->l1_slot == Ln_ENTRIES ||
980 /* Reset lower levels */
982 state->l2_slot = Ln_ENTRIES;
984 /* Check the existing L1 entry */
985 state->l1_slot = l1_slot;
986 if (state->dmap_valid) {
987 l1e = state->l1[l1_slot];
988 if ((l1e & ATTR_DESCR_VALID) != 0) {
989 MPASS((l1e & ATTR_DESCR_MASK) == L1_TABLE);
990 l2_pa = PTE_TO_PHYS(l1e);
991 state->l2 = (pt_entry_t *)PHYS_TO_DMAP(l2_pa);
996 /* Create a new L1 table entry */
997 state->l2 = (pt_entry_t *)state->freemempos;
998 memset(state->l2, 0, PAGE_SIZE);
999 state->freemempos += PAGE_SIZE;
1001 l2_pa = pmap_early_vtophys((vm_offset_t)state->l2);
1002 MPASS((l2_pa & Ln_TABLE_MASK) == 0);
1003 MPASS(state->l1[l1_slot] == 0);
1004 pmap_store(&state->l1[l1_slot], PHYS_TO_PTE(l2_pa) |
1005 state->table_attrs | L1_TABLE);
1007 KASSERT(state->l2 != NULL, ("%s: NULL l2", __func__));
1011 pmap_bootstrap_l2_table(struct pmap_bootstrap_state *state)
1017 /* Make sure there is a valid L1 -> L2 table */
1018 pmap_bootstrap_l1_table(state);
1020 /* Link the level 2 table to a level 3 table */
1021 l2_slot = pmap_l2_index(state->va);
1022 if (l2_slot != state->l2_slot) {
1023 /* See pmap_bootstrap_l0_table for a description */
1024 MPASS(state->l2_slot < l2_slot ||
1025 state->l2_slot == Ln_ENTRIES ||
1028 /* Check the existing L2 entry */
1029 state->l2_slot = l2_slot;
1030 if (state->dmap_valid) {
1031 l2e = state->l2[l2_slot];
1032 if ((l2e & ATTR_DESCR_VALID) != 0) {
1033 MPASS((l2e & ATTR_DESCR_MASK) == L2_TABLE);
1034 l3_pa = PTE_TO_PHYS(l2e);
1035 state->l3 = (pt_entry_t *)PHYS_TO_DMAP(l3_pa);
1040 /* Create a new L2 table entry */
1041 state->l3 = (pt_entry_t *)state->freemempos;
1042 memset(state->l3, 0, PAGE_SIZE);
1043 state->freemempos += PAGE_SIZE;
1045 l3_pa = pmap_early_vtophys((vm_offset_t)state->l3);
1046 MPASS((l3_pa & Ln_TABLE_MASK) == 0);
1047 MPASS(state->l2[l2_slot] == 0);
1048 pmap_store(&state->l2[l2_slot], PHYS_TO_PTE(l3_pa) |
1049 state->table_attrs | L2_TABLE);
1051 KASSERT(state->l3 != NULL, ("%s: NULL l3", __func__));
1055 pmap_bootstrap_l2_block(struct pmap_bootstrap_state *state, int i)
1060 if ((physmap[i + 1] - state->pa) < L2_SIZE)
1063 /* Make sure there is a valid L1 table */
1064 pmap_bootstrap_l1_table(state);
1066 MPASS((state->va & L2_OFFSET) == 0);
1068 state->va < DMAP_MAX_ADDRESS &&
1069 (physmap[i + 1] - state->pa) >= L2_SIZE;
1070 state->va += L2_SIZE, state->pa += L2_SIZE) {
1072 * Stop if we are about to walk off the end of what the
1073 * current L1 slot can address.
1075 if (!first && (state->pa & L1_OFFSET) == 0)
1079 l2_slot = pmap_l2_index(state->va);
1080 MPASS((state->pa & L2_OFFSET) == 0);
1081 MPASS(state->l2[l2_slot] == 0);
1082 pmap_store(&state->l2[l2_slot], PHYS_TO_PTE(state->pa) |
1083 ATTR_DEFAULT | ATTR_S1_XN |
1084 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) | L2_BLOCK);
1086 MPASS(state->va == (state->pa - dmap_phys_base + DMAP_MIN_ADDRESS));
1090 pmap_bootstrap_l3_page(struct pmap_bootstrap_state *state, int i)
1095 if ((physmap[i + 1] - state->pa) < L3_SIZE)
1098 /* Make sure there is a valid L2 table */
1099 pmap_bootstrap_l2_table(state);
1101 MPASS((state->va & L3_OFFSET) == 0);
1103 state->va < DMAP_MAX_ADDRESS &&
1104 (physmap[i + 1] - state->pa) >= L3_SIZE;
1105 state->va += L3_SIZE, state->pa += L3_SIZE) {
1107 * Stop if we are about to walk off the end of what the
1108 * current L2 slot can address.
1110 if (!first && (state->pa & L2_OFFSET) == 0)
1114 l3_slot = pmap_l3_index(state->va);
1115 MPASS((state->pa & L3_OFFSET) == 0);
1116 MPASS(state->l3[l3_slot] == 0);
1117 pmap_store(&state->l3[l3_slot], PHYS_TO_PTE(state->pa) |
1118 ATTR_DEFAULT | ATTR_S1_XN |
1119 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) | L3_PAGE);
1121 MPASS(state->va == (state->pa - dmap_phys_base + DMAP_MIN_ADDRESS));
1125 pmap_bootstrap_dmap(vm_paddr_t min_pa)
1129 dmap_phys_base = min_pa & ~L1_OFFSET;
1133 for (i = 0; i < (physmap_idx * 2); i += 2) {
1134 bs_state.pa = physmap[i] & ~L3_OFFSET;
1135 bs_state.va = bs_state.pa - dmap_phys_base + DMAP_MIN_ADDRESS;
1137 /* Create L3 mappings at the start of the region */
1138 if ((bs_state.pa & L2_OFFSET) != 0)
1139 pmap_bootstrap_l3_page(&bs_state, i);
1140 MPASS(bs_state.pa <= physmap[i + 1]);
1142 if (L1_BLOCKS_SUPPORTED) {
1143 /* Create L2 mappings at the start of the region */
1144 if ((bs_state.pa & L1_OFFSET) != 0)
1145 pmap_bootstrap_l2_block(&bs_state, i);
1146 MPASS(bs_state.pa <= physmap[i + 1]);
1148 /* Create the main L1 block mappings */
1149 for (; bs_state.va < DMAP_MAX_ADDRESS &&
1150 (physmap[i + 1] - bs_state.pa) >= L1_SIZE;
1151 bs_state.va += L1_SIZE, bs_state.pa += L1_SIZE) {
1152 /* Make sure there is a valid L1 table */
1153 pmap_bootstrap_l0_table(&bs_state);
1154 MPASS((bs_state.pa & L1_OFFSET) == 0);
1156 &bs_state.l1[pmap_l1_index(bs_state.va)],
1157 PHYS_TO_PTE(bs_state.pa) | ATTR_DEFAULT |
1158 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) |
1159 ATTR_S1_XN | L1_BLOCK);
1161 MPASS(bs_state.pa <= physmap[i + 1]);
1163 /* Create L2 mappings at the end of the region */
1164 pmap_bootstrap_l2_block(&bs_state, i);
1166 while (bs_state.va < DMAP_MAX_ADDRESS &&
1167 (physmap[i + 1] - bs_state.pa) >= L2_SIZE) {
1168 pmap_bootstrap_l2_block(&bs_state, i);
1171 MPASS(bs_state.pa <= physmap[i + 1]);
1173 /* Create L3 mappings at the end of the region */
1174 pmap_bootstrap_l3_page(&bs_state, i);
1175 MPASS(bs_state.pa == physmap[i + 1]);
1177 if (bs_state.pa > dmap_phys_max) {
1178 dmap_phys_max = bs_state.pa;
1179 dmap_max_addr = bs_state.va;
1187 pmap_bootstrap_l2(vm_offset_t va)
1189 KASSERT((va & L1_OFFSET) == 0, ("Invalid virtual address"));
1191 /* Leave bs_state.pa as it's only needed to bootstrap blocks and pages*/
1194 for (; bs_state.va < VM_MAX_KERNEL_ADDRESS; bs_state.va += L1_SIZE)
1195 pmap_bootstrap_l1_table(&bs_state);
1199 pmap_bootstrap_l3(vm_offset_t va)
1201 KASSERT((va & L2_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 += L2_SIZE)
1207 pmap_bootstrap_l2_table(&bs_state);
1212 pmap_bootstrap_allocate_kasan_l2(vm_paddr_t start_pa, vm_paddr_t end_pa,
1213 vm_offset_t *start_va, int *nkasan_l2)
1221 pa = rounddown2(end_pa - L2_SIZE, L2_SIZE);
1222 l2 = pmap_l2(kernel_pmap, va);
1224 for (i = 0; pa >= start_pa && i < *nkasan_l2;
1225 i++, va += L2_SIZE, pa -= L2_SIZE, l2++) {
1227 * KASAN stack checking results in us having already allocated
1228 * part of our shadow map, so we can just skip those segments.
1230 if ((pmap_load(l2) & ATTR_DESCR_VALID) != 0) {
1235 pmap_store(l2, PHYS_TO_PTE(pa) | PMAP_SAN_PTE_BITS | L2_BLOCK);
1239 * Ended the allocation due to start_pa constraint, rather than because
1240 * we allocated everything. Adjust back up to the start_pa and remove
1241 * the invalid L2 block from our accounting.
1243 if (pa < start_pa) {
1249 bzero((void *)PHYS_TO_DMAP(pa), i * L2_SIZE);
1250 physmem_exclude_region(pa, i * L2_SIZE, EXFLAG_NOALLOC);
1258 * Bootstrap the system enough to run with virtual memory.
1261 pmap_bootstrap(vm_paddr_t kernstart, vm_size_t kernlen)
1263 vm_offset_t dpcpu, msgbufpv;
1264 vm_paddr_t start_pa, pa, min_pa;
1265 uint64_t kern_delta;
1268 /* Verify that the ASID is set through TTBR0. */
1269 KASSERT((READ_SPECIALREG(tcr_el1) & TCR_A1) == 0,
1270 ("pmap_bootstrap: TCR_EL1.A1 != 0"));
1272 kern_delta = KERNBASE - kernstart;
1274 printf("pmap_bootstrap %lx %lx\n", kernstart, kernlen);
1275 printf("%lx\n", (KERNBASE >> L1_SHIFT) & Ln_ADDR_MASK);
1277 /* Set this early so we can use the pagetable walking functions */
1278 kernel_pmap_store.pm_l0 = pagetable_l0_ttbr1;
1279 PMAP_LOCK_INIT(kernel_pmap);
1280 kernel_pmap->pm_l0_paddr =
1281 pmap_early_vtophys((vm_offset_t)kernel_pmap_store.pm_l0);
1282 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1283 vm_radix_init(&kernel_pmap->pm_root);
1284 kernel_pmap->pm_cookie = COOKIE_FROM(-1, INT_MIN);
1285 kernel_pmap->pm_stage = PM_STAGE1;
1286 kernel_pmap->pm_levels = 4;
1287 kernel_pmap->pm_ttbr = kernel_pmap->pm_l0_paddr;
1288 kernel_pmap->pm_asid_set = &asids;
1290 /* Assume the address we were loaded to is a valid physical address */
1291 min_pa = KERNBASE - kern_delta;
1293 physmap_idx = physmem_avail(physmap, nitems(physmap));
1297 * Find the minimum physical address. physmap is sorted,
1298 * but may contain empty ranges.
1300 for (i = 0; i < physmap_idx * 2; i += 2) {
1301 if (physmap[i] == physmap[i + 1])
1303 if (physmap[i] <= min_pa)
1304 min_pa = physmap[i];
1307 bs_state.freemempos = KERNBASE + kernlen;
1308 bs_state.freemempos = roundup2(bs_state.freemempos, PAGE_SIZE);
1310 /* Create a direct map region early so we can use it for pa -> va */
1311 pmap_bootstrap_dmap(min_pa);
1312 bs_state.dmap_valid = true;
1314 * We only use PXN when we know nothing will be executed from it, e.g.
1317 bs_state.table_attrs &= ~TATTR_PXN_TABLE;
1319 start_pa = pa = KERNBASE - kern_delta;
1322 * Create the l2 tables up to VM_MAX_KERNEL_ADDRESS. We assume that the
1323 * loader allocated the first and only l2 page table page used to map
1324 * the kernel, preloaded files and module metadata.
1326 pmap_bootstrap_l2(KERNBASE + L1_SIZE);
1327 /* And the l3 tables for the early devmap */
1328 pmap_bootstrap_l3(VM_MAX_KERNEL_ADDRESS - (PMAP_MAPDEV_EARLY_SIZE));
1332 #define alloc_pages(var, np) \
1333 (var) = bs_state.freemempos; \
1334 bs_state.freemempos += (np * PAGE_SIZE); \
1335 memset((char *)(var), 0, ((np) * PAGE_SIZE));
1337 /* Allocate dynamic per-cpu area. */
1338 alloc_pages(dpcpu, DPCPU_SIZE / PAGE_SIZE);
1339 dpcpu_init((void *)dpcpu, 0);
1341 /* Allocate memory for the msgbuf, e.g. for /sbin/dmesg */
1342 alloc_pages(msgbufpv, round_page(msgbufsize) / PAGE_SIZE);
1343 msgbufp = (void *)msgbufpv;
1345 /* Reserve some VA space for early BIOS/ACPI mapping */
1346 preinit_map_va = roundup2(bs_state.freemempos, L2_SIZE);
1348 virtual_avail = preinit_map_va + PMAP_PREINIT_MAPPING_SIZE;
1349 virtual_avail = roundup2(virtual_avail, L1_SIZE);
1350 virtual_end = VM_MAX_KERNEL_ADDRESS - (PMAP_MAPDEV_EARLY_SIZE);
1351 kernel_vm_end = virtual_avail;
1353 pa = pmap_early_vtophys(bs_state.freemempos);
1355 physmem_exclude_region(start_pa, pa - start_pa, EXFLAG_NOALLOC);
1362 * Finish constructing the initial shadow map:
1363 * - Count how many pages from KERNBASE to virtual_avail (scaled for
1365 * - Map that entire range using L2 superpages.
1368 pmap_bootstrap_san(vm_paddr_t kernstart)
1371 int i, shadow_npages, nkasan_l2;
1374 * Rebuild physmap one more time, we may have excluded more regions from
1375 * allocation since pmap_bootstrap().
1377 bzero(physmap, sizeof(physmap));
1378 physmap_idx = physmem_avail(physmap, nitems(physmap));
1381 shadow_npages = (virtual_avail - VM_MIN_KERNEL_ADDRESS) / PAGE_SIZE;
1382 shadow_npages = howmany(shadow_npages, KASAN_SHADOW_SCALE);
1383 nkasan_l2 = howmany(shadow_npages, Ln_ENTRIES);
1385 /* Map the valid KVA up to this point. */
1386 va = KASAN_MIN_ADDRESS;
1389 * Find a slot in the physmap large enough for what we needed. We try to put
1390 * the shadow map as high up as we can to avoid depleting the lower 4GB in case
1391 * it's needed for, e.g., an xhci controller that can only do 32-bit DMA.
1393 for (i = (physmap_idx * 2) - 2; i >= 0 && nkasan_l2 > 0; i -= 2) {
1394 vm_paddr_t plow, phigh;
1396 /* L2 mappings must be backed by memory that is L2-aligned */
1397 plow = roundup2(physmap[i], L2_SIZE);
1398 phigh = physmap[i + 1];
1401 if (kernstart >= plow && kernstart < phigh)
1403 if (phigh - plow >= L2_SIZE)
1404 pmap_bootstrap_allocate_kasan_l2(plow, phigh, &va,
1409 panic("Could not find phys region for shadow map");
1412 * Done. We should now have a valid shadow address mapped for all KVA
1413 * that has been mapped so far, i.e., KERNBASE to virtual_avail. Thus,
1414 * shadow accesses by the kasan(9) runtime will succeed for this range.
1415 * When the kernel virtual address range is later expanded, as will
1416 * happen in vm_mem_init(), the shadow map will be grown as well. This
1417 * is handled by pmap_san_enter().
1423 * Initialize a vm_page's machine-dependent fields.
1426 pmap_page_init(vm_page_t m)
1429 TAILQ_INIT(&m->md.pv_list);
1430 m->md.pv_memattr = VM_MEMATTR_WRITE_BACK;
1434 pmap_init_asids(struct asid_set *set, int bits)
1438 set->asid_bits = bits;
1441 * We may be too early in the overall initialization process to use
1444 set->asid_set_size = 1 << set->asid_bits;
1445 set->asid_set = kmem_malloc(bitstr_size(set->asid_set_size),
1447 for (i = 0; i < ASID_FIRST_AVAILABLE; i++)
1448 bit_set(set->asid_set, i);
1449 set->asid_next = ASID_FIRST_AVAILABLE;
1450 mtx_init(&set->asid_set_mutex, "asid set", NULL, MTX_SPIN);
1454 pmap_init_pv_table(void)
1456 struct vm_phys_seg *seg, *next_seg;
1457 struct pmap_large_md_page *pvd;
1459 int domain, i, j, pages;
1462 * We strongly depend on the size being a power of two, so the assert
1463 * is overzealous. However, should the struct be resized to a
1464 * different power of two, the code below needs to be revisited.
1466 CTASSERT((sizeof(*pvd) == 64));
1469 * Calculate the size of the array.
1472 for (i = 0; i < vm_phys_nsegs; i++) {
1473 seg = &vm_phys_segs[i];
1474 pages = pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) -
1475 pmap_l2_pindex(seg->start);
1476 s += round_page(pages * sizeof(*pvd));
1478 pv_table = (struct pmap_large_md_page *)kva_alloc(s);
1479 if (pv_table == NULL)
1480 panic("%s: kva_alloc failed\n", __func__);
1483 * Iterate physical segments to allocate domain-local memory for PV
1487 for (i = 0; i < vm_phys_nsegs; i++) {
1488 seg = &vm_phys_segs[i];
1489 pages = pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) -
1490 pmap_l2_pindex(seg->start);
1491 domain = seg->domain;
1493 s = round_page(pages * sizeof(*pvd));
1495 for (j = 0; j < s; j += PAGE_SIZE) {
1496 vm_page_t m = vm_page_alloc_noobj_domain(domain,
1499 panic("failed to allocate PV table page");
1500 pmap_qenter((vm_offset_t)pvd + j, &m, 1);
1503 for (j = 0; j < s / sizeof(*pvd); j++) {
1504 rw_init_flags(&pvd->pv_lock, "pmap pv list", RW_NEW);
1505 TAILQ_INIT(&pvd->pv_page.pv_list);
1509 pvd = &pv_dummy_large;
1510 memset(pvd, 0, sizeof(*pvd));
1511 rw_init_flags(&pvd->pv_lock, "pmap pv list dummy", RW_NEW);
1512 TAILQ_INIT(&pvd->pv_page.pv_list);
1515 * Set pointers from vm_phys_segs to pv_table.
1517 for (i = 0, pvd = pv_table; i < vm_phys_nsegs; i++) {
1518 seg = &vm_phys_segs[i];
1519 seg->md_first = pvd;
1520 pvd += pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) -
1521 pmap_l2_pindex(seg->start);
1524 * If there is a following segment, and the final
1525 * superpage of this segment and the initial superpage
1526 * of the next segment are the same then adjust the
1527 * pv_table entry for that next segment down by one so
1528 * that the pv_table entries will be shared.
1530 if (i + 1 < vm_phys_nsegs) {
1531 next_seg = &vm_phys_segs[i + 1];
1532 if (pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) - 1 ==
1533 pmap_l2_pindex(next_seg->start)) {
1541 * Initialize the pmap module.
1542 * Called by vm_init, to initialize any structures that the pmap
1543 * system needs to map virtual memory.
1552 * Are large page mappings enabled?
1554 TUNABLE_INT_FETCH("vm.pmap.superpages_enabled", &superpages_enabled);
1555 if (superpages_enabled) {
1556 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1557 ("pmap_init: can't assign to pagesizes[1]"));
1558 pagesizes[1] = L2_SIZE;
1559 if (L1_BLOCKS_SUPPORTED) {
1560 KASSERT(MAXPAGESIZES > 2 && pagesizes[2] == 0,
1561 ("pmap_init: can't assign to pagesizes[2]"));
1562 pagesizes[2] = L1_SIZE;
1567 * Initialize the ASID allocator.
1569 pmap_init_asids(&asids,
1570 (READ_SPECIALREG(tcr_el1) & TCR_ASID_16) != 0 ? 16 : 8);
1573 mmfr1 = READ_SPECIALREG(id_aa64mmfr1_el1);
1576 if (ID_AA64MMFR1_VMIDBits_VAL(mmfr1) ==
1577 ID_AA64MMFR1_VMIDBits_16)
1579 pmap_init_asids(&vmids, vmid_bits);
1583 * Initialize pv chunk lists.
1585 for (i = 0; i < PMAP_MEMDOM; i++) {
1586 mtx_init(&pv_chunks[i].pvc_lock, "pmap pv chunk list", NULL,
1588 TAILQ_INIT(&pv_chunks[i].pvc_list);
1590 pmap_init_pv_table();
1595 static SYSCTL_NODE(_vm_pmap, OID_AUTO, l2, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
1596 "2MB page mapping counters");
1598 static u_long pmap_l2_demotions;
1599 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, demotions, CTLFLAG_RD,
1600 &pmap_l2_demotions, 0, "2MB page demotions");
1602 static u_long pmap_l2_mappings;
1603 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, mappings, CTLFLAG_RD,
1604 &pmap_l2_mappings, 0, "2MB page mappings");
1606 static u_long pmap_l2_p_failures;
1607 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, p_failures, CTLFLAG_RD,
1608 &pmap_l2_p_failures, 0, "2MB page promotion failures");
1610 static u_long pmap_l2_promotions;
1611 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, promotions, CTLFLAG_RD,
1612 &pmap_l2_promotions, 0, "2MB page promotions");
1615 * If the given value for "final_only" is false, then any cached intermediate-
1616 * level entries, i.e., L{0,1,2}_TABLE entries, are invalidated in addition to
1617 * any cached final-level entry, i.e., either an L{1,2}_BLOCK or L3_PAGE entry.
1618 * Otherwise, just the cached final-level entry is invalidated.
1620 static __inline void
1621 pmap_s1_invalidate_kernel(uint64_t r, bool final_only)
1624 __asm __volatile("tlbi vaale1is, %0" : : "r" (r));
1626 __asm __volatile("tlbi vaae1is, %0" : : "r" (r));
1629 static __inline void
1630 pmap_s1_invalidate_user(uint64_t r, bool final_only)
1633 __asm __volatile("tlbi vale1is, %0" : : "r" (r));
1635 __asm __volatile("tlbi vae1is, %0" : : "r" (r));
1639 * Invalidates any cached final- and optionally intermediate-level TLB entries
1640 * for the specified virtual address in the given virtual address space.
1642 static __inline void
1643 pmap_s1_invalidate_page(pmap_t pmap, vm_offset_t va, bool final_only)
1647 PMAP_ASSERT_STAGE1(pmap);
1651 if (pmap == kernel_pmap) {
1652 pmap_s1_invalidate_kernel(r, final_only);
1654 r |= ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
1655 pmap_s1_invalidate_user(r, final_only);
1661 static __inline void
1662 pmap_s2_invalidate_page(pmap_t pmap, vm_offset_t va, bool final_only)
1664 PMAP_ASSERT_STAGE2(pmap);
1665 MPASS(pmap_stage2_invalidate_range != NULL);
1666 pmap_stage2_invalidate_range(pmap_to_ttbr0(pmap), va, va + PAGE_SIZE,
1670 static __inline void
1671 pmap_invalidate_page(pmap_t pmap, vm_offset_t va, bool final_only)
1673 if (pmap->pm_stage == PM_STAGE1)
1674 pmap_s1_invalidate_page(pmap, va, final_only);
1676 pmap_s2_invalidate_page(pmap, va, final_only);
1680 * Invalidates any cached final- and optionally intermediate-level TLB entries
1681 * for the specified virtual address range in the given virtual address space.
1683 static __inline void
1684 pmap_s1_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1687 uint64_t end, r, start;
1689 PMAP_ASSERT_STAGE1(pmap);
1692 if (pmap == kernel_pmap) {
1693 start = TLBI_VA(sva);
1695 for (r = start; r < end; r += TLBI_VA_L3_INCR)
1696 pmap_s1_invalidate_kernel(r, final_only);
1698 start = end = ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
1699 start |= TLBI_VA(sva);
1700 end |= TLBI_VA(eva);
1701 for (r = start; r < end; r += TLBI_VA_L3_INCR)
1702 pmap_s1_invalidate_user(r, final_only);
1708 static __inline void
1709 pmap_s2_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1712 PMAP_ASSERT_STAGE2(pmap);
1713 MPASS(pmap_stage2_invalidate_range != NULL);
1714 pmap_stage2_invalidate_range(pmap_to_ttbr0(pmap), sva, eva, final_only);
1717 static __inline void
1718 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1721 if (pmap->pm_stage == PM_STAGE1)
1722 pmap_s1_invalidate_range(pmap, sva, eva, final_only);
1724 pmap_s2_invalidate_range(pmap, sva, eva, final_only);
1728 * Invalidates all cached intermediate- and final-level TLB entries for the
1729 * given virtual address space.
1731 static __inline void
1732 pmap_s1_invalidate_all(pmap_t pmap)
1736 PMAP_ASSERT_STAGE1(pmap);
1739 if (pmap == kernel_pmap) {
1740 __asm __volatile("tlbi vmalle1is");
1742 r = ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
1743 __asm __volatile("tlbi aside1is, %0" : : "r" (r));
1749 static __inline void
1750 pmap_s2_invalidate_all(pmap_t pmap)
1752 PMAP_ASSERT_STAGE2(pmap);
1753 MPASS(pmap_stage2_invalidate_all != NULL);
1754 pmap_stage2_invalidate_all(pmap_to_ttbr0(pmap));
1757 static __inline void
1758 pmap_invalidate_all(pmap_t pmap)
1760 if (pmap->pm_stage == PM_STAGE1)
1761 pmap_s1_invalidate_all(pmap);
1763 pmap_s2_invalidate_all(pmap);
1767 * Routine: pmap_extract
1769 * Extract the physical page address associated
1770 * with the given map/virtual_address pair.
1773 pmap_extract(pmap_t pmap, vm_offset_t va)
1775 pt_entry_t *pte, tpte;
1782 * Find the block or page map for this virtual address. pmap_pte
1783 * will return either a valid block/page entry, or NULL.
1785 pte = pmap_pte(pmap, va, &lvl);
1787 tpte = pmap_load(pte);
1788 pa = PTE_TO_PHYS(tpte);
1791 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
1792 KASSERT((tpte & ATTR_DESCR_MASK) == L1_BLOCK,
1793 ("pmap_extract: Invalid L1 pte found: %lx",
1794 tpte & ATTR_DESCR_MASK));
1795 pa |= (va & L1_OFFSET);
1798 KASSERT((tpte & ATTR_DESCR_MASK) == L2_BLOCK,
1799 ("pmap_extract: Invalid L2 pte found: %lx",
1800 tpte & ATTR_DESCR_MASK));
1801 pa |= (va & L2_OFFSET);
1804 KASSERT((tpte & ATTR_DESCR_MASK) == L3_PAGE,
1805 ("pmap_extract: Invalid L3 pte found: %lx",
1806 tpte & ATTR_DESCR_MASK));
1807 pa |= (va & L3_OFFSET);
1816 * Routine: pmap_extract_and_hold
1818 * Atomically extract and hold the physical page
1819 * with the given pmap and virtual address pair
1820 * if that mapping permits the given protection.
1823 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1825 pt_entry_t *pte, tpte;
1833 pte = pmap_pte(pmap, va, &lvl);
1835 tpte = pmap_load(pte);
1837 KASSERT(lvl > 0 && lvl <= 3,
1838 ("pmap_extract_and_hold: Invalid level %d", lvl));
1840 * Check that the pte is either a L3 page, or a L1 or L2 block
1841 * entry. We can assume L1_BLOCK == L2_BLOCK.
1843 KASSERT((lvl == 3 && (tpte & ATTR_DESCR_MASK) == L3_PAGE) ||
1844 (lvl < 3 && (tpte & ATTR_DESCR_MASK) == L1_BLOCK),
1845 ("pmap_extract_and_hold: Invalid pte at L%d: %lx", lvl,
1846 tpte & ATTR_DESCR_MASK));
1849 if ((prot & VM_PROT_WRITE) == 0)
1851 else if (pmap->pm_stage == PM_STAGE1 &&
1852 (tpte & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP(ATTR_S1_AP_RW))
1854 else if (pmap->pm_stage == PM_STAGE2 &&
1855 ((tpte & ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE)) ==
1856 ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE)))
1862 off = va & L1_OFFSET;
1865 off = va & L2_OFFSET;
1871 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tpte) | off);
1872 if (m != NULL && !vm_page_wire_mapped(m))
1881 * Walks the page tables to translate a kernel virtual address to a
1882 * physical address. Returns true if the kva is valid and stores the
1883 * physical address in pa if it is not NULL.
1885 * See the comment above data_abort() for the rationale for specifying
1886 * NO_PERTHREAD_SSP here.
1888 bool NO_PERTHREAD_SSP
1889 pmap_klookup(vm_offset_t va, vm_paddr_t *pa)
1891 pt_entry_t *pte, tpte;
1896 * Disable interrupts so we don't get interrupted between asking
1897 * for address translation, and getting the result back.
1899 intr = intr_disable();
1900 par = arm64_address_translate_s1e1r(va);
1903 if (PAR_SUCCESS(par)) {
1905 *pa = (par & PAR_PA_MASK) | (va & PAR_LOW_MASK);
1910 * Fall back to walking the page table. The address translation
1911 * instruction may fail when the page is in a break-before-make
1912 * sequence. As we only clear the valid bit in said sequence we
1913 * can walk the page table to find the physical address.
1916 pte = pmap_l1(kernel_pmap, va);
1921 * A concurrent pmap_update_entry() will clear the entry's valid bit
1922 * but leave the rest of the entry unchanged. Therefore, we treat a
1923 * non-zero entry as being valid, and we ignore the valid bit when
1924 * determining whether the entry maps a block, page, or table.
1926 tpte = pmap_load(pte);
1929 if ((tpte & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
1931 *pa = PTE_TO_PHYS(tpte) | (va & L1_OFFSET);
1934 pte = pmap_l1_to_l2(&tpte, va);
1935 tpte = pmap_load(pte);
1938 if ((tpte & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
1940 *pa = PTE_TO_PHYS(tpte) | (va & L2_OFFSET);
1943 pte = pmap_l2_to_l3(&tpte, va);
1944 tpte = pmap_load(pte);
1948 *pa = PTE_TO_PHYS(tpte) | (va & L3_OFFSET);
1953 pmap_kextract(vm_offset_t va)
1957 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
1958 return (DMAP_TO_PHYS(va));
1960 if (pmap_klookup(va, &pa) == false)
1965 /***************************************************
1966 * Low level mapping routines.....
1967 ***************************************************/
1970 pmap_kenter(vm_offset_t sva, vm_size_t size, vm_paddr_t pa, int mode)
1973 pt_entry_t attr, old_l3e, *pte;
1977 KASSERT((pa & L3_OFFSET) == 0,
1978 ("pmap_kenter: Invalid physical address"));
1979 KASSERT((sva & L3_OFFSET) == 0,
1980 ("pmap_kenter: Invalid virtual address"));
1981 KASSERT((size & PAGE_MASK) == 0,
1982 ("pmap_kenter: Mapping is not page-sized"));
1984 attr = ATTR_DEFAULT | ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_S1_XN |
1985 ATTR_S1_IDX(mode) | L3_PAGE;
1989 pde = pmap_pde(kernel_pmap, va, &lvl);
1990 KASSERT(pde != NULL,
1991 ("pmap_kenter: Invalid page entry, va: 0x%lx", va));
1992 KASSERT(lvl == 2, ("pmap_kenter: Invalid level %d", lvl));
1994 pte = pmap_l2_to_l3(pde, va);
1995 old_l3e |= pmap_load_store(pte, PHYS_TO_PTE(pa) | attr);
2001 if ((old_l3e & ATTR_DESCR_VALID) != 0)
2002 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
2005 * Because the old entries were invalid and the new mappings
2006 * are not executable, an isb is not required.
2013 pmap_kenter_device(vm_offset_t sva, vm_size_t size, vm_paddr_t pa)
2016 pmap_kenter(sva, size, pa, VM_MEMATTR_DEVICE);
2020 * Remove a page from the kernel pagetables.
2023 pmap_kremove(vm_offset_t va)
2027 pte = pmap_pte_exists(kernel_pmap, va, 3, __func__);
2029 pmap_s1_invalidate_page(kernel_pmap, va, true);
2033 * Remove the specified range of mappings from the kernel address space.
2035 * Should only be applied to mappings that were created by pmap_kenter() or
2036 * pmap_kenter_device(). Nothing about this function is actually specific
2037 * to device mappings.
2040 pmap_kremove_device(vm_offset_t sva, vm_size_t size)
2045 KASSERT((sva & L3_OFFSET) == 0,
2046 ("pmap_kremove_device: Invalid virtual address"));
2047 KASSERT((size & PAGE_MASK) == 0,
2048 ("pmap_kremove_device: Mapping is not page-sized"));
2052 pte = pmap_pte_exists(kernel_pmap, va, 3, __func__);
2058 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
2062 * Used to map a range of physical addresses into kernel
2063 * virtual address space.
2065 * The value passed in '*virt' is a suggested virtual address for
2066 * the mapping. Architectures which can support a direct-mapped
2067 * physical to virtual region can return the appropriate address
2068 * within that region, leaving '*virt' unchanged. Other
2069 * architectures should map the pages starting at '*virt' and
2070 * update '*virt' with the first usable address after the mapped
2074 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2076 return PHYS_TO_DMAP(start);
2080 * Add a list of wired pages to the kva
2081 * this routine is only used for temporary
2082 * kernel mappings that do not need to have
2083 * page modification or references recorded.
2084 * Note that old mappings are simply written
2085 * over. The page *must* be wired.
2086 * Note: SMP coherent. Uses a ranged shootdown IPI.
2089 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2092 pt_entry_t attr, old_l3e, pa, *pte;
2099 for (i = 0; i < count; i++) {
2100 pde = pmap_pde(kernel_pmap, va, &lvl);
2101 KASSERT(pde != NULL,
2102 ("pmap_qenter: Invalid page entry, va: 0x%lx", va));
2104 ("pmap_qenter: Invalid level %d", lvl));
2107 pa = VM_PAGE_TO_PHYS(m);
2108 attr = ATTR_DEFAULT | ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_S1_XN |
2109 ATTR_S1_IDX(m->md.pv_memattr) | L3_PAGE;
2110 pte = pmap_l2_to_l3(pde, va);
2111 old_l3e |= pmap_load_store(pte, PHYS_TO_PTE(pa) | attr);
2115 if ((old_l3e & ATTR_DESCR_VALID) != 0)
2116 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
2119 * Because the old entries were invalid and the new mappings
2120 * are not executable, an isb is not required.
2127 * This routine tears out page mappings from the
2128 * kernel -- it is meant only for temporary mappings.
2131 pmap_qremove(vm_offset_t sva, int count)
2136 KASSERT(ADDR_IS_CANONICAL(sva),
2137 ("%s: Address not in canonical form: %lx", __func__, sva));
2138 KASSERT(ADDR_IS_KERNEL(sva), ("usermode va %lx", sva));
2141 while (count-- > 0) {
2142 pte = pmap_pte_exists(kernel_pmap, va, 3, NULL);
2149 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
2152 /***************************************************
2153 * Page table page management routines.....
2154 ***************************************************/
2156 * Schedule the specified unused page table page to be freed. Specifically,
2157 * add the page to the specified list of pages that will be released to the
2158 * physical memory manager after the TLB has been updated.
2160 static __inline void
2161 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2162 boolean_t set_PG_ZERO)
2166 m->flags |= PG_ZERO;
2168 m->flags &= ~PG_ZERO;
2169 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2173 * Decrements a page table page's reference count, which is used to record the
2174 * number of valid page table entries within the page. If the reference count
2175 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2176 * page table page was unmapped and FALSE otherwise.
2178 static inline boolean_t
2179 pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2183 if (m->ref_count == 0) {
2184 _pmap_unwire_l3(pmap, va, m, free);
2191 _pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2194 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2196 * unmap the page table page
2198 if (m->pindex >= (NUL2E + NUL1E)) {
2202 l0 = pmap_l0(pmap, va);
2204 } else if (m->pindex >= NUL2E) {
2208 l1 = pmap_l1(pmap, va);
2214 l2 = pmap_l2(pmap, va);
2217 pmap_resident_count_dec(pmap, 1);
2218 if (m->pindex < NUL2E) {
2219 /* We just released an l3, unhold the matching l2 */
2220 pd_entry_t *l1, tl1;
2223 l1 = pmap_l1(pmap, va);
2224 tl1 = pmap_load(l1);
2225 l2pg = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tl1));
2226 pmap_unwire_l3(pmap, va, l2pg, free);
2227 } else if (m->pindex < (NUL2E + NUL1E)) {
2228 /* We just released an l2, unhold the matching l1 */
2229 pd_entry_t *l0, tl0;
2232 l0 = pmap_l0(pmap, va);
2233 tl0 = pmap_load(l0);
2234 l1pg = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tl0));
2235 pmap_unwire_l3(pmap, va, l1pg, free);
2237 pmap_invalidate_page(pmap, va, false);
2240 * Put page on a list so that it is released after
2241 * *ALL* TLB shootdown is done
2243 pmap_add_delayed_free_list(m, free, TRUE);
2247 * After removing a page table entry, this routine is used to
2248 * conditionally free the page, and manage the reference count.
2251 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2252 struct spglist *free)
2256 KASSERT(ADDR_IS_CANONICAL(va),
2257 ("%s: Address not in canonical form: %lx", __func__, va));
2258 if (ADDR_IS_KERNEL(va))
2260 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2261 mpte = PHYS_TO_VM_PAGE(PTE_TO_PHYS(ptepde));
2262 return (pmap_unwire_l3(pmap, va, mpte, free));
2266 * Release a page table page reference after a failed attempt to create a
2270 pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
2272 struct spglist free;
2275 if (pmap_unwire_l3(pmap, va, mpte, &free))
2276 vm_page_free_pages_toq(&free, true);
2280 pmap_pinit0(pmap_t pmap)
2283 PMAP_LOCK_INIT(pmap);
2284 bzero(&pmap->pm_stats, sizeof(pmap->pm_stats));
2285 pmap->pm_l0_paddr = READ_SPECIALREG(ttbr0_el1);
2286 pmap->pm_l0 = (pd_entry_t *)PHYS_TO_DMAP(pmap->pm_l0_paddr);
2287 TAILQ_INIT(&pmap->pm_pvchunk);
2288 vm_radix_init(&pmap->pm_root);
2289 pmap->pm_cookie = COOKIE_FROM(ASID_RESERVED_FOR_PID_0, INT_MIN);
2290 pmap->pm_stage = PM_STAGE1;
2291 pmap->pm_levels = 4;
2292 pmap->pm_ttbr = pmap->pm_l0_paddr;
2293 pmap->pm_asid_set = &asids;
2295 PCPU_SET(curpmap, pmap);
2299 pmap_pinit_stage(pmap_t pmap, enum pmap_stage stage, int levels)
2304 * allocate the l0 page
2306 m = vm_page_alloc_noobj(VM_ALLOC_WAITOK | VM_ALLOC_WIRED |
2308 pmap->pm_l0_paddr = VM_PAGE_TO_PHYS(m);
2309 pmap->pm_l0 = (pd_entry_t *)PHYS_TO_DMAP(pmap->pm_l0_paddr);
2311 TAILQ_INIT(&pmap->pm_pvchunk);
2312 vm_radix_init(&pmap->pm_root);
2313 bzero(&pmap->pm_stats, sizeof(pmap->pm_stats));
2314 pmap->pm_cookie = COOKIE_FROM(-1, INT_MAX);
2316 MPASS(levels == 3 || levels == 4);
2317 pmap->pm_levels = levels;
2318 pmap->pm_stage = stage;
2321 pmap->pm_asid_set = &asids;
2324 pmap->pm_asid_set = &vmids;
2327 panic("%s: Invalid pmap type %d", __func__, stage);
2331 /* XXX Temporarily disable deferred ASID allocation. */
2332 pmap_alloc_asid(pmap);
2335 * Allocate the level 1 entry to use as the root. This will increase
2336 * the refcount on the level 1 page so it won't be removed until
2337 * pmap_release() is called.
2339 if (pmap->pm_levels == 3) {
2341 m = _pmap_alloc_l3(pmap, NUL2E + NUL1E, NULL);
2344 pmap->pm_ttbr = VM_PAGE_TO_PHYS(m);
2350 pmap_pinit(pmap_t pmap)
2353 return (pmap_pinit_stage(pmap, PM_STAGE1, 4));
2357 * This routine is called if the desired page table page does not exist.
2359 * If page table page allocation fails, this routine may sleep before
2360 * returning NULL. It sleeps only if a lock pointer was given.
2362 * Note: If a page allocation fails at page table level two or three,
2363 * one or two pages may be held during the wait, only to be released
2364 * afterwards. This conservative approach is easily argued to avoid
2368 _pmap_alloc_l3(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2370 vm_page_t m, l1pg, l2pg;
2372 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2375 * Allocate a page table page.
2377 if ((m = vm_page_alloc_noobj(VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2378 if (lockp != NULL) {
2379 RELEASE_PV_LIST_LOCK(lockp);
2386 * Indicate the need to retry. While waiting, the page table
2387 * page may have been allocated.
2391 m->pindex = ptepindex;
2394 * Because of AArch64's weak memory consistency model, we must have a
2395 * barrier here to ensure that the stores for zeroing "m", whether by
2396 * pmap_zero_page() or an earlier function, are visible before adding
2397 * "m" to the page table. Otherwise, a page table walk by another
2398 * processor's MMU could see the mapping to "m" and a stale, non-zero
2404 * Map the pagetable page into the process address space, if
2405 * it isn't already there.
2408 if (ptepindex >= (NUL2E + NUL1E)) {
2409 pd_entry_t *l0p, l0e;
2410 vm_pindex_t l0index;
2412 l0index = ptepindex - (NUL2E + NUL1E);
2413 l0p = &pmap->pm_l0[l0index];
2414 KASSERT((pmap_load(l0p) & ATTR_DESCR_VALID) == 0,
2415 ("%s: L0 entry %#lx is valid", __func__, pmap_load(l0p)));
2416 l0e = PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) | L0_TABLE;
2419 * Mark all kernel memory as not accessible from userspace
2420 * and userspace memory as not executable from the kernel.
2421 * This has been done for the bootstrap L0 entries in
2424 if (pmap == kernel_pmap)
2425 l0e |= TATTR_UXN_TABLE | TATTR_AP_TABLE_NO_EL0;
2427 l0e |= TATTR_PXN_TABLE;
2428 pmap_store(l0p, l0e);
2429 } else if (ptepindex >= NUL2E) {
2430 vm_pindex_t l0index, l1index;
2431 pd_entry_t *l0, *l1;
2434 l1index = ptepindex - NUL2E;
2435 l0index = l1index >> Ln_ENTRIES_SHIFT;
2437 l0 = &pmap->pm_l0[l0index];
2438 tl0 = pmap_load(l0);
2440 /* recurse for allocating page dir */
2441 if (_pmap_alloc_l3(pmap, NUL2E + NUL1E + l0index,
2443 vm_page_unwire_noq(m);
2444 vm_page_free_zero(m);
2448 l1pg = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tl0));
2452 l1 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(pmap_load(l0)));
2453 l1 = &l1[ptepindex & Ln_ADDR_MASK];
2454 KASSERT((pmap_load(l1) & ATTR_DESCR_VALID) == 0,
2455 ("%s: L1 entry %#lx is valid", __func__, pmap_load(l1)));
2456 pmap_store(l1, PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) | L1_TABLE);
2458 vm_pindex_t l0index, l1index;
2459 pd_entry_t *l0, *l1, *l2;
2460 pd_entry_t tl0, tl1;
2462 l1index = ptepindex >> Ln_ENTRIES_SHIFT;
2463 l0index = l1index >> Ln_ENTRIES_SHIFT;
2465 l0 = &pmap->pm_l0[l0index];
2466 tl0 = pmap_load(l0);
2468 /* recurse for allocating page dir */
2469 if (_pmap_alloc_l3(pmap, NUL2E + l1index,
2471 vm_page_unwire_noq(m);
2472 vm_page_free_zero(m);
2475 tl0 = pmap_load(l0);
2476 l1 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(tl0));
2477 l1 = &l1[l1index & Ln_ADDR_MASK];
2479 l1 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(tl0));
2480 l1 = &l1[l1index & Ln_ADDR_MASK];
2481 tl1 = pmap_load(l1);
2483 /* recurse for allocating page dir */
2484 if (_pmap_alloc_l3(pmap, NUL2E + l1index,
2486 vm_page_unwire_noq(m);
2487 vm_page_free_zero(m);
2491 l2pg = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tl1));
2496 l2 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(pmap_load(l1)));
2497 l2 = &l2[ptepindex & Ln_ADDR_MASK];
2498 KASSERT((pmap_load(l2) & ATTR_DESCR_VALID) == 0,
2499 ("%s: L2 entry %#lx is valid", __func__, pmap_load(l2)));
2500 pmap_store(l2, PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) | L2_TABLE);
2503 pmap_resident_count_inc(pmap, 1);
2509 pmap_alloc_l2(pmap_t pmap, vm_offset_t va, vm_page_t *l2pgp,
2510 struct rwlock **lockp)
2512 pd_entry_t *l1, *l2;
2514 vm_pindex_t l2pindex;
2516 KASSERT(ADDR_IS_CANONICAL(va),
2517 ("%s: Address not in canonical form: %lx", __func__, va));
2520 l1 = pmap_l1(pmap, va);
2521 if (l1 != NULL && (pmap_load(l1) & ATTR_DESCR_MASK) == L1_TABLE) {
2522 l2 = pmap_l1_to_l2(l1, va);
2523 if (!ADDR_IS_KERNEL(va)) {
2524 /* Add a reference to the L2 page. */
2525 l2pg = PHYS_TO_VM_PAGE(PTE_TO_PHYS(pmap_load(l1)));
2529 } else if (!ADDR_IS_KERNEL(va)) {
2530 /* Allocate a L2 page. */
2531 l2pindex = pmap_l2_pindex(va) >> Ln_ENTRIES_SHIFT;
2532 l2pg = _pmap_alloc_l3(pmap, NUL2E + l2pindex, lockp);
2539 l2 = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(l2pg));
2540 l2 = &l2[pmap_l2_index(va)];
2542 panic("pmap_alloc_l2: missing page table page for va %#lx",
2549 pmap_alloc_l3(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2551 vm_pindex_t ptepindex;
2552 pd_entry_t *pde, tpde;
2560 * Calculate pagetable page index
2562 ptepindex = pmap_l2_pindex(va);
2565 * Get the page directory entry
2567 pde = pmap_pde(pmap, va, &lvl);
2570 * If the page table page is mapped, we just increment the hold count,
2571 * and activate it. If we get a level 2 pde it will point to a level 3
2579 pte = pmap_l0_to_l1(pde, va);
2580 KASSERT(pmap_load(pte) == 0,
2581 ("pmap_alloc_l3: TODO: l0 superpages"));
2586 pte = pmap_l1_to_l2(pde, va);
2587 KASSERT(pmap_load(pte) == 0,
2588 ("pmap_alloc_l3: TODO: l1 superpages"));
2592 tpde = pmap_load(pde);
2594 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tpde));
2600 panic("pmap_alloc_l3: Invalid level %d", lvl);
2604 * Here if the pte page isn't mapped, or if it has been deallocated.
2606 m = _pmap_alloc_l3(pmap, ptepindex, lockp);
2607 if (m == NULL && lockp != NULL)
2613 /***************************************************
2614 * Pmap allocation/deallocation routines.
2615 ***************************************************/
2618 * Release any resources held by the given physical map.
2619 * Called when a pmap initialized by pmap_pinit is being released.
2620 * Should only be called if the map contains no valid mappings.
2623 pmap_release(pmap_t pmap)
2625 boolean_t rv __diagused;
2626 struct spglist free;
2627 struct asid_set *set;
2631 if (pmap->pm_levels != 4) {
2632 PMAP_ASSERT_STAGE2(pmap);
2633 KASSERT(pmap->pm_stats.resident_count == 1,
2634 ("pmap_release: pmap resident count %ld != 0",
2635 pmap->pm_stats.resident_count));
2636 KASSERT((pmap->pm_l0[0] & ATTR_DESCR_VALID) == ATTR_DESCR_VALID,
2637 ("pmap_release: Invalid l0 entry: %lx", pmap->pm_l0[0]));
2640 m = PHYS_TO_VM_PAGE(pmap->pm_ttbr);
2642 rv = pmap_unwire_l3(pmap, 0, m, &free);
2645 vm_page_free_pages_toq(&free, true);
2648 KASSERT(pmap->pm_stats.resident_count == 0,
2649 ("pmap_release: pmap resident count %ld != 0",
2650 pmap->pm_stats.resident_count));
2651 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2652 ("pmap_release: pmap has reserved page table page(s)"));
2654 set = pmap->pm_asid_set;
2655 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
2658 * Allow the ASID to be reused. In stage 2 VMIDs we don't invalidate
2659 * the entries when removing them so rely on a later tlb invalidation.
2660 * this will happen when updating the VMID generation. Because of this
2661 * we don't reuse VMIDs within a generation.
2663 if (pmap->pm_stage == PM_STAGE1) {
2664 mtx_lock_spin(&set->asid_set_mutex);
2665 if (COOKIE_TO_EPOCH(pmap->pm_cookie) == set->asid_epoch) {
2666 asid = COOKIE_TO_ASID(pmap->pm_cookie);
2667 KASSERT(asid >= ASID_FIRST_AVAILABLE &&
2668 asid < set->asid_set_size,
2669 ("pmap_release: pmap cookie has out-of-range asid"));
2670 bit_clear(set->asid_set, asid);
2672 mtx_unlock_spin(&set->asid_set_mutex);
2675 m = PHYS_TO_VM_PAGE(pmap->pm_l0_paddr);
2676 vm_page_unwire_noq(m);
2677 vm_page_free_zero(m);
2681 kvm_size(SYSCTL_HANDLER_ARGS)
2683 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2685 return sysctl_handle_long(oidp, &ksize, 0, req);
2687 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
2688 0, 0, kvm_size, "LU",
2692 kvm_free(SYSCTL_HANDLER_ARGS)
2694 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2696 return sysctl_handle_long(oidp, &kfree, 0, req);
2698 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
2699 0, 0, kvm_free, "LU",
2700 "Amount of KVM free");
2703 * grow the number of kernel page table entries, if needed
2706 pmap_growkernel(vm_offset_t addr)
2710 pd_entry_t *l0, *l1, *l2;
2712 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2714 addr = roundup2(addr, L2_SIZE);
2715 if (addr - 1 >= vm_map_max(kernel_map))
2716 addr = vm_map_max(kernel_map);
2717 if (kernel_vm_end < addr)
2718 kasan_shadow_map(kernel_vm_end, addr - kernel_vm_end);
2719 while (kernel_vm_end < addr) {
2720 l0 = pmap_l0(kernel_pmap, kernel_vm_end);
2721 KASSERT(pmap_load(l0) != 0,
2722 ("pmap_growkernel: No level 0 kernel entry"));
2724 l1 = pmap_l0_to_l1(l0, kernel_vm_end);
2725 if (pmap_load(l1) == 0) {
2726 /* We need a new PDP entry */
2727 nkpg = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT |
2728 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2730 panic("pmap_growkernel: no memory to grow kernel");
2731 nkpg->pindex = kernel_vm_end >> L1_SHIFT;
2732 /* See the dmb() in _pmap_alloc_l3(). */
2734 paddr = VM_PAGE_TO_PHYS(nkpg);
2735 pmap_store(l1, PHYS_TO_PTE(paddr) | L1_TABLE);
2736 continue; /* try again */
2738 l2 = pmap_l1_to_l2(l1, kernel_vm_end);
2739 if (pmap_load(l2) != 0) {
2740 kernel_vm_end = (kernel_vm_end + L2_SIZE) & ~L2_OFFSET;
2741 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
2742 kernel_vm_end = vm_map_max(kernel_map);
2748 nkpg = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED |
2751 panic("pmap_growkernel: no memory to grow kernel");
2752 nkpg->pindex = kernel_vm_end >> L2_SHIFT;
2753 /* See the dmb() in _pmap_alloc_l3(). */
2755 paddr = VM_PAGE_TO_PHYS(nkpg);
2756 pmap_store(l2, PHYS_TO_PTE(paddr) | L2_TABLE);
2758 kernel_vm_end = (kernel_vm_end + L2_SIZE) & ~L2_OFFSET;
2759 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
2760 kernel_vm_end = vm_map_max(kernel_map);
2766 /***************************************************
2767 * page management routines.
2768 ***************************************************/
2770 static const uint64_t pc_freemask[_NPCM] = {
2771 [0 ... _NPCM - 2] = PC_FREEN,
2772 [_NPCM - 1] = PC_FREEL
2776 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2778 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2779 "Current number of pv entry chunks");
2780 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2781 "Current number of pv entry chunks allocated");
2782 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2783 "Current number of pv entry chunks frees");
2784 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
2785 "Number of times tried to get a chunk page but failed.");
2787 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
2788 static int pv_entry_spare;
2790 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2791 "Current number of pv entry frees");
2792 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
2793 "Current number of pv entry allocs");
2794 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2795 "Current number of pv entries");
2796 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2797 "Current number of spare pv entries");
2801 * We are in a serious low memory condition. Resort to
2802 * drastic measures to free some pages so we can allocate
2803 * another pv entry chunk.
2805 * Returns NULL if PV entries were reclaimed from the specified pmap.
2807 * We do not, however, unmap 2mpages because subsequent accesses will
2808 * allocate per-page pv entries until repromotion occurs, thereby
2809 * exacerbating the shortage of free pv entries.
2812 reclaim_pv_chunk_domain(pmap_t locked_pmap, struct rwlock **lockp, int domain)
2814 struct pv_chunks_list *pvc;
2815 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
2816 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
2817 struct md_page *pvh;
2819 pmap_t next_pmap, pmap;
2820 pt_entry_t *pte, tpte;
2824 struct spglist free;
2826 int bit, field, freed, lvl;
2828 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2829 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
2834 bzero(&pc_marker_b, sizeof(pc_marker_b));
2835 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
2836 pc_marker = (struct pv_chunk *)&pc_marker_b;
2837 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
2839 pvc = &pv_chunks[domain];
2840 mtx_lock(&pvc->pvc_lock);
2841 pvc->active_reclaims++;
2842 TAILQ_INSERT_HEAD(&pvc->pvc_list, pc_marker, pc_lru);
2843 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc_marker_end, pc_lru);
2844 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
2845 SLIST_EMPTY(&free)) {
2846 next_pmap = pc->pc_pmap;
2847 if (next_pmap == NULL) {
2849 * The next chunk is a marker. However, it is
2850 * not our marker, so active_reclaims must be
2851 * > 1. Consequently, the next_chunk code
2852 * will not rotate the pv_chunks list.
2856 mtx_unlock(&pvc->pvc_lock);
2859 * A pv_chunk can only be removed from the pc_lru list
2860 * when both pvc->pvc_lock is owned and the
2861 * corresponding pmap is locked.
2863 if (pmap != next_pmap) {
2864 if (pmap != NULL && pmap != locked_pmap)
2867 /* Avoid deadlock and lock recursion. */
2868 if (pmap > locked_pmap) {
2869 RELEASE_PV_LIST_LOCK(lockp);
2871 mtx_lock(&pvc->pvc_lock);
2873 } else if (pmap != locked_pmap) {
2874 if (PMAP_TRYLOCK(pmap)) {
2875 mtx_lock(&pvc->pvc_lock);
2878 pmap = NULL; /* pmap is not locked */
2879 mtx_lock(&pvc->pvc_lock);
2880 pc = TAILQ_NEXT(pc_marker, pc_lru);
2882 pc->pc_pmap != next_pmap)
2890 * Destroy every non-wired, 4 KB page mapping in the chunk.
2893 for (field = 0; field < _NPCM; field++) {
2894 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2895 inuse != 0; inuse &= ~(1UL << bit)) {
2896 bit = ffsl(inuse) - 1;
2897 pv = &pc->pc_pventry[field * 64 + bit];
2899 pde = pmap_pde(pmap, va, &lvl);
2902 pte = pmap_l2_to_l3(pde, va);
2903 tpte = pmap_load(pte);
2904 if ((tpte & ATTR_SW_WIRED) != 0)
2906 tpte = pmap_load_clear(pte);
2907 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tpte));
2908 if (pmap_pte_dirty(pmap, tpte))
2910 if ((tpte & ATTR_AF) != 0) {
2911 pmap_s1_invalidate_page(pmap, va, true);
2912 vm_page_aflag_set(m, PGA_REFERENCED);
2914 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
2915 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
2917 if (TAILQ_EMPTY(&m->md.pv_list) &&
2918 (m->flags & PG_FICTITIOUS) == 0) {
2919 pvh = page_to_pvh(m);
2920 if (TAILQ_EMPTY(&pvh->pv_list)) {
2921 vm_page_aflag_clear(m,
2925 pc->pc_map[field] |= 1UL << bit;
2926 pmap_unuse_pt(pmap, va, pmap_load(pde), &free);
2931 mtx_lock(&pvc->pvc_lock);
2934 /* Every freed mapping is for a 4 KB page. */
2935 pmap_resident_count_dec(pmap, freed);
2936 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
2937 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
2938 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
2939 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2940 if (pc_is_free(pc)) {
2941 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
2942 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
2943 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
2944 /* Entire chunk is free; return it. */
2945 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
2946 dump_drop_page(m_pc->phys_addr);
2947 mtx_lock(&pvc->pvc_lock);
2948 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
2951 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2952 mtx_lock(&pvc->pvc_lock);
2953 /* One freed pv entry in locked_pmap is sufficient. */
2954 if (pmap == locked_pmap)
2958 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
2959 TAILQ_INSERT_AFTER(&pvc->pvc_list, pc, pc_marker, pc_lru);
2960 if (pvc->active_reclaims == 1 && pmap != NULL) {
2962 * Rotate the pv chunks list so that we do not
2963 * scan the same pv chunks that could not be
2964 * freed (because they contained a wired
2965 * and/or superpage mapping) on every
2966 * invocation of reclaim_pv_chunk().
2968 while ((pc = TAILQ_FIRST(&pvc->pvc_list)) != pc_marker){
2969 MPASS(pc->pc_pmap != NULL);
2970 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
2971 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
2975 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
2976 TAILQ_REMOVE(&pvc->pvc_list, pc_marker_end, pc_lru);
2977 pvc->active_reclaims--;
2978 mtx_unlock(&pvc->pvc_lock);
2979 if (pmap != NULL && pmap != locked_pmap)
2981 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
2982 m_pc = SLIST_FIRST(&free);
2983 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2984 /* Recycle a freed page table page. */
2985 m_pc->ref_count = 1;
2987 vm_page_free_pages_toq(&free, true);
2992 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
2997 domain = PCPU_GET(domain);
2998 for (i = 0; i < vm_ndomains; i++) {
2999 m = reclaim_pv_chunk_domain(locked_pmap, lockp, domain);
3002 domain = (domain + 1) % vm_ndomains;
3009 * free the pv_entry back to the free list
3012 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3014 struct pv_chunk *pc;
3015 int idx, field, bit;
3017 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3018 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3019 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3020 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3021 pc = pv_to_chunk(pv);
3022 idx = pv - &pc->pc_pventry[0];
3025 pc->pc_map[field] |= 1ul << bit;
3026 if (!pc_is_free(pc)) {
3027 /* 98% of the time, pc is already at the head of the list. */
3028 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3029 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3030 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3034 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3039 free_pv_chunk_dequeued(struct pv_chunk *pc)
3043 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3044 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3045 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3046 /* entire chunk is free, return it */
3047 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3048 dump_drop_page(m->phys_addr);
3049 vm_page_unwire_noq(m);
3054 free_pv_chunk(struct pv_chunk *pc)
3056 struct pv_chunks_list *pvc;
3058 pvc = &pv_chunks[pc_to_domain(pc)];
3059 mtx_lock(&pvc->pvc_lock);
3060 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
3061 mtx_unlock(&pvc->pvc_lock);
3062 free_pv_chunk_dequeued(pc);
3066 free_pv_chunk_batch(struct pv_chunklist *batch)
3068 struct pv_chunks_list *pvc;
3069 struct pv_chunk *pc, *npc;
3072 for (i = 0; i < vm_ndomains; i++) {
3073 if (TAILQ_EMPTY(&batch[i]))
3075 pvc = &pv_chunks[i];
3076 mtx_lock(&pvc->pvc_lock);
3077 TAILQ_FOREACH(pc, &batch[i], pc_list) {
3078 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
3080 mtx_unlock(&pvc->pvc_lock);
3083 for (i = 0; i < vm_ndomains; i++) {
3084 TAILQ_FOREACH_SAFE(pc, &batch[i], pc_list, npc) {
3085 free_pv_chunk_dequeued(pc);
3091 * Returns a new PV entry, allocating a new PV chunk from the system when
3092 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3093 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3096 * The given PV list lock may be released.
3099 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3101 struct pv_chunks_list *pvc;
3104 struct pv_chunk *pc;
3107 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3108 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3110 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3112 for (field = 0; field < _NPCM; field++) {
3113 if (pc->pc_map[field]) {
3114 bit = ffsl(pc->pc_map[field]) - 1;
3118 if (field < _NPCM) {
3119 pv = &pc->pc_pventry[field * 64 + bit];
3120 pc->pc_map[field] &= ~(1ul << bit);
3121 /* If this was the last item, move it to tail */
3122 if (pc_is_full(pc)) {
3123 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3124 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3127 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3128 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3132 /* No free items, allocate another chunk */
3133 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
3135 if (lockp == NULL) {
3136 PV_STAT(pc_chunk_tryfail++);
3139 m = reclaim_pv_chunk(pmap, lockp);
3143 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3144 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3145 dump_add_page(m->phys_addr);
3146 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3148 memcpy(pc->pc_map, pc_freemask, sizeof(pc_freemask));
3149 pc->pc_map[0] &= ~1ul; /* preallocated bit 0 */
3150 pvc = &pv_chunks[vm_page_domain(m)];
3151 mtx_lock(&pvc->pvc_lock);
3152 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
3153 mtx_unlock(&pvc->pvc_lock);
3154 pv = &pc->pc_pventry[0];
3155 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3156 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3157 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3162 * Ensure that the number of spare PV entries in the specified pmap meets or
3163 * exceeds the given count, "needed".
3165 * The given PV list lock may be released.
3168 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3170 struct pv_chunks_list *pvc;
3171 struct pch new_tail[PMAP_MEMDOM];
3172 struct pv_chunk *pc;
3177 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3178 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3181 * Newly allocated PV chunks must be stored in a private list until
3182 * the required number of PV chunks have been allocated. Otherwise,
3183 * reclaim_pv_chunk() could recycle one of these chunks. In
3184 * contrast, these chunks must be added to the pmap upon allocation.
3186 for (i = 0; i < PMAP_MEMDOM; i++)
3187 TAILQ_INIT(&new_tail[i]);
3190 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3191 bit_count((bitstr_t *)pc->pc_map, 0,
3192 sizeof(pc->pc_map) * NBBY, &free);
3196 if (avail >= needed)
3199 for (reclaimed = false; avail < needed; avail += _NPCPV) {
3200 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
3202 m = reclaim_pv_chunk(pmap, lockp);
3207 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3208 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3209 dump_add_page(m->phys_addr);
3210 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3212 memcpy(pc->pc_map, pc_freemask, sizeof(pc_freemask));
3213 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3214 TAILQ_INSERT_TAIL(&new_tail[vm_page_domain(m)], pc, pc_lru);
3215 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3218 * The reclaim might have freed a chunk from the current pmap.
3219 * If that chunk contained available entries, we need to
3220 * re-count the number of available entries.
3225 for (i = 0; i < vm_ndomains; i++) {
3226 if (TAILQ_EMPTY(&new_tail[i]))
3228 pvc = &pv_chunks[i];
3229 mtx_lock(&pvc->pvc_lock);
3230 TAILQ_CONCAT(&pvc->pvc_list, &new_tail[i], pc_lru);
3231 mtx_unlock(&pvc->pvc_lock);
3236 * First find and then remove the pv entry for the specified pmap and virtual
3237 * address from the specified pv list. Returns the pv entry if found and NULL
3238 * otherwise. This operation can be performed on pv lists for either 4KB or
3239 * 2MB page mappings.
3241 static __inline pv_entry_t
3242 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3246 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3247 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3248 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3257 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3258 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3259 * entries for each of the 4KB page mappings.
3262 pmap_pv_demote_l2(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3263 struct rwlock **lockp)
3265 struct md_page *pvh;
3266 struct pv_chunk *pc;
3268 vm_offset_t va_last;
3272 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3273 KASSERT((va & L2_OFFSET) == 0,
3274 ("pmap_pv_demote_l2: va is not 2mpage aligned"));
3275 KASSERT((pa & L2_OFFSET) == 0,
3276 ("pmap_pv_demote_l2: pa is not 2mpage aligned"));
3277 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3280 * Transfer the 2mpage's pv entry for this mapping to the first
3281 * page's pv list. Once this transfer begins, the pv list lock
3282 * must not be released until the last pv entry is reinstantiated.
3284 pvh = pa_to_pvh(pa);
3285 pv = pmap_pvh_remove(pvh, pmap, va);
3286 KASSERT(pv != NULL, ("pmap_pv_demote_l2: pv not found"));
3287 m = PHYS_TO_VM_PAGE(pa);
3288 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3290 /* Instantiate the remaining Ln_ENTRIES - 1 pv entries. */
3291 PV_STAT(atomic_add_long(&pv_entry_allocs, Ln_ENTRIES - 1));
3292 va_last = va + L2_SIZE - PAGE_SIZE;
3294 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3295 KASSERT(!pc_is_full(pc), ("pmap_pv_demote_l2: missing spare"));
3296 for (field = 0; field < _NPCM; field++) {
3297 while (pc->pc_map[field]) {
3298 bit = ffsl(pc->pc_map[field]) - 1;
3299 pc->pc_map[field] &= ~(1ul << bit);
3300 pv = &pc->pc_pventry[field * 64 + bit];
3304 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3305 ("pmap_pv_demote_l2: page %p is not managed", m));
3306 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3312 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3313 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3316 if (pc_is_full(pc)) {
3317 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3318 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3320 PV_STAT(atomic_add_long(&pv_entry_count, Ln_ENTRIES - 1));
3321 PV_STAT(atomic_subtract_int(&pv_entry_spare, Ln_ENTRIES - 1));
3325 * First find and then destroy the pv entry for the specified pmap and virtual
3326 * address. This operation can be performed on pv lists for either 4KB or 2MB
3330 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3334 pv = pmap_pvh_remove(pvh, pmap, va);
3335 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3336 free_pv_entry(pmap, pv);
3340 * Conditionally create the PV entry for a 4KB page mapping if the required
3341 * memory can be allocated without resorting to reclamation.
3344 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3345 struct rwlock **lockp)
3349 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3350 /* Pass NULL instead of the lock pointer to disable reclamation. */
3351 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3353 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3354 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3362 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3363 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3364 * false if the PV entry cannot be allocated without resorting to reclamation.
3367 pmap_pv_insert_l2(pmap_t pmap, vm_offset_t va, pd_entry_t l2e, u_int flags,
3368 struct rwlock **lockp)
3370 struct md_page *pvh;
3374 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3375 /* Pass NULL instead of the lock pointer to disable reclamation. */
3376 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3377 NULL : lockp)) == NULL)
3380 pa = PTE_TO_PHYS(l2e);
3381 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3382 pvh = pa_to_pvh(pa);
3383 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3389 pmap_remove_kernel_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va)
3391 pt_entry_t newl2, oldl2 __diagused;
3395 KASSERT(!VIRT_IN_DMAP(va), ("removing direct mapping of %#lx", va));
3396 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3397 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3399 ml3 = pmap_remove_pt_page(pmap, va);
3401 panic("pmap_remove_kernel_l2: Missing pt page");
3403 ml3pa = VM_PAGE_TO_PHYS(ml3);
3404 newl2 = PHYS_TO_PTE(ml3pa) | L2_TABLE;
3407 * If this page table page was unmapped by a promotion, then it
3408 * contains valid mappings. Zero it to invalidate those mappings.
3410 if (vm_page_any_valid(ml3))
3411 pagezero((void *)PHYS_TO_DMAP(ml3pa));
3414 * Demote the mapping. The caller must have already invalidated the
3415 * mapping (i.e., the "break" in break-before-make).
3417 oldl2 = pmap_load_store(l2, newl2);
3418 KASSERT(oldl2 == 0, ("%s: found existing mapping at %p: %#lx",
3419 __func__, l2, oldl2));
3423 * pmap_remove_l2: Do the things to unmap a level 2 superpage.
3426 pmap_remove_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva,
3427 pd_entry_t l1e, struct spglist *free, struct rwlock **lockp)
3429 struct md_page *pvh;
3431 vm_page_t m, ml3, mt;
3433 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3434 KASSERT((sva & L2_OFFSET) == 0, ("pmap_remove_l2: sva is not aligned"));
3435 old_l2 = pmap_load_clear(l2);
3436 KASSERT((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK,
3437 ("pmap_remove_l2: L2e %lx is not a block mapping", old_l2));
3440 * Since a promotion must break the 4KB page mappings before making
3441 * the 2MB page mapping, a pmap_s1_invalidate_page() suffices.
3443 pmap_s1_invalidate_page(pmap, sva, true);
3445 if (old_l2 & ATTR_SW_WIRED)
3446 pmap->pm_stats.wired_count -= L2_SIZE / PAGE_SIZE;
3447 pmap_resident_count_dec(pmap, L2_SIZE / PAGE_SIZE);
3448 if (old_l2 & ATTR_SW_MANAGED) {
3449 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(old_l2));
3450 pvh = page_to_pvh(m);
3451 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3452 pmap_pvh_free(pvh, pmap, sva);
3453 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++) {
3454 if (pmap_pte_dirty(pmap, old_l2))
3456 if (old_l2 & ATTR_AF)
3457 vm_page_aflag_set(mt, PGA_REFERENCED);
3458 if (TAILQ_EMPTY(&mt->md.pv_list) &&
3459 TAILQ_EMPTY(&pvh->pv_list))
3460 vm_page_aflag_clear(mt, PGA_WRITEABLE);
3463 if (pmap == kernel_pmap) {
3464 pmap_remove_kernel_l2(pmap, l2, sva);
3466 ml3 = pmap_remove_pt_page(pmap, sva);
3468 KASSERT(vm_page_any_valid(ml3),
3469 ("pmap_remove_l2: l3 page not promoted"));
3470 pmap_resident_count_dec(pmap, 1);
3471 KASSERT(ml3->ref_count == NL3PG,
3472 ("pmap_remove_l2: l3 page ref count error"));
3474 pmap_add_delayed_free_list(ml3, free, FALSE);
3477 return (pmap_unuse_pt(pmap, sva, l1e, free));
3481 * pmap_remove_l3: do the things to unmap a page in a process
3484 pmap_remove_l3(pmap_t pmap, pt_entry_t *l3, vm_offset_t va,
3485 pd_entry_t l2e, struct spglist *free, struct rwlock **lockp)
3487 struct md_page *pvh;
3491 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3492 old_l3 = pmap_load_clear(l3);
3493 pmap_s1_invalidate_page(pmap, va, true);
3494 if (old_l3 & ATTR_SW_WIRED)
3495 pmap->pm_stats.wired_count -= 1;
3496 pmap_resident_count_dec(pmap, 1);
3497 if (old_l3 & ATTR_SW_MANAGED) {
3498 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(old_l3));
3499 if (pmap_pte_dirty(pmap, old_l3))
3501 if (old_l3 & ATTR_AF)
3502 vm_page_aflag_set(m, PGA_REFERENCED);
3503 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3504 pmap_pvh_free(&m->md, pmap, va);
3505 if (TAILQ_EMPTY(&m->md.pv_list) &&
3506 (m->flags & PG_FICTITIOUS) == 0) {
3507 pvh = page_to_pvh(m);
3508 if (TAILQ_EMPTY(&pvh->pv_list))
3509 vm_page_aflag_clear(m, PGA_WRITEABLE);
3512 return (pmap_unuse_pt(pmap, va, l2e, free));
3516 * Remove the specified range of addresses from the L3 page table that is
3517 * identified by the given L2 entry.
3520 pmap_remove_l3_range(pmap_t pmap, pd_entry_t l2e, vm_offset_t sva,
3521 vm_offset_t eva, struct spglist *free, struct rwlock **lockp)
3523 struct md_page *pvh;
3524 struct rwlock *new_lock;
3525 pt_entry_t *l3, old_l3;
3529 KASSERT(ADDR_IS_CANONICAL(sva),
3530 ("%s: Start address not in canonical form: %lx", __func__, sva));
3531 KASSERT(ADDR_IS_CANONICAL(eva) || eva == VM_MAX_USER_ADDRESS,
3532 ("%s: End address not in canonical form: %lx", __func__, eva));
3534 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3535 KASSERT(rounddown2(sva, L2_SIZE) + L2_SIZE == roundup2(eva, L2_SIZE),
3536 ("pmap_remove_l3_range: range crosses an L3 page table boundary"));
3537 l3pg = !ADDR_IS_KERNEL(sva) ? PHYS_TO_VM_PAGE(PTE_TO_PHYS(l2e)) : NULL;
3539 for (l3 = pmap_l2_to_l3(&l2e, sva); sva != eva; l3++, sva += L3_SIZE) {
3540 if (!pmap_l3_valid(pmap_load(l3))) {
3542 pmap_invalidate_range(pmap, va, sva, true);
3547 old_l3 = pmap_load_clear(l3);
3548 if ((old_l3 & ATTR_SW_WIRED) != 0)
3549 pmap->pm_stats.wired_count--;
3550 pmap_resident_count_dec(pmap, 1);
3551 if ((old_l3 & ATTR_SW_MANAGED) != 0) {
3552 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(old_l3));
3553 if (pmap_pte_dirty(pmap, old_l3))
3555 if ((old_l3 & ATTR_AF) != 0)
3556 vm_page_aflag_set(m, PGA_REFERENCED);
3557 new_lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3558 if (new_lock != *lockp) {
3559 if (*lockp != NULL) {
3561 * Pending TLB invalidations must be
3562 * performed before the PV list lock is
3563 * released. Otherwise, a concurrent
3564 * pmap_remove_all() on a physical page
3565 * could return while a stale TLB entry
3566 * still provides access to that page.
3569 pmap_invalidate_range(pmap, va,
3578 pmap_pvh_free(&m->md, pmap, sva);
3579 if (TAILQ_EMPTY(&m->md.pv_list) &&
3580 (m->flags & PG_FICTITIOUS) == 0) {
3581 pvh = page_to_pvh(m);
3582 if (TAILQ_EMPTY(&pvh->pv_list))
3583 vm_page_aflag_clear(m, PGA_WRITEABLE);
3586 if (l3pg != NULL && pmap_unwire_l3(pmap, sva, l3pg, free)) {
3588 * _pmap_unwire_l3() has already invalidated the TLB
3589 * entries at all levels for "sva". So, we need not
3590 * perform "sva += L3_SIZE;" here. Moreover, we need
3591 * not perform "va = sva;" if "sva" is at the start
3592 * of a new valid range consisting of a single page.
3600 pmap_invalidate_range(pmap, va, sva, true);
3604 * Remove the given range of addresses from the specified map.
3606 * It is assumed that the start and end are properly
3607 * rounded to the page size.
3610 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3612 struct rwlock *lock;
3613 vm_offset_t va_next;
3614 pd_entry_t *l0, *l1, *l2;
3615 pt_entry_t l3_paddr;
3616 struct spglist free;
3619 * Perform an unsynchronized read. This is, however, safe.
3621 if (pmap->pm_stats.resident_count == 0)
3629 for (; sva < eva; sva = va_next) {
3630 if (pmap->pm_stats.resident_count == 0)
3633 l0 = pmap_l0(pmap, sva);
3634 if (pmap_load(l0) == 0) {
3635 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
3641 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
3644 l1 = pmap_l0_to_l1(l0, sva);
3645 if (pmap_load(l1) == 0)
3647 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
3648 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
3649 KASSERT(va_next <= eva,
3650 ("partial update of non-transparent 1G page "
3651 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
3652 pmap_load(l1), sva, eva, va_next));
3653 MPASS(pmap != kernel_pmap);
3654 MPASS((pmap_load(l1) & ATTR_SW_MANAGED) == 0);
3656 pmap_s1_invalidate_page(pmap, sva, true);
3657 pmap_resident_count_dec(pmap, L1_SIZE / PAGE_SIZE);
3658 pmap_unuse_pt(pmap, sva, pmap_load(l0), &free);
3663 * Calculate index for next page table.
3665 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
3669 l2 = pmap_l1_to_l2(l1, sva);
3673 l3_paddr = pmap_load(l2);
3675 if ((l3_paddr & ATTR_DESCR_MASK) == L2_BLOCK) {
3676 if (sva + L2_SIZE == va_next && eva >= va_next) {
3677 pmap_remove_l2(pmap, l2, sva, pmap_load(l1),
3680 } else if (pmap_demote_l2_locked(pmap, l2, sva,
3683 l3_paddr = pmap_load(l2);
3687 * Weed out invalid mappings.
3689 if ((l3_paddr & ATTR_DESCR_MASK) != L2_TABLE)
3693 * Limit our scan to either the end of the va represented
3694 * by the current page table page, or to the end of the
3695 * range being removed.
3700 pmap_remove_l3_range(pmap, l3_paddr, sva, va_next, &free,
3706 vm_page_free_pages_toq(&free, true);
3710 * Remove the given range of addresses as part of a logical unmap
3711 * operation. This has the effect of calling pmap_remove(), but
3712 * also clears any metadata that should persist for the lifetime
3713 * of a logical mapping.
3716 pmap_map_delete(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3718 pmap_remove(pmap, sva, eva);
3722 * Routine: pmap_remove_all
3724 * Removes this physical page from
3725 * all physical maps in which it resides.
3726 * Reflects back modify bits to the pager.
3729 * Original versions of this routine were very
3730 * inefficient because they iteratively called
3731 * pmap_remove (slow...)
3735 pmap_remove_all(vm_page_t m)
3737 struct md_page *pvh;
3740 struct rwlock *lock;
3741 pd_entry_t *pde, tpde;
3742 pt_entry_t *pte, tpte;
3744 struct spglist free;
3745 int lvl, pvh_gen, md_gen;
3747 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3748 ("pmap_remove_all: page %p is not managed", m));
3750 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3751 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
3754 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
3756 if (!PMAP_TRYLOCK(pmap)) {
3757 pvh_gen = pvh->pv_gen;
3761 if (pvh_gen != pvh->pv_gen) {
3767 pte = pmap_pte_exists(pmap, va, 2, __func__);
3768 pmap_demote_l2_locked(pmap, pte, va, &lock);
3771 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3773 if (!PMAP_TRYLOCK(pmap)) {
3774 pvh_gen = pvh->pv_gen;
3775 md_gen = m->md.pv_gen;
3779 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
3784 pmap_resident_count_dec(pmap, 1);
3786 pde = pmap_pde(pmap, pv->pv_va, &lvl);
3787 KASSERT(pde != NULL,
3788 ("pmap_remove_all: no page directory entry found"));
3790 ("pmap_remove_all: invalid pde level %d", lvl));
3791 tpde = pmap_load(pde);
3793 pte = pmap_l2_to_l3(pde, pv->pv_va);
3794 tpte = pmap_load_clear(pte);
3795 if (tpte & ATTR_SW_WIRED)
3796 pmap->pm_stats.wired_count--;
3797 if ((tpte & ATTR_AF) != 0) {
3798 pmap_invalidate_page(pmap, pv->pv_va, true);
3799 vm_page_aflag_set(m, PGA_REFERENCED);
3803 * Update the vm_page_t clean and reference bits.
3805 if (pmap_pte_dirty(pmap, tpte))
3807 pmap_unuse_pt(pmap, pv->pv_va, tpde, &free);
3808 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3810 free_pv_entry(pmap, pv);
3813 vm_page_aflag_clear(m, PGA_WRITEABLE);
3815 vm_page_free_pages_toq(&free, true);
3819 * Masks and sets bits in a level 2 page table entries in the specified pmap
3822 pmap_protect_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva, pt_entry_t mask,
3828 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3829 PMAP_ASSERT_STAGE1(pmap);
3830 KASSERT((sva & L2_OFFSET) == 0,
3831 ("pmap_protect_l2: sva is not 2mpage aligned"));
3832 old_l2 = pmap_load(l2);
3833 KASSERT((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK,
3834 ("pmap_protect_l2: L2e %lx is not a block mapping", old_l2));
3837 * Return if the L2 entry already has the desired access restrictions
3840 if ((old_l2 & mask) == nbits)
3843 while (!atomic_fcmpset_64(l2, &old_l2, (old_l2 & ~mask) | nbits))
3847 * When a dirty read/write superpage mapping is write protected,
3848 * update the dirty field of each of the superpage's constituent 4KB
3851 if ((old_l2 & ATTR_SW_MANAGED) != 0 &&
3852 (nbits & ATTR_S1_AP(ATTR_S1_AP_RO)) != 0 &&
3853 pmap_pte_dirty(pmap, old_l2)) {
3854 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(old_l2));
3855 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
3860 * Since a promotion must break the 4KB page mappings before making
3861 * the 2MB page mapping, a pmap_s1_invalidate_page() suffices.
3863 pmap_s1_invalidate_page(pmap, sva, true);
3867 * Masks and sets bits in last level page table entries in the specified
3871 pmap_mask_set_locked(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, pt_entry_t mask,
3872 pt_entry_t nbits, bool invalidate)
3874 vm_offset_t va, va_next;
3875 pd_entry_t *l0, *l1, *l2;
3876 pt_entry_t *l3p, l3;
3878 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3879 for (; sva < eva; sva = va_next) {
3880 l0 = pmap_l0(pmap, sva);
3881 if (pmap_load(l0) == 0) {
3882 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
3888 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
3891 l1 = pmap_l0_to_l1(l0, sva);
3892 if (pmap_load(l1) == 0)
3894 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
3895 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
3896 KASSERT(va_next <= eva,
3897 ("partial update of non-transparent 1G page "
3898 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
3899 pmap_load(l1), sva, eva, va_next));
3900 MPASS((pmap_load(l1) & ATTR_SW_MANAGED) == 0);
3901 if ((pmap_load(l1) & mask) != nbits) {
3902 pmap_store(l1, (pmap_load(l1) & ~mask) | nbits);
3904 pmap_s1_invalidate_page(pmap, sva, true);
3909 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
3913 l2 = pmap_l1_to_l2(l1, sva);
3914 if (pmap_load(l2) == 0)
3917 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK) {
3918 if (sva + L2_SIZE == va_next && eva >= va_next) {
3919 pmap_protect_l2(pmap, l2, sva, mask, nbits);
3921 } else if (pmap_demote_l2(pmap, l2, sva) == NULL)
3924 KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
3925 ("pmap_protect: Invalid L2 entry after demotion"));
3931 for (l3p = pmap_l2_to_l3(l2, sva); sva != va_next; l3p++,
3933 l3 = pmap_load(l3p);
3936 * Go to the next L3 entry if the current one is
3937 * invalid or already has the desired access
3938 * restrictions in place. (The latter case occurs
3939 * frequently. For example, in a "buildworld"
3940 * workload, almost 1 out of 4 L3 entries already
3941 * have the desired restrictions.)
3943 if (!pmap_l3_valid(l3) || (l3 & mask) == nbits) {
3944 if (va != va_next) {
3946 pmap_s1_invalidate_range(pmap,
3953 while (!atomic_fcmpset_64(l3p, &l3, (l3 & ~mask) |
3958 * When a dirty read/write mapping is write protected,
3959 * update the page's dirty field.
3961 if ((l3 & ATTR_SW_MANAGED) != 0 &&
3962 (nbits & ATTR_S1_AP(ATTR_S1_AP_RO)) != 0 &&
3963 pmap_pte_dirty(pmap, l3))
3964 vm_page_dirty(PHYS_TO_VM_PAGE(PTE_TO_PHYS(l3)));
3969 if (va != va_next && invalidate)
3970 pmap_s1_invalidate_range(pmap, va, sva, true);
3975 pmap_mask_set(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, pt_entry_t mask,
3976 pt_entry_t nbits, bool invalidate)
3979 pmap_mask_set_locked(pmap, sva, eva, mask, nbits, invalidate);
3984 * Set the physical protection on the
3985 * specified range of this map as requested.
3988 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
3990 pt_entry_t mask, nbits;
3992 PMAP_ASSERT_STAGE1(pmap);
3993 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
3994 if (prot == VM_PROT_NONE) {
3995 pmap_remove(pmap, sva, eva);
4000 if ((prot & VM_PROT_WRITE) == 0) {
4001 mask |= ATTR_S1_AP_RW_BIT | ATTR_SW_DBM;
4002 nbits |= ATTR_S1_AP(ATTR_S1_AP_RO);
4004 if ((prot & VM_PROT_EXECUTE) == 0) {
4006 nbits |= ATTR_S1_XN;
4011 pmap_mask_set(pmap, sva, eva, mask, nbits, true);
4015 pmap_disable_promotion(vm_offset_t sva, vm_size_t size)
4018 MPASS((sva & L3_OFFSET) == 0);
4019 MPASS(((sva + size) & L3_OFFSET) == 0);
4021 pmap_mask_set(kernel_pmap, sva, sva + size, ATTR_SW_NO_PROMOTE,
4022 ATTR_SW_NO_PROMOTE, false);
4026 * Inserts the specified page table page into the specified pmap's collection
4027 * of idle page table pages. Each of a pmap's page table pages is responsible
4028 * for mapping a distinct range of virtual addresses. The pmap's collection is
4029 * ordered by this virtual address range.
4031 * If "promoted" is false, then the page table page "mpte" must be zero filled;
4032 * "mpte"'s valid field will be set to 0.
4034 * If "promoted" is true and "all_l3e_AF_set" is false, then "mpte" must
4035 * contain valid mappings with identical attributes except for ATTR_AF;
4036 * "mpte"'s valid field will be set to 1.
4038 * If "promoted" and "all_l3e_AF_set" are both true, then "mpte" must contain
4039 * valid mappings with identical attributes including ATTR_AF; "mpte"'s valid
4040 * field will be set to VM_PAGE_BITS_ALL.
4043 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted,
4044 bool all_l3e_AF_set)
4047 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4048 KASSERT(promoted || !all_l3e_AF_set,
4049 ("a zero-filled PTP can't have ATTR_AF set in every PTE"));
4050 mpte->valid = promoted ? (all_l3e_AF_set ? VM_PAGE_BITS_ALL : 1) : 0;
4051 return (vm_radix_insert(&pmap->pm_root, mpte));
4055 * Removes the page table page mapping the specified virtual address from the
4056 * specified pmap's collection of idle page table pages, and returns it.
4057 * Otherwise, returns NULL if there is no page table page corresponding to the
4058 * specified virtual address.
4060 static __inline vm_page_t
4061 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
4064 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4065 return (vm_radix_remove(&pmap->pm_root, pmap_l2_pindex(va)));
4069 * Performs a break-before-make update of a pmap entry. This is needed when
4070 * either promoting or demoting pages to ensure the TLB doesn't get into an
4071 * inconsistent state.
4074 pmap_update_entry(pmap_t pmap, pd_entry_t *pte, pd_entry_t newpte,
4075 vm_offset_t va, vm_size_t size)
4079 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4081 if ((newpte & ATTR_SW_NO_PROMOTE) != 0)
4082 panic("%s: Updating non-promote pte", __func__);
4085 * Ensure we don't get switched out with the page table in an
4086 * inconsistent state. We also need to ensure no interrupts fire
4087 * as they may make use of an address we are about to invalidate.
4089 intr = intr_disable();
4092 * Clear the old mapping's valid bit, but leave the rest of the entry
4093 * unchanged, so that a lockless, concurrent pmap_kextract() can still
4094 * lookup the physical address.
4096 pmap_clear_bits(pte, ATTR_DESCR_VALID);
4099 * When promoting, the L{1,2}_TABLE entry that is being replaced might
4100 * be cached, so we invalidate intermediate entries as well as final
4103 pmap_s1_invalidate_range(pmap, va, va + size, false);
4105 /* Create the new mapping */
4106 pmap_store(pte, newpte);
4112 #if VM_NRESERVLEVEL > 0
4114 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
4115 * replace the many pv entries for the 4KB page mappings by a single pv entry
4116 * for the 2MB page mapping.
4119 pmap_pv_promote_l2(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
4120 struct rwlock **lockp)
4122 struct md_page *pvh;
4124 vm_offset_t va_last;
4127 KASSERT((pa & L2_OFFSET) == 0,
4128 ("pmap_pv_promote_l2: pa is not 2mpage aligned"));
4129 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
4132 * Transfer the first page's pv entry for this mapping to the 2mpage's
4133 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
4134 * a transfer avoids the possibility that get_pv_entry() calls
4135 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
4136 * mappings that is being promoted.
4138 m = PHYS_TO_VM_PAGE(pa);
4139 va = va & ~L2_OFFSET;
4140 pv = pmap_pvh_remove(&m->md, pmap, va);
4141 KASSERT(pv != NULL, ("pmap_pv_promote_l2: pv not found"));
4142 pvh = page_to_pvh(m);
4143 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
4145 /* Free the remaining NPTEPG - 1 pv entries. */
4146 va_last = va + L2_SIZE - PAGE_SIZE;
4150 pmap_pvh_free(&m->md, pmap, va);
4151 } while (va < va_last);
4155 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4156 * single level 2 table entry to a single 2MB page mapping. For promotion
4157 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4158 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4159 * identical characteristics.
4162 pmap_promote_l2(pmap_t pmap, pd_entry_t *l2, vm_offset_t va, vm_page_t mpte,
4163 struct rwlock **lockp)
4165 pt_entry_t all_l3e_AF, *firstl3, *l3, newl2, oldl3, pa;
4167 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4170 * Currently, this function only supports promotion on stage 1 pmaps
4171 * because it tests stage 1 specific fields and performs a break-
4172 * before-make sequence that is incorrect for stage 2 pmaps.
4174 if (pmap->pm_stage != PM_STAGE1 || !pmap_ps_enabled(pmap))
4178 * Examine the first L3E in the specified PTP. Abort if this L3E is
4179 * ineligible for promotion...
4181 firstl3 = (pt_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(pmap_load(l2)));
4182 newl2 = pmap_load(firstl3);
4183 if ((newl2 & ATTR_SW_NO_PROMOTE) != 0)
4185 /* ... is not the first physical page within an L2 block */
4186 if ((PTE_TO_PHYS(newl2) & L2_OFFSET) != 0 ||
4187 ((newl2 & ATTR_DESCR_MASK) != L3_PAGE)) { /* ... or is invalid */
4188 atomic_add_long(&pmap_l2_p_failures, 1);
4189 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
4190 " in pmap %p", va, pmap);
4195 * Both here and in the below "for" loop, to allow for repromotion
4196 * after MADV_FREE, conditionally write protect a clean L3E before
4197 * possibly aborting the promotion due to other L3E attributes. Why?
4198 * Suppose that MADV_FREE is applied to a part of a superpage, the
4199 * address range [S, E). pmap_advise() will demote the superpage
4200 * mapping, destroy the 4KB page mapping at the end of [S, E), and
4201 * set AP_RO and clear AF in the L3Es for the rest of [S, E). Later,
4202 * imagine that the memory in [S, E) is recycled, but the last 4KB
4203 * page in [S, E) is not the last to be rewritten, or simply accessed.
4204 * In other words, there is still a 4KB page in [S, E), call it P,
4205 * that is writeable but AP_RO is set and AF is clear in P's L3E.
4206 * Unless we write protect P before aborting the promotion, if and
4207 * when P is finally rewritten, there won't be a page fault to trigger
4211 if ((newl2 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
4212 (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM)) {
4214 * When the mapping is clean, i.e., ATTR_S1_AP_RO is set,
4215 * ATTR_SW_DBM can be cleared without a TLB invalidation.
4217 if (!atomic_fcmpset_64(firstl3, &newl2, newl2 & ~ATTR_SW_DBM))
4219 newl2 &= ~ATTR_SW_DBM;
4220 CTR2(KTR_PMAP, "pmap_promote_l2: protect for va %#lx"
4221 " in pmap %p", va & ~L2_OFFSET, pmap);
4225 * Examine each of the other L3Es in the specified PTP. Abort if this
4226 * L3E maps an unexpected 4KB physical page or does not have identical
4227 * characteristics to the first L3E. If ATTR_AF is not set in every
4228 * PTE, then request that the PTP be refilled on demotion.
4230 all_l3e_AF = newl2 & ATTR_AF;
4231 pa = (PTE_TO_PHYS(newl2) | (newl2 & ATTR_DESCR_MASK))
4232 + L2_SIZE - PAGE_SIZE;
4233 for (l3 = firstl3 + NL3PG - 1; l3 > firstl3; l3--) {
4234 oldl3 = pmap_load(l3);
4235 if ((PTE_TO_PHYS(oldl3) | (oldl3 & ATTR_DESCR_MASK)) != pa) {
4236 atomic_add_long(&pmap_l2_p_failures, 1);
4237 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
4238 " in pmap %p", va, pmap);
4242 if ((oldl3 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
4243 (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM)) {
4245 * When the mapping is clean, i.e., ATTR_S1_AP_RO is
4246 * set, ATTR_SW_DBM can be cleared without a TLB
4249 if (!atomic_fcmpset_64(l3, &oldl3, oldl3 &
4252 oldl3 &= ~ATTR_SW_DBM;
4254 if ((oldl3 & (ATTR_MASK & ~ATTR_AF)) != (newl2 & (ATTR_MASK &
4256 atomic_add_long(&pmap_l2_p_failures, 1);
4257 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
4258 " in pmap %p", va, pmap);
4261 all_l3e_AF &= oldl3;
4266 * Unless all PTEs have ATTR_AF set, clear it from the superpage
4267 * mapping, so that promotions triggered by speculative mappings,
4268 * such as pmap_enter_quick(), don't automatically mark the
4269 * underlying pages as referenced.
4271 newl2 &= ~ATTR_AF | all_l3e_AF;
4274 * Save the page table page in its current state until the L2
4275 * mapping the superpage is demoted by pmap_demote_l2() or
4276 * destroyed by pmap_remove_l3().
4279 mpte = PHYS_TO_VM_PAGE(PTE_TO_PHYS(pmap_load(l2)));
4280 KASSERT(mpte >= vm_page_array &&
4281 mpte < &vm_page_array[vm_page_array_size],
4282 ("pmap_promote_l2: page table page is out of range"));
4283 KASSERT(mpte->pindex == pmap_l2_pindex(va),
4284 ("pmap_promote_l2: page table page's pindex is wrong"));
4285 if (pmap_insert_pt_page(pmap, mpte, true, all_l3e_AF != 0)) {
4286 atomic_add_long(&pmap_l2_p_failures, 1);
4288 "pmap_promote_l2: failure for va %#lx in pmap %p", va,
4293 if ((newl2 & ATTR_SW_MANAGED) != 0)
4294 pmap_pv_promote_l2(pmap, va, PTE_TO_PHYS(newl2), lockp);
4296 newl2 &= ~ATTR_DESCR_MASK;
4299 pmap_update_entry(pmap, l2, newl2, va & ~L2_OFFSET, L2_SIZE);
4301 atomic_add_long(&pmap_l2_promotions, 1);
4302 CTR2(KTR_PMAP, "pmap_promote_l2: success for va %#lx in pmap %p", va,
4306 #endif /* VM_NRESERVLEVEL > 0 */
4309 pmap_enter_largepage(pmap_t pmap, vm_offset_t va, pt_entry_t newpte, int flags,
4312 pd_entry_t *l0p, *l1p, *l2p, origpte;
4315 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4316 KASSERT(psind > 0 && psind < MAXPAGESIZES,
4317 ("psind %d unexpected", psind));
4318 KASSERT((PTE_TO_PHYS(newpte) & (pagesizes[psind] - 1)) == 0,
4319 ("unaligned phys address %#lx newpte %#lx psind %d",
4320 PTE_TO_PHYS(newpte), newpte, psind));
4324 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
4326 l0p = pmap_l0(pmap, va);
4327 if ((pmap_load(l0p) & ATTR_DESCR_VALID) == 0) {
4328 mp = _pmap_alloc_l3(pmap, pmap_l0_pindex(va), NULL);
4330 if ((flags & PMAP_ENTER_NOSLEEP) != 0)
4331 return (KERN_RESOURCE_SHORTAGE);
4337 l1p = pmap_l0_to_l1(l0p, va);
4338 KASSERT(l1p != NULL, ("va %#lx lost l1 entry", va));
4339 origpte = pmap_load(l1p);
4341 l1p = pmap_l0_to_l1(l0p, va);
4342 KASSERT(l1p != NULL, ("va %#lx lost l1 entry", va));
4343 origpte = pmap_load(l1p);
4344 if ((origpte & ATTR_DESCR_VALID) == 0) {
4345 mp = PHYS_TO_VM_PAGE(
4346 PTE_TO_PHYS(pmap_load(l0p)));
4350 KASSERT((PTE_TO_PHYS(origpte) == PTE_TO_PHYS(newpte) &&
4351 (origpte & ATTR_DESCR_MASK) == L1_BLOCK) ||
4352 (origpte & ATTR_DESCR_VALID) == 0,
4353 ("va %#lx changing 1G phys page l1 %#lx newpte %#lx",
4354 va, origpte, newpte));
4355 pmap_store(l1p, newpte);
4356 } else /* (psind == 1) */ {
4357 l2p = pmap_l2(pmap, va);
4359 mp = _pmap_alloc_l3(pmap, pmap_l1_pindex(va), NULL);
4361 if ((flags & PMAP_ENTER_NOSLEEP) != 0)
4362 return (KERN_RESOURCE_SHORTAGE);
4368 l2p = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
4369 l2p = &l2p[pmap_l2_index(va)];
4370 origpte = pmap_load(l2p);
4372 l1p = pmap_l1(pmap, va);
4373 origpte = pmap_load(l2p);
4374 if ((origpte & ATTR_DESCR_VALID) == 0) {
4375 mp = PHYS_TO_VM_PAGE(
4376 PTE_TO_PHYS(pmap_load(l1p)));
4380 KASSERT((origpte & ATTR_DESCR_VALID) == 0 ||
4381 ((origpte & ATTR_DESCR_MASK) == L2_BLOCK &&
4382 PTE_TO_PHYS(origpte) == PTE_TO_PHYS(newpte)),
4383 ("va %#lx changing 2M phys page l2 %#lx newpte %#lx",
4384 va, origpte, newpte));
4385 pmap_store(l2p, newpte);
4389 if ((origpte & ATTR_DESCR_VALID) == 0)
4390 pmap_resident_count_inc(pmap, pagesizes[psind] / PAGE_SIZE);
4391 if ((newpte & ATTR_SW_WIRED) != 0 && (origpte & ATTR_SW_WIRED) == 0)
4392 pmap->pm_stats.wired_count += pagesizes[psind] / PAGE_SIZE;
4393 else if ((newpte & ATTR_SW_WIRED) == 0 &&
4394 (origpte & ATTR_SW_WIRED) != 0)
4395 pmap->pm_stats.wired_count -= pagesizes[psind] / PAGE_SIZE;
4397 return (KERN_SUCCESS);
4401 * Insert the given physical page (p) at
4402 * the specified virtual address (v) in the
4403 * target physical map with the protection requested.
4405 * If specified, the page will be wired down, meaning
4406 * that the related pte can not be reclaimed.
4408 * NB: This is the only routine which MAY NOT lazy-evaluate
4409 * or lose information. That is, this routine must actually
4410 * insert this page into the given map NOW.
4413 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4414 u_int flags, int8_t psind)
4416 struct rwlock *lock;
4418 pt_entry_t new_l3, orig_l3;
4419 pt_entry_t *l2, *l3;
4426 KASSERT(ADDR_IS_CANONICAL(va),
4427 ("%s: Address not in canonical form: %lx", __func__, va));
4429 va = trunc_page(va);
4430 if ((m->oflags & VPO_UNMANAGED) == 0)
4431 VM_PAGE_OBJECT_BUSY_ASSERT(m);
4432 pa = VM_PAGE_TO_PHYS(m);
4433 new_l3 = (pt_entry_t)(PHYS_TO_PTE(pa) | ATTR_DEFAULT | L3_PAGE);
4434 new_l3 |= pmap_pte_memattr(pmap, m->md.pv_memattr);
4435 new_l3 |= pmap_pte_prot(pmap, prot);
4437 if ((flags & PMAP_ENTER_WIRED) != 0)
4438 new_l3 |= ATTR_SW_WIRED;
4439 if (pmap->pm_stage == PM_STAGE1) {
4440 if (!ADDR_IS_KERNEL(va))
4441 new_l3 |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
4443 new_l3 |= ATTR_S1_UXN;
4444 if (pmap != kernel_pmap)
4445 new_l3 |= ATTR_S1_nG;
4448 * Clear the access flag on executable mappings, this will be
4449 * set later when the page is accessed. The fault handler is
4450 * required to invalidate the I-cache.
4452 * TODO: Switch to the valid flag to allow hardware management
4453 * of the access flag. Much of the pmap code assumes the
4454 * valid flag is set and fails to destroy the old page tables
4455 * correctly if it is clear.
4457 if (prot & VM_PROT_EXECUTE)
4460 if ((m->oflags & VPO_UNMANAGED) == 0) {
4461 new_l3 |= ATTR_SW_MANAGED;
4462 if ((prot & VM_PROT_WRITE) != 0) {
4463 new_l3 |= ATTR_SW_DBM;
4464 if ((flags & VM_PROT_WRITE) == 0) {
4465 if (pmap->pm_stage == PM_STAGE1)
4466 new_l3 |= ATTR_S1_AP(ATTR_S1_AP_RO);
4469 ~ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
4474 CTR2(KTR_PMAP, "pmap_enter: %.16lx -> %.16lx", va, pa);
4478 if ((flags & PMAP_ENTER_LARGEPAGE) != 0) {
4479 KASSERT((m->oflags & VPO_UNMANAGED) != 0,
4480 ("managed largepage va %#lx flags %#x", va, flags));
4483 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
4485 } else /* (psind == 1) */
4487 rv = pmap_enter_largepage(pmap, va, new_l3, flags, psind);
4491 /* Assert the required virtual and physical alignment. */
4492 KASSERT((va & L2_OFFSET) == 0, ("pmap_enter: va unaligned"));
4493 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4494 rv = pmap_enter_l2(pmap, va, (new_l3 & ~L3_PAGE) | L2_BLOCK,
4501 * In the case that a page table page is not
4502 * resident, we are creating it here.
4505 pde = pmap_pde(pmap, va, &lvl);
4506 if (pde != NULL && lvl == 2) {
4507 l3 = pmap_l2_to_l3(pde, va);
4508 if (!ADDR_IS_KERNEL(va) && mpte == NULL) {
4509 mpte = PHYS_TO_VM_PAGE(PTE_TO_PHYS(pmap_load(pde)));
4513 } else if (pde != NULL && lvl == 1) {
4514 l2 = pmap_l1_to_l2(pde, va);
4515 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK &&
4516 (l3 = pmap_demote_l2_locked(pmap, l2, va, &lock)) != NULL) {
4517 l3 = &l3[pmap_l3_index(va)];
4518 if (!ADDR_IS_KERNEL(va)) {
4519 mpte = PHYS_TO_VM_PAGE(
4520 PTE_TO_PHYS(pmap_load(l2)));
4525 /* We need to allocate an L3 table. */
4527 if (!ADDR_IS_KERNEL(va)) {
4528 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4531 * We use _pmap_alloc_l3() instead of pmap_alloc_l3() in order
4532 * to handle the possibility that a superpage mapping for "va"
4533 * was created while we slept.
4535 mpte = _pmap_alloc_l3(pmap, pmap_l2_pindex(va),
4536 nosleep ? NULL : &lock);
4537 if (mpte == NULL && nosleep) {
4538 CTR0(KTR_PMAP, "pmap_enter: mpte == NULL");
4539 rv = KERN_RESOURCE_SHORTAGE;
4544 panic("pmap_enter: missing L3 table for kernel va %#lx", va);
4547 orig_l3 = pmap_load(l3);
4548 opa = PTE_TO_PHYS(orig_l3);
4552 * Is the specified virtual address already mapped?
4554 if (pmap_l3_valid(orig_l3)) {
4556 * Wiring change, just update stats. We don't worry about
4557 * wiring PT pages as they remain resident as long as there
4558 * are valid mappings in them. Hence, if a user page is wired,
4559 * the PT page will be also.
4561 if ((flags & PMAP_ENTER_WIRED) != 0 &&
4562 (orig_l3 & ATTR_SW_WIRED) == 0)
4563 pmap->pm_stats.wired_count++;
4564 else if ((flags & PMAP_ENTER_WIRED) == 0 &&
4565 (orig_l3 & ATTR_SW_WIRED) != 0)
4566 pmap->pm_stats.wired_count--;
4569 * Remove the extra PT page reference.
4573 KASSERT(mpte->ref_count > 0,
4574 ("pmap_enter: missing reference to page table page,"
4579 * Has the physical page changed?
4583 * No, might be a protection or wiring change.
4585 if ((orig_l3 & ATTR_SW_MANAGED) != 0 &&
4586 (new_l3 & ATTR_SW_DBM) != 0)
4587 vm_page_aflag_set(m, PGA_WRITEABLE);
4592 * The physical page has changed. Temporarily invalidate
4595 orig_l3 = pmap_load_clear(l3);
4596 KASSERT(PTE_TO_PHYS(orig_l3) == opa,
4597 ("pmap_enter: unexpected pa update for %#lx", va));
4598 if ((orig_l3 & ATTR_SW_MANAGED) != 0) {
4599 om = PHYS_TO_VM_PAGE(opa);
4602 * The pmap lock is sufficient to synchronize with
4603 * concurrent calls to pmap_page_test_mappings() and
4604 * pmap_ts_referenced().
4606 if (pmap_pte_dirty(pmap, orig_l3))
4608 if ((orig_l3 & ATTR_AF) != 0) {
4609 pmap_invalidate_page(pmap, va, true);
4610 vm_page_aflag_set(om, PGA_REFERENCED);
4612 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, om);
4613 pv = pmap_pvh_remove(&om->md, pmap, va);
4614 if ((m->oflags & VPO_UNMANAGED) != 0)
4615 free_pv_entry(pmap, pv);
4616 if ((om->a.flags & PGA_WRITEABLE) != 0 &&
4617 TAILQ_EMPTY(&om->md.pv_list) &&
4618 ((om->flags & PG_FICTITIOUS) != 0 ||
4619 TAILQ_EMPTY(&page_to_pvh(om)->pv_list)))
4620 vm_page_aflag_clear(om, PGA_WRITEABLE);
4622 KASSERT((orig_l3 & ATTR_AF) != 0,
4623 ("pmap_enter: unmanaged mapping lacks ATTR_AF"));
4624 pmap_invalidate_page(pmap, va, true);
4629 * Increment the counters.
4631 if ((new_l3 & ATTR_SW_WIRED) != 0)
4632 pmap->pm_stats.wired_count++;
4633 pmap_resident_count_inc(pmap, 1);
4636 * Enter on the PV list if part of our managed memory.
4638 if ((m->oflags & VPO_UNMANAGED) == 0) {
4640 pv = get_pv_entry(pmap, &lock);
4643 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
4644 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4646 if ((new_l3 & ATTR_SW_DBM) != 0)
4647 vm_page_aflag_set(m, PGA_WRITEABLE);
4651 if (pmap->pm_stage == PM_STAGE1) {
4653 * Sync icache if exec permission and attribute
4654 * VM_MEMATTR_WRITE_BACK is set. Do it now, before the mapping
4655 * is stored and made valid for hardware table walk. If done
4656 * later, then other can access this page before caches are
4657 * properly synced. Don't do it for kernel memory which is
4658 * mapped with exec permission even if the memory isn't going
4659 * to hold executable code. The only time when icache sync is
4660 * needed is after kernel module is loaded and the relocation
4661 * info is processed. And it's done in elf_cpu_load_file().
4663 if ((prot & VM_PROT_EXECUTE) && pmap != kernel_pmap &&
4664 m->md.pv_memattr == VM_MEMATTR_WRITE_BACK &&
4665 (opa != pa || (orig_l3 & ATTR_S1_XN))) {
4666 PMAP_ASSERT_STAGE1(pmap);
4667 cpu_icache_sync_range(PHYS_TO_DMAP(pa), PAGE_SIZE);
4670 cpu_dcache_wb_range(PHYS_TO_DMAP(pa), PAGE_SIZE);
4674 * Update the L3 entry
4676 if (pmap_l3_valid(orig_l3)) {
4677 KASSERT(opa == pa, ("pmap_enter: invalid update"));
4678 if ((orig_l3 & ~ATTR_AF) != (new_l3 & ~ATTR_AF)) {
4679 /* same PA, different attributes */
4680 orig_l3 = pmap_load_store(l3, new_l3);
4681 pmap_invalidate_page(pmap, va, true);
4682 if ((orig_l3 & ATTR_SW_MANAGED) != 0 &&
4683 pmap_pte_dirty(pmap, orig_l3))
4688 * This can happens if multiple threads simultaneously
4689 * access not yet mapped page. This bad for performance
4690 * since this can cause full demotion-NOP-promotion
4692 * Another possible reasons are:
4693 * - VM and pmap memory layout are diverged
4694 * - tlb flush is missing somewhere and CPU doesn't see
4697 CTR4(KTR_PMAP, "%s: already mapped page - "
4698 "pmap %p va 0x%#lx pte 0x%lx",
4699 __func__, pmap, va, new_l3);
4703 pmap_store(l3, new_l3);
4707 #if VM_NRESERVLEVEL > 0
4709 * If both the page table page and the reservation are fully
4710 * populated, then attempt promotion.
4712 if ((mpte == NULL || mpte->ref_count == NL3PG) &&
4713 (m->flags & PG_FICTITIOUS) == 0 &&
4714 vm_reserv_level_iffullpop(m) == 0)
4715 (void)pmap_promote_l2(pmap, pde, va, mpte, &lock);
4727 * Tries to create a read- and/or execute-only 2MB page mapping. Returns
4728 * KERN_SUCCESS if the mapping was created. Otherwise, returns an error
4729 * value. See pmap_enter_l2() for the possible error values when "no sleep",
4730 * "no replace", and "no reclaim" are specified.
4733 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4734 struct rwlock **lockp)
4738 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4739 PMAP_ASSERT_STAGE1(pmap);
4740 KASSERT(ADDR_IS_CANONICAL(va),
4741 ("%s: Address not in canonical form: %lx", __func__, va));
4743 new_l2 = (pd_entry_t)(PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) | ATTR_DEFAULT |
4744 ATTR_S1_IDX(m->md.pv_memattr) | ATTR_S1_AP(ATTR_S1_AP_RO) |
4746 if ((m->oflags & VPO_UNMANAGED) == 0) {
4747 new_l2 |= ATTR_SW_MANAGED;
4750 if ((prot & VM_PROT_EXECUTE) == 0 ||
4751 m->md.pv_memattr == VM_MEMATTR_DEVICE)
4752 new_l2 |= ATTR_S1_XN;
4753 if (!ADDR_IS_KERNEL(va))
4754 new_l2 |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
4756 new_l2 |= ATTR_S1_UXN;
4757 if (pmap != kernel_pmap)
4758 new_l2 |= ATTR_S1_nG;
4759 return (pmap_enter_l2(pmap, va, new_l2, PMAP_ENTER_NOSLEEP |
4760 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, m, lockp));
4764 * Returns true if every page table entry in the specified page table is
4768 pmap_every_pte_zero(vm_paddr_t pa)
4770 pt_entry_t *pt_end, *pte;
4772 KASSERT((pa & PAGE_MASK) == 0, ("pa is misaligned"));
4773 pte = (pt_entry_t *)PHYS_TO_DMAP(pa);
4774 for (pt_end = pte + Ln_ENTRIES; pte < pt_end; pte++) {
4782 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
4783 * the mapping was created, and one of KERN_FAILURE, KERN_NO_SPACE, or
4784 * KERN_RESOURCE_SHORTAGE otherwise. Returns KERN_FAILURE if
4785 * PMAP_ENTER_NOREPLACE was specified and a 4KB page mapping already exists
4786 * within the 2MB virtual address range starting at the specified virtual
4787 * address. Returns KERN_NO_SPACE if PMAP_ENTER_NOREPLACE was specified and a
4788 * 2MB page mapping already exists at the specified virtual address. Returns
4789 * KERN_RESOURCE_SHORTAGE if either (1) PMAP_ENTER_NOSLEEP was specified and a
4790 * page table page allocation failed or (2) PMAP_ENTER_NORECLAIM was specified
4791 * and a PV entry allocation failed.
4794 pmap_enter_l2(pmap_t pmap, vm_offset_t va, pd_entry_t new_l2, u_int flags,
4795 vm_page_t m, struct rwlock **lockp)
4797 struct spglist free;
4798 pd_entry_t *l2, old_l2;
4801 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4802 KASSERT(ADDR_IS_CANONICAL(va),
4803 ("%s: Address not in canonical form: %lx", __func__, va));
4805 if ((l2 = pmap_alloc_l2(pmap, va, &l2pg, (flags &
4806 PMAP_ENTER_NOSLEEP) != 0 ? NULL : lockp)) == NULL) {
4807 CTR2(KTR_PMAP, "pmap_enter_l2: failure for va %#lx in pmap %p",
4809 return (KERN_RESOURCE_SHORTAGE);
4813 * If there are existing mappings, either abort or remove them.
4815 if ((old_l2 = pmap_load(l2)) != 0) {
4816 KASSERT(l2pg == NULL || l2pg->ref_count > 1,
4817 ("pmap_enter_l2: l2pg's ref count is too low"));
4818 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
4819 if ((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK) {
4823 "pmap_enter_l2: no space for va %#lx"
4824 " in pmap %p", va, pmap);
4825 return (KERN_NO_SPACE);
4826 } else if (!ADDR_IS_KERNEL(va) ||
4827 !pmap_every_pte_zero(PTE_TO_PHYS(old_l2))) {
4831 "pmap_enter_l2: failure for va %#lx"
4832 " in pmap %p", va, pmap);
4833 return (KERN_FAILURE);
4837 if ((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK)
4838 (void)pmap_remove_l2(pmap, l2, va,
4839 pmap_load(pmap_l1(pmap, va)), &free, lockp);
4841 pmap_remove_l3_range(pmap, old_l2, va, va + L2_SIZE,
4843 if (!ADDR_IS_KERNEL(va)) {
4844 vm_page_free_pages_toq(&free, true);
4845 KASSERT(pmap_load(l2) == 0,
4846 ("pmap_enter_l2: non-zero L2 entry %p", l2));
4848 KASSERT(SLIST_EMPTY(&free),
4849 ("pmap_enter_l2: freed kernel page table page"));
4852 * Both pmap_remove_l2() and pmap_remove_l3_range()
4853 * will leave the kernel page table page zero filled.
4854 * Nonetheless, the TLB could have an intermediate
4855 * entry for the kernel page table page, so request
4856 * an invalidation at all levels after clearing
4857 * the L2_TABLE entry.
4859 mt = PHYS_TO_VM_PAGE(PTE_TO_PHYS(pmap_load(l2)));
4860 if (pmap_insert_pt_page(pmap, mt, false, false))
4861 panic("pmap_enter_l2: trie insert failed");
4863 pmap_s1_invalidate_page(pmap, va, false);
4867 if ((new_l2 & ATTR_SW_MANAGED) != 0) {
4869 * Abort this mapping if its PV entry could not be created.
4871 if (!pmap_pv_insert_l2(pmap, va, new_l2, flags, lockp)) {
4873 pmap_abort_ptp(pmap, va, l2pg);
4875 "pmap_enter_l2: failure for va %#lx in pmap %p",
4877 return (KERN_RESOURCE_SHORTAGE);
4879 if ((new_l2 & ATTR_SW_DBM) != 0)
4880 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
4881 vm_page_aflag_set(mt, PGA_WRITEABLE);
4885 * Increment counters.
4887 if ((new_l2 & ATTR_SW_WIRED) != 0)
4888 pmap->pm_stats.wired_count += L2_SIZE / PAGE_SIZE;
4889 pmap->pm_stats.resident_count += L2_SIZE / PAGE_SIZE;
4892 * Conditionally sync the icache. See pmap_enter() for details.
4894 if ((new_l2 & ATTR_S1_XN) == 0 && (PTE_TO_PHYS(new_l2) !=
4895 PTE_TO_PHYS(old_l2) || (old_l2 & ATTR_S1_XN) != 0) &&
4896 pmap != kernel_pmap && m->md.pv_memattr == VM_MEMATTR_WRITE_BACK) {
4897 cpu_icache_sync_range(PHYS_TO_DMAP(PTE_TO_PHYS(new_l2)),
4902 * Map the superpage.
4904 pmap_store(l2, new_l2);
4907 atomic_add_long(&pmap_l2_mappings, 1);
4908 CTR2(KTR_PMAP, "pmap_enter_l2: success for va %#lx in pmap %p",
4911 return (KERN_SUCCESS);
4915 * Maps a sequence of resident pages belonging to the same object.
4916 * The sequence begins with the given page m_start. This page is
4917 * mapped at the given virtual address start. Each subsequent page is
4918 * mapped at a virtual address that is offset from start by the same
4919 * amount as the page is offset from m_start within the object. The
4920 * last page in the sequence is the page with the largest offset from
4921 * m_start that can be mapped at a virtual address less than the given
4922 * virtual address end. Not every virtual page between start and end
4923 * is mapped; only those for which a resident page exists with the
4924 * corresponding offset from m_start are mapped.
4927 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
4928 vm_page_t m_start, vm_prot_t prot)
4930 struct rwlock *lock;
4933 vm_pindex_t diff, psize;
4936 VM_OBJECT_ASSERT_LOCKED(m_start->object);
4938 psize = atop(end - start);
4943 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
4944 va = start + ptoa(diff);
4945 if ((va & L2_OFFSET) == 0 && va + L2_SIZE <= end &&
4946 m->psind == 1 && pmap_ps_enabled(pmap) &&
4947 ((rv = pmap_enter_2mpage(pmap, va, m, prot, &lock)) ==
4948 KERN_SUCCESS || rv == KERN_NO_SPACE))
4949 m = &m[L2_SIZE / PAGE_SIZE - 1];
4951 mpte = pmap_enter_quick_locked(pmap, va, m, prot, mpte,
4953 m = TAILQ_NEXT(m, listq);
4961 * this code makes some *MAJOR* assumptions:
4962 * 1. Current pmap & pmap exists.
4965 * 4. No page table pages.
4966 * but is *MUCH* faster than pmap_enter...
4970 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
4972 struct rwlock *lock;
4976 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
4983 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
4984 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
4987 pt_entry_t *l1, *l2, *l3, l3_val;
4991 KASSERT(!VA_IS_CLEANMAP(va) ||
4992 (m->oflags & VPO_UNMANAGED) != 0,
4993 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
4994 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4995 PMAP_ASSERT_STAGE1(pmap);
4996 KASSERT(ADDR_IS_CANONICAL(va),
4997 ("%s: Address not in canonical form: %lx", __func__, va));
5000 CTR2(KTR_PMAP, "pmap_enter_quick_locked: %p %lx", pmap, va);
5002 * In the case that a page table page is not
5003 * resident, we are creating it here.
5005 if (!ADDR_IS_KERNEL(va)) {
5006 vm_pindex_t l2pindex;
5009 * Calculate pagetable page index
5011 l2pindex = pmap_l2_pindex(va);
5012 if (mpte && (mpte->pindex == l2pindex)) {
5016 * If the page table page is mapped, we just increment
5017 * the hold count, and activate it. Otherwise, we
5018 * attempt to allocate a page table page, passing NULL
5019 * instead of the PV list lock pointer because we don't
5020 * intend to sleep. If this attempt fails, we don't
5021 * retry. Instead, we give up.
5023 l1 = pmap_l1(pmap, va);
5024 if (l1 != NULL && pmap_load(l1) != 0) {
5025 if ((pmap_load(l1) & ATTR_DESCR_MASK) ==
5028 l2 = pmap_l1_to_l2(l1, va);
5029 if (pmap_load(l2) != 0) {
5030 if ((pmap_load(l2) & ATTR_DESCR_MASK) ==
5033 mpte = PHYS_TO_VM_PAGE(
5034 PTE_TO_PHYS(pmap_load(l2)));
5037 mpte = _pmap_alloc_l3(pmap, l2pindex,
5043 mpte = _pmap_alloc_l3(pmap, l2pindex, NULL);
5048 l3 = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
5049 l3 = &l3[pmap_l3_index(va)];
5052 pde = pmap_pde(kernel_pmap, va, &lvl);
5053 KASSERT(pde != NULL,
5054 ("pmap_enter_quick_locked: Invalid page entry, va: 0x%lx",
5057 ("pmap_enter_quick_locked: Invalid level %d", lvl));
5058 l3 = pmap_l2_to_l3(pde, va);
5062 * Abort if a mapping already exists.
5064 if (pmap_load(l3) != 0) {
5071 * Enter on the PV list if part of our managed memory.
5073 if ((m->oflags & VPO_UNMANAGED) == 0 &&
5074 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
5076 pmap_abort_ptp(pmap, va, mpte);
5081 * Increment counters
5083 pmap_resident_count_inc(pmap, 1);
5085 pa = VM_PAGE_TO_PHYS(m);
5086 l3_val = PHYS_TO_PTE(pa) | ATTR_DEFAULT | ATTR_S1_IDX(m->md.pv_memattr) |
5087 ATTR_S1_AP(ATTR_S1_AP_RO) | L3_PAGE;
5088 if ((prot & VM_PROT_EXECUTE) == 0 ||
5089 m->md.pv_memattr == VM_MEMATTR_DEVICE)
5090 l3_val |= ATTR_S1_XN;
5091 if (!ADDR_IS_KERNEL(va))
5092 l3_val |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
5094 l3_val |= ATTR_S1_UXN;
5095 if (pmap != kernel_pmap)
5096 l3_val |= ATTR_S1_nG;
5099 * Now validate mapping with RO protection
5101 if ((m->oflags & VPO_UNMANAGED) == 0) {
5102 l3_val |= ATTR_SW_MANAGED;
5106 /* Sync icache before the mapping is stored to PTE */
5107 if ((prot & VM_PROT_EXECUTE) && pmap != kernel_pmap &&
5108 m->md.pv_memattr == VM_MEMATTR_WRITE_BACK)
5109 cpu_icache_sync_range(PHYS_TO_DMAP(pa), PAGE_SIZE);
5111 pmap_store(l3, l3_val);
5114 #if VM_NRESERVLEVEL > 0
5116 * If both the PTP and the reservation are fully populated, then
5117 * attempt promotion.
5119 if ((mpte == NULL || mpte->ref_count == NL3PG) &&
5120 (m->flags & PG_FICTITIOUS) == 0 &&
5121 vm_reserv_level_iffullpop(m) == 0) {
5123 l2 = pmap_pde(pmap, va, &lvl);
5126 * If promotion succeeds, then the next call to this function
5127 * should not be given the unmapped PTP as a hint.
5129 if (pmap_promote_l2(pmap, l2, va, mpte, lockp))
5138 * This code maps large physical mmap regions into the
5139 * processor address space. Note that some shortcuts
5140 * are taken, but the code works.
5143 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
5144 vm_pindex_t pindex, vm_size_t size)
5147 VM_OBJECT_ASSERT_WLOCKED(object);
5148 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
5149 ("pmap_object_init_pt: non-device object"));
5153 * Clear the wired attribute from the mappings for the specified range of
5154 * addresses in the given pmap. Every valid mapping within that range
5155 * must have the wired attribute set. In contrast, invalid mappings
5156 * cannot have the wired attribute set, so they are ignored.
5158 * The wired attribute of the page table entry is not a hardware feature,
5159 * so there is no need to invalidate any TLB entries.
5162 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5164 vm_offset_t va_next;
5165 pd_entry_t *l0, *l1, *l2;
5169 for (; sva < eva; sva = va_next) {
5170 l0 = pmap_l0(pmap, sva);
5171 if (pmap_load(l0) == 0) {
5172 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
5178 l1 = pmap_l0_to_l1(l0, sva);
5179 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
5182 if (pmap_load(l1) == 0)
5185 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
5186 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
5187 KASSERT(va_next <= eva,
5188 ("partial update of non-transparent 1G page "
5189 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
5190 pmap_load(l1), sva, eva, va_next));
5191 MPASS(pmap != kernel_pmap);
5192 MPASS((pmap_load(l1) & (ATTR_SW_MANAGED |
5193 ATTR_SW_WIRED)) == ATTR_SW_WIRED);
5194 pmap_clear_bits(l1, ATTR_SW_WIRED);
5195 pmap->pm_stats.wired_count -= L1_SIZE / PAGE_SIZE;
5199 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
5203 l2 = pmap_l1_to_l2(l1, sva);
5204 if (pmap_load(l2) == 0)
5207 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK) {
5208 if ((pmap_load(l2) & ATTR_SW_WIRED) == 0)
5209 panic("pmap_unwire: l2 %#jx is missing "
5210 "ATTR_SW_WIRED", (uintmax_t)pmap_load(l2));
5213 * Are we unwiring the entire large page? If not,
5214 * demote the mapping and fall through.
5216 if (sva + L2_SIZE == va_next && eva >= va_next) {
5217 pmap_clear_bits(l2, ATTR_SW_WIRED);
5218 pmap->pm_stats.wired_count -= L2_SIZE /
5221 } else if (pmap_demote_l2(pmap, l2, sva) == NULL)
5222 panic("pmap_unwire: demotion failed");
5224 KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
5225 ("pmap_unwire: Invalid l2 entry after demotion"));
5229 for (l3 = pmap_l2_to_l3(l2, sva); sva != va_next; l3++,
5231 if (pmap_load(l3) == 0)
5233 if ((pmap_load(l3) & ATTR_SW_WIRED) == 0)
5234 panic("pmap_unwire: l3 %#jx is missing "
5235 "ATTR_SW_WIRED", (uintmax_t)pmap_load(l3));
5238 * ATTR_SW_WIRED must be cleared atomically. Although
5239 * the pmap lock synchronizes access to ATTR_SW_WIRED,
5240 * the System MMU may write to the entry concurrently.
5242 pmap_clear_bits(l3, ATTR_SW_WIRED);
5243 pmap->pm_stats.wired_count--;
5250 * Copy the range specified by src_addr/len
5251 * from the source map to the range dst_addr/len
5252 * in the destination map.
5254 * This routine is only advisory and need not do anything.
5256 * Because the executable mappings created by this routine are copied,
5257 * it should not have to flush the instruction cache.
5260 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5261 vm_offset_t src_addr)
5263 struct rwlock *lock;
5264 pd_entry_t *l0, *l1, *l2, srcptepaddr;
5265 pt_entry_t *dst_pte, mask, nbits, ptetemp, *src_pte;
5266 vm_offset_t addr, end_addr, va_next;
5267 vm_page_t dst_m, dstmpte, srcmpte;
5269 PMAP_ASSERT_STAGE1(dst_pmap);
5270 PMAP_ASSERT_STAGE1(src_pmap);
5272 if (dst_addr != src_addr)
5274 end_addr = src_addr + len;
5276 if (dst_pmap < src_pmap) {
5277 PMAP_LOCK(dst_pmap);
5278 PMAP_LOCK(src_pmap);
5280 PMAP_LOCK(src_pmap);
5281 PMAP_LOCK(dst_pmap);
5283 for (addr = src_addr; addr < end_addr; addr = va_next) {
5284 l0 = pmap_l0(src_pmap, addr);
5285 if (pmap_load(l0) == 0) {
5286 va_next = (addr + L0_SIZE) & ~L0_OFFSET;
5292 va_next = (addr + L1_SIZE) & ~L1_OFFSET;
5295 l1 = pmap_l0_to_l1(l0, addr);
5296 if (pmap_load(l1) == 0)
5298 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
5299 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
5300 KASSERT(va_next <= end_addr,
5301 ("partial update of non-transparent 1G page "
5302 "l1 %#lx addr %#lx end_addr %#lx va_next %#lx",
5303 pmap_load(l1), addr, end_addr, va_next));
5304 srcptepaddr = pmap_load(l1);
5305 l1 = pmap_l1(dst_pmap, addr);
5307 if (_pmap_alloc_l3(dst_pmap,
5308 pmap_l0_pindex(addr), NULL) == NULL)
5310 l1 = pmap_l1(dst_pmap, addr);
5312 l0 = pmap_l0(dst_pmap, addr);
5313 dst_m = PHYS_TO_VM_PAGE(
5314 PTE_TO_PHYS(pmap_load(l0)));
5317 KASSERT(pmap_load(l1) == 0,
5318 ("1G mapping present in dst pmap "
5319 "l1 %#lx addr %#lx end_addr %#lx va_next %#lx",
5320 pmap_load(l1), addr, end_addr, va_next));
5321 pmap_store(l1, srcptepaddr & ~ATTR_SW_WIRED);
5322 pmap_resident_count_inc(dst_pmap, L1_SIZE / PAGE_SIZE);
5326 va_next = (addr + L2_SIZE) & ~L2_OFFSET;
5329 l2 = pmap_l1_to_l2(l1, addr);
5330 srcptepaddr = pmap_load(l2);
5331 if (srcptepaddr == 0)
5333 if ((srcptepaddr & ATTR_DESCR_MASK) == L2_BLOCK) {
5335 * We can only virtual copy whole superpages.
5337 if ((addr & L2_OFFSET) != 0 ||
5338 addr + L2_SIZE > end_addr)
5340 l2 = pmap_alloc_l2(dst_pmap, addr, &dst_m, NULL);
5343 if (pmap_load(l2) == 0 &&
5344 ((srcptepaddr & ATTR_SW_MANAGED) == 0 ||
5345 pmap_pv_insert_l2(dst_pmap, addr, srcptepaddr,
5346 PMAP_ENTER_NORECLAIM, &lock))) {
5348 * We leave the dirty bit unchanged because
5349 * managed read/write superpage mappings are
5350 * required to be dirty. However, managed
5351 * superpage mappings are not required to
5352 * have their accessed bit set, so we clear
5353 * it because we don't know if this mapping
5356 srcptepaddr &= ~ATTR_SW_WIRED;
5357 if ((srcptepaddr & ATTR_SW_MANAGED) != 0)
5358 srcptepaddr &= ~ATTR_AF;
5359 pmap_store(l2, srcptepaddr);
5360 pmap_resident_count_inc(dst_pmap, L2_SIZE /
5362 atomic_add_long(&pmap_l2_mappings, 1);
5364 pmap_abort_ptp(dst_pmap, addr, dst_m);
5367 KASSERT((srcptepaddr & ATTR_DESCR_MASK) == L2_TABLE,
5368 ("pmap_copy: invalid L2 entry"));
5369 srcmpte = PHYS_TO_VM_PAGE(PTE_TO_PHYS(srcptepaddr));
5370 KASSERT(srcmpte->ref_count > 0,
5371 ("pmap_copy: source page table page is unused"));
5372 if (va_next > end_addr)
5374 src_pte = (pt_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(srcptepaddr));
5375 src_pte = &src_pte[pmap_l3_index(addr)];
5377 for (; addr < va_next; addr += PAGE_SIZE, src_pte++) {
5378 ptetemp = pmap_load(src_pte);
5381 * We only virtual copy managed pages.
5383 if ((ptetemp & ATTR_SW_MANAGED) == 0)
5386 if (dstmpte != NULL) {
5387 KASSERT(dstmpte->pindex == pmap_l2_pindex(addr),
5388 ("dstmpte pindex/addr mismatch"));
5389 dstmpte->ref_count++;
5390 } else if ((dstmpte = pmap_alloc_l3(dst_pmap, addr,
5393 dst_pte = (pt_entry_t *)
5394 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5395 dst_pte = &dst_pte[pmap_l3_index(addr)];
5396 if (pmap_load(dst_pte) == 0 &&
5397 pmap_try_insert_pv_entry(dst_pmap, addr,
5398 PHYS_TO_VM_PAGE(PTE_TO_PHYS(ptetemp)), &lock)) {
5400 * Clear the wired, modified, and accessed
5401 * (referenced) bits during the copy.
5403 mask = ATTR_AF | ATTR_SW_WIRED;
5405 if ((ptetemp & ATTR_SW_DBM) != 0)
5406 nbits |= ATTR_S1_AP_RW_BIT;
5407 pmap_store(dst_pte, (ptetemp & ~mask) | nbits);
5408 pmap_resident_count_inc(dst_pmap, 1);
5410 pmap_abort_ptp(dst_pmap, addr, dstmpte);
5413 /* Have we copied all of the valid mappings? */
5414 if (dstmpte->ref_count >= srcmpte->ref_count)
5420 * XXX This barrier may not be needed because the destination pmap is
5427 PMAP_UNLOCK(src_pmap);
5428 PMAP_UNLOCK(dst_pmap);
5432 * pmap_zero_page zeros the specified hardware page by mapping
5433 * the page into KVM and using bzero to clear its contents.
5436 pmap_zero_page(vm_page_t m)
5438 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5440 pagezero((void *)va);
5444 * pmap_zero_page_area zeros the specified hardware page by mapping
5445 * the page into KVM and using bzero to clear its contents.
5447 * off and size may not cover an area beyond a single hardware page.
5450 pmap_zero_page_area(vm_page_t m, int off, int size)
5452 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5454 if (off == 0 && size == PAGE_SIZE)
5455 pagezero((void *)va);
5457 bzero((char *)va + off, size);
5461 * pmap_copy_page copies the specified (machine independent)
5462 * page by mapping the page into virtual memory and using
5463 * bcopy to copy the page, one machine dependent page at a
5467 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5469 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5470 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5472 pagecopy((void *)src, (void *)dst);
5475 int unmapped_buf_allowed = 1;
5478 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5479 vm_offset_t b_offset, int xfersize)
5483 vm_paddr_t p_a, p_b;
5484 vm_offset_t a_pg_offset, b_pg_offset;
5487 while (xfersize > 0) {
5488 a_pg_offset = a_offset & PAGE_MASK;
5489 m_a = ma[a_offset >> PAGE_SHIFT];
5490 p_a = m_a->phys_addr;
5491 b_pg_offset = b_offset & PAGE_MASK;
5492 m_b = mb[b_offset >> PAGE_SHIFT];
5493 p_b = m_b->phys_addr;
5494 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5495 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5496 if (__predict_false(!PHYS_IN_DMAP(p_a))) {
5497 panic("!DMAP a %lx", p_a);
5499 a_cp = (char *)PHYS_TO_DMAP(p_a) + a_pg_offset;
5501 if (__predict_false(!PHYS_IN_DMAP(p_b))) {
5502 panic("!DMAP b %lx", p_b);
5504 b_cp = (char *)PHYS_TO_DMAP(p_b) + b_pg_offset;
5506 bcopy(a_cp, b_cp, cnt);
5514 pmap_quick_enter_page(vm_page_t m)
5517 return (PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)));
5521 pmap_quick_remove_page(vm_offset_t addr)
5526 * Returns true if the pmap's pv is one of the first
5527 * 16 pvs linked to from this page. This count may
5528 * be changed upwards or downwards in the future; it
5529 * is only necessary that true be returned for a small
5530 * subset of pmaps for proper page aging.
5533 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5535 struct md_page *pvh;
5536 struct rwlock *lock;
5541 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5542 ("pmap_page_exists_quick: page %p is not managed", m));
5544 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5546 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5547 if (PV_PMAP(pv) == pmap) {
5555 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5556 pvh = page_to_pvh(m);
5557 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5558 if (PV_PMAP(pv) == pmap) {
5572 * pmap_page_wired_mappings:
5574 * Return the number of managed mappings to the given physical page
5578 pmap_page_wired_mappings(vm_page_t m)
5580 struct rwlock *lock;
5581 struct md_page *pvh;
5585 int count, md_gen, pvh_gen;
5587 if ((m->oflags & VPO_UNMANAGED) != 0)
5589 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5593 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5595 if (!PMAP_TRYLOCK(pmap)) {
5596 md_gen = m->md.pv_gen;
5600 if (md_gen != m->md.pv_gen) {
5605 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
5606 if ((pmap_load(pte) & ATTR_SW_WIRED) != 0)
5610 if ((m->flags & PG_FICTITIOUS) == 0) {
5611 pvh = page_to_pvh(m);
5612 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5614 if (!PMAP_TRYLOCK(pmap)) {
5615 md_gen = m->md.pv_gen;
5616 pvh_gen = pvh->pv_gen;
5620 if (md_gen != m->md.pv_gen ||
5621 pvh_gen != pvh->pv_gen) {
5626 pte = pmap_pte_exists(pmap, pv->pv_va, 2, __func__);
5627 if ((pmap_load(pte) & ATTR_SW_WIRED) != 0)
5637 * Returns true if the given page is mapped individually or as part of
5638 * a 2mpage. Otherwise, returns false.
5641 pmap_page_is_mapped(vm_page_t m)
5643 struct rwlock *lock;
5646 if ((m->oflags & VPO_UNMANAGED) != 0)
5648 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5650 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5651 ((m->flags & PG_FICTITIOUS) == 0 &&
5652 !TAILQ_EMPTY(&page_to_pvh(m)->pv_list));
5658 * Destroy all managed, non-wired mappings in the given user-space
5659 * pmap. This pmap cannot be active on any processor besides the
5662 * This function cannot be applied to the kernel pmap. Moreover, it
5663 * is not intended for general use. It is only to be used during
5664 * process termination. Consequently, it can be implemented in ways
5665 * that make it faster than pmap_remove(). First, it can more quickly
5666 * destroy mappings by iterating over the pmap's collection of PV
5667 * entries, rather than searching the page table. Second, it doesn't
5668 * have to test and clear the page table entries atomically, because
5669 * no processor is currently accessing the user address space. In
5670 * particular, a page table entry's dirty bit won't change state once
5671 * this function starts.
5674 pmap_remove_pages(pmap_t pmap)
5677 pt_entry_t *pte, tpte;
5678 struct spglist free;
5679 struct pv_chunklist free_chunks[PMAP_MEMDOM];
5680 vm_page_t m, ml3, mt;
5682 struct md_page *pvh;
5683 struct pv_chunk *pc, *npc;
5684 struct rwlock *lock;
5686 uint64_t inuse, bitmask;
5687 int allfree, field, i, idx, lvl;
5693 for (i = 0; i < PMAP_MEMDOM; i++)
5694 TAILQ_INIT(&free_chunks[i]);
5697 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5700 for (field = 0; field < _NPCM; field++) {
5701 inuse = ~pc->pc_map[field] & pc_freemask[field];
5702 while (inuse != 0) {
5703 bit = ffsl(inuse) - 1;
5704 bitmask = 1UL << bit;
5705 idx = field * 64 + bit;
5706 pv = &pc->pc_pventry[idx];
5709 pde = pmap_pde(pmap, pv->pv_va, &lvl);
5710 KASSERT(pde != NULL,
5711 ("Attempting to remove an unmapped page"));
5715 pte = pmap_l1_to_l2(pde, pv->pv_va);
5716 tpte = pmap_load(pte);
5717 KASSERT((tpte & ATTR_DESCR_MASK) ==
5719 ("Attempting to remove an invalid "
5720 "block: %lx", tpte));
5723 pte = pmap_l2_to_l3(pde, pv->pv_va);
5724 tpte = pmap_load(pte);
5725 KASSERT((tpte & ATTR_DESCR_MASK) ==
5727 ("Attempting to remove an invalid "
5728 "page: %lx", tpte));
5732 "Invalid page directory level: %d",
5737 * We cannot remove wired pages from a process' mapping at this time
5739 if (tpte & ATTR_SW_WIRED) {
5745 pc->pc_map[field] |= bitmask;
5748 * Because this pmap is not active on other
5749 * processors, the dirty bit cannot have
5750 * changed state since we last loaded pte.
5754 pa = PTE_TO_PHYS(tpte);
5756 m = PHYS_TO_VM_PAGE(pa);
5757 KASSERT(m->phys_addr == pa,
5758 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5759 m, (uintmax_t)m->phys_addr,
5762 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5763 m < &vm_page_array[vm_page_array_size],
5764 ("pmap_remove_pages: bad pte %#jx",
5768 * Update the vm_page_t clean/reference bits.
5770 if (pmap_pte_dirty(pmap, tpte)) {
5773 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
5782 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5786 pmap_resident_count_dec(pmap,
5787 L2_SIZE / PAGE_SIZE);
5788 pvh = page_to_pvh(m);
5789 TAILQ_REMOVE(&pvh->pv_list, pv,pv_next);
5791 if (TAILQ_EMPTY(&pvh->pv_list)) {
5792 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
5793 if ((mt->a.flags & PGA_WRITEABLE) != 0 &&
5794 TAILQ_EMPTY(&mt->md.pv_list))
5795 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5797 ml3 = pmap_remove_pt_page(pmap,
5800 KASSERT(vm_page_any_valid(ml3),
5801 ("pmap_remove_pages: l3 page not promoted"));
5802 pmap_resident_count_dec(pmap,1);
5803 KASSERT(ml3->ref_count == NL3PG,
5804 ("pmap_remove_pages: l3 page ref count error"));
5806 pmap_add_delayed_free_list(ml3,
5811 pmap_resident_count_dec(pmap, 1);
5812 TAILQ_REMOVE(&m->md.pv_list, pv,
5815 if ((m->a.flags & PGA_WRITEABLE) != 0 &&
5816 TAILQ_EMPTY(&m->md.pv_list) &&
5817 (m->flags & PG_FICTITIOUS) == 0) {
5818 pvh = page_to_pvh(m);
5819 if (TAILQ_EMPTY(&pvh->pv_list))
5820 vm_page_aflag_clear(m,
5825 pmap_unuse_pt(pmap, pv->pv_va, pmap_load(pde),
5830 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5831 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5832 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5834 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5835 TAILQ_INSERT_TAIL(&free_chunks[pc_to_domain(pc)], pc,
5841 pmap_invalidate_all(pmap);
5842 free_pv_chunk_batch(free_chunks);
5844 vm_page_free_pages_toq(&free, true);
5848 * This is used to check if a page has been accessed or modified.
5851 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
5853 struct rwlock *lock;
5855 struct md_page *pvh;
5856 pt_entry_t *pte, mask, value;
5858 int md_gen, pvh_gen;
5862 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5865 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5867 PMAP_ASSERT_STAGE1(pmap);
5868 if (!PMAP_TRYLOCK(pmap)) {
5869 md_gen = m->md.pv_gen;
5873 if (md_gen != m->md.pv_gen) {
5878 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
5882 mask |= ATTR_S1_AP_RW_BIT;
5883 value |= ATTR_S1_AP(ATTR_S1_AP_RW);
5886 mask |= ATTR_AF | ATTR_DESCR_MASK;
5887 value |= ATTR_AF | L3_PAGE;
5889 rv = (pmap_load(pte) & mask) == value;
5894 if ((m->flags & PG_FICTITIOUS) == 0) {
5895 pvh = page_to_pvh(m);
5896 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5898 PMAP_ASSERT_STAGE1(pmap);
5899 if (!PMAP_TRYLOCK(pmap)) {
5900 md_gen = m->md.pv_gen;
5901 pvh_gen = pvh->pv_gen;
5905 if (md_gen != m->md.pv_gen ||
5906 pvh_gen != pvh->pv_gen) {
5911 pte = pmap_pte_exists(pmap, pv->pv_va, 2, __func__);
5915 mask |= ATTR_S1_AP_RW_BIT;
5916 value |= ATTR_S1_AP(ATTR_S1_AP_RW);
5919 mask |= ATTR_AF | ATTR_DESCR_MASK;
5920 value |= ATTR_AF | L2_BLOCK;
5922 rv = (pmap_load(pte) & mask) == value;
5936 * Return whether or not the specified physical page was modified
5937 * in any physical maps.
5940 pmap_is_modified(vm_page_t m)
5943 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5944 ("pmap_is_modified: page %p is not managed", m));
5947 * If the page is not busied then this check is racy.
5949 if (!pmap_page_is_write_mapped(m))
5951 return (pmap_page_test_mappings(m, FALSE, TRUE));
5955 * pmap_is_prefaultable:
5957 * Return whether or not the specified virtual address is eligible
5961 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
5969 * Return TRUE if and only if the L3 entry for the specified virtual
5970 * address is allocated but invalid.
5974 pde = pmap_pde(pmap, addr, &lvl);
5975 if (pde != NULL && lvl == 2) {
5976 pte = pmap_l2_to_l3(pde, addr);
5977 rv = pmap_load(pte) == 0;
5984 * pmap_is_referenced:
5986 * Return whether or not the specified physical page was referenced
5987 * in any physical maps.
5990 pmap_is_referenced(vm_page_t m)
5993 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5994 ("pmap_is_referenced: page %p is not managed", m));
5995 return (pmap_page_test_mappings(m, TRUE, FALSE));
5999 * Clear the write and modified bits in each of the given page's mappings.
6002 pmap_remove_write(vm_page_t m)
6004 struct md_page *pvh;
6006 struct rwlock *lock;
6007 pv_entry_t next_pv, pv;
6008 pt_entry_t oldpte, *pte, set, clear, mask, val;
6010 int md_gen, pvh_gen;
6012 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6013 ("pmap_remove_write: page %p is not managed", m));
6014 vm_page_assert_busied(m);
6016 if (!pmap_page_is_write_mapped(m))
6018 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6019 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
6022 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6024 PMAP_ASSERT_STAGE1(pmap);
6025 if (!PMAP_TRYLOCK(pmap)) {
6026 pvh_gen = pvh->pv_gen;
6030 if (pvh_gen != pvh->pv_gen) {
6036 pte = pmap_pte_exists(pmap, va, 2, __func__);
6037 if ((pmap_load(pte) & ATTR_SW_DBM) != 0)
6038 (void)pmap_demote_l2_locked(pmap, pte, va, &lock);
6039 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6040 ("inconsistent pv lock %p %p for page %p",
6041 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6044 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6046 if (!PMAP_TRYLOCK(pmap)) {
6047 pvh_gen = pvh->pv_gen;
6048 md_gen = m->md.pv_gen;
6052 if (pvh_gen != pvh->pv_gen ||
6053 md_gen != m->md.pv_gen) {
6058 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
6059 oldpte = pmap_load(pte);
6060 if ((oldpte & ATTR_SW_DBM) != 0) {
6061 if (pmap->pm_stage == PM_STAGE1) {
6062 set = ATTR_S1_AP_RW_BIT;
6064 mask = ATTR_S1_AP_RW_BIT;
6065 val = ATTR_S1_AP(ATTR_S1_AP_RW);
6068 clear = ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
6069 mask = ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
6070 val = ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
6072 clear |= ATTR_SW_DBM;
6073 while (!atomic_fcmpset_64(pte, &oldpte,
6074 (oldpte | set) & ~clear))
6077 if ((oldpte & mask) == val)
6079 pmap_invalidate_page(pmap, pv->pv_va, true);
6084 vm_page_aflag_clear(m, PGA_WRITEABLE);
6088 * pmap_ts_referenced:
6090 * Return a count of reference bits for a page, clearing those bits.
6091 * It is not necessary for every reference bit to be cleared, but it
6092 * is necessary that 0 only be returned when there are truly no
6093 * reference bits set.
6095 * As an optimization, update the page's dirty field if a modified bit is
6096 * found while counting reference bits. This opportunistic update can be
6097 * performed at low cost and can eliminate the need for some future calls
6098 * to pmap_is_modified(). However, since this function stops after
6099 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
6100 * dirty pages. Those dirty pages will only be detected by a future call
6101 * to pmap_is_modified().
6104 pmap_ts_referenced(vm_page_t m)
6106 struct md_page *pvh;
6109 struct rwlock *lock;
6110 pt_entry_t *pte, tpte;
6113 int cleared, md_gen, not_cleared, pvh_gen;
6114 struct spglist free;
6116 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6117 ("pmap_ts_referenced: page %p is not managed", m));
6120 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
6121 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6125 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6126 goto small_mappings;
6132 if (!PMAP_TRYLOCK(pmap)) {
6133 pvh_gen = pvh->pv_gen;
6137 if (pvh_gen != pvh->pv_gen) {
6143 pte = pmap_pte_exists(pmap, va, 2, __func__);
6144 tpte = pmap_load(pte);
6145 if (pmap_pte_dirty(pmap, tpte)) {
6147 * Although "tpte" is mapping a 2MB page, because
6148 * this function is called at a 4KB page granularity,
6149 * we only update the 4KB page under test.
6153 if ((tpte & ATTR_AF) != 0) {
6154 pa = VM_PAGE_TO_PHYS(m);
6157 * Since this reference bit is shared by 512 4KB pages,
6158 * it should not be cleared every time it is tested.
6159 * Apply a simple "hash" function on the physical page
6160 * number, the virtual superpage number, and the pmap
6161 * address to select one 4KB page out of the 512 on
6162 * which testing the reference bit will result in
6163 * clearing that reference bit. This function is
6164 * designed to avoid the selection of the same 4KB page
6165 * for every 2MB page mapping.
6167 * On demotion, a mapping that hasn't been referenced
6168 * is simply destroyed. To avoid the possibility of a
6169 * subsequent page fault on a demoted wired mapping,
6170 * always leave its reference bit set. Moreover,
6171 * since the superpage is wired, the current state of
6172 * its reference bit won't affect page replacement.
6174 if ((((pa >> PAGE_SHIFT) ^ (va >> L2_SHIFT) ^
6175 (uintptr_t)pmap) & (Ln_ENTRIES - 1)) == 0 &&
6176 (tpte & ATTR_SW_WIRED) == 0) {
6177 pmap_clear_bits(pte, ATTR_AF);
6178 pmap_invalidate_page(pmap, va, true);
6184 /* Rotate the PV list if it has more than one entry. */
6185 if (TAILQ_NEXT(pv, pv_next) != NULL) {
6186 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6187 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6190 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6192 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6194 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6201 if (!PMAP_TRYLOCK(pmap)) {
6202 pvh_gen = pvh->pv_gen;
6203 md_gen = m->md.pv_gen;
6207 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6212 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
6213 tpte = pmap_load(pte);
6214 if (pmap_pte_dirty(pmap, tpte))
6216 if ((tpte & ATTR_AF) != 0) {
6217 if ((tpte & ATTR_SW_WIRED) == 0) {
6218 pmap_clear_bits(pte, ATTR_AF);
6219 pmap_invalidate_page(pmap, pv->pv_va, true);
6225 /* Rotate the PV list if it has more than one entry. */
6226 if (TAILQ_NEXT(pv, pv_next) != NULL) {
6227 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6228 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6231 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6232 not_cleared < PMAP_TS_REFERENCED_MAX);
6235 vm_page_free_pages_toq(&free, true);
6236 return (cleared + not_cleared);
6240 * Apply the given advice to the specified range of addresses within the
6241 * given pmap. Depending on the advice, clear the referenced and/or
6242 * modified flags in each mapping and set the mapped page's dirty field.
6245 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6247 struct rwlock *lock;
6248 vm_offset_t va, va_next;
6250 pd_entry_t *l0, *l1, *l2, oldl2;
6251 pt_entry_t *l3, oldl3;
6253 PMAP_ASSERT_STAGE1(pmap);
6255 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6259 for (; sva < eva; sva = va_next) {
6260 l0 = pmap_l0(pmap, sva);
6261 if (pmap_load(l0) == 0) {
6262 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
6268 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
6271 l1 = pmap_l0_to_l1(l0, sva);
6272 if (pmap_load(l1) == 0)
6274 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
6275 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
6279 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
6282 l2 = pmap_l1_to_l2(l1, sva);
6283 oldl2 = pmap_load(l2);
6286 if ((oldl2 & ATTR_DESCR_MASK) == L2_BLOCK) {
6287 if ((oldl2 & ATTR_SW_MANAGED) == 0)
6290 if (!pmap_demote_l2_locked(pmap, l2, sva, &lock)) {
6295 * The 2MB page mapping was destroyed.
6301 * Unless the page mappings are wired, remove the
6302 * mapping to a single page so that a subsequent
6303 * access may repromote. Choosing the last page
6304 * within the address range [sva, min(va_next, eva))
6305 * generally results in more repromotions. Since the
6306 * underlying page table page is fully populated, this
6307 * removal never frees a page table page.
6309 if ((oldl2 & ATTR_SW_WIRED) == 0) {
6315 ("pmap_advise: no address gap"));
6316 l3 = pmap_l2_to_l3(l2, va);
6317 KASSERT(pmap_load(l3) != 0,
6318 ("pmap_advise: invalid PTE"));
6319 pmap_remove_l3(pmap, l3, va, pmap_load(l2),
6325 KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
6326 ("pmap_advise: invalid L2 entry after demotion"));
6330 for (l3 = pmap_l2_to_l3(l2, sva); sva != va_next; l3++,
6332 oldl3 = pmap_load(l3);
6333 if ((oldl3 & (ATTR_SW_MANAGED | ATTR_DESCR_MASK)) !=
6334 (ATTR_SW_MANAGED | L3_PAGE))
6336 else if (pmap_pte_dirty(pmap, oldl3)) {
6337 if (advice == MADV_DONTNEED) {
6339 * Future calls to pmap_is_modified()
6340 * can be avoided by making the page
6343 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(oldl3));
6346 while (!atomic_fcmpset_long(l3, &oldl3,
6347 (oldl3 & ~ATTR_AF) |
6348 ATTR_S1_AP(ATTR_S1_AP_RO)))
6350 } else if ((oldl3 & ATTR_AF) != 0)
6351 pmap_clear_bits(l3, ATTR_AF);
6358 if (va != va_next) {
6359 pmap_s1_invalidate_range(pmap, va, sva, true);
6364 pmap_s1_invalidate_range(pmap, va, sva, true);
6370 * Clear the modify bits on the specified physical page.
6373 pmap_clear_modify(vm_page_t m)
6375 struct md_page *pvh;
6376 struct rwlock *lock;
6378 pv_entry_t next_pv, pv;
6379 pd_entry_t *l2, oldl2;
6380 pt_entry_t *l3, oldl3;
6382 int md_gen, pvh_gen;
6384 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6385 ("pmap_clear_modify: page %p is not managed", m));
6386 vm_page_assert_busied(m);
6388 if (!pmap_page_is_write_mapped(m))
6390 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
6391 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6394 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6396 PMAP_ASSERT_STAGE1(pmap);
6397 if (!PMAP_TRYLOCK(pmap)) {
6398 pvh_gen = pvh->pv_gen;
6402 if (pvh_gen != pvh->pv_gen) {
6408 l2 = pmap_l2(pmap, va);
6409 oldl2 = pmap_load(l2);
6410 /* If oldl2 has ATTR_SW_DBM set, then it is also dirty. */
6411 if ((oldl2 & ATTR_SW_DBM) != 0 &&
6412 pmap_demote_l2_locked(pmap, l2, va, &lock) &&
6413 (oldl2 & ATTR_SW_WIRED) == 0) {
6415 * Write protect the mapping to a single page so that
6416 * a subsequent write access may repromote.
6418 va += VM_PAGE_TO_PHYS(m) - PTE_TO_PHYS(oldl2);
6419 l3 = pmap_l2_to_l3(l2, va);
6420 oldl3 = pmap_load(l3);
6421 while (!atomic_fcmpset_long(l3, &oldl3,
6422 (oldl3 & ~ATTR_SW_DBM) | ATTR_S1_AP(ATTR_S1_AP_RO)))
6425 pmap_s1_invalidate_page(pmap, va, true);
6429 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6431 PMAP_ASSERT_STAGE1(pmap);
6432 if (!PMAP_TRYLOCK(pmap)) {
6433 md_gen = m->md.pv_gen;
6434 pvh_gen = pvh->pv_gen;
6438 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6443 l2 = pmap_l2(pmap, pv->pv_va);
6444 l3 = pmap_l2_to_l3(l2, pv->pv_va);
6445 oldl3 = pmap_load(l3);
6446 if ((oldl3 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) == ATTR_SW_DBM){
6447 pmap_set_bits(l3, ATTR_S1_AP(ATTR_S1_AP_RO));
6448 pmap_s1_invalidate_page(pmap, pv->pv_va, true);
6456 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6458 struct pmap_preinit_mapping *ppim;
6459 vm_offset_t va, offset;
6460 pd_entry_t old_l2e, *pde;
6462 int i, lvl, l2_blocks, free_l2_count, start_idx;
6464 if (!vm_initialized) {
6466 * No L3 ptables so map entire L2 blocks where start VA is:
6467 * preinit_map_va + start_idx * L2_SIZE
6468 * There may be duplicate mappings (multiple VA -> same PA) but
6469 * ARM64 dcache is always PIPT so that's acceptable.
6474 /* Calculate how many L2 blocks are needed for the mapping */
6475 l2_blocks = (roundup2(pa + size, L2_SIZE) -
6476 rounddown2(pa, L2_SIZE)) >> L2_SHIFT;
6478 offset = pa & L2_OFFSET;
6480 if (preinit_map_va == 0)
6483 /* Map 2MiB L2 blocks from reserved VA space */
6487 /* Find enough free contiguous VA space */
6488 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6489 ppim = pmap_preinit_mapping + i;
6490 if (free_l2_count > 0 && ppim->pa != 0) {
6491 /* Not enough space here */
6497 if (ppim->pa == 0) {
6499 if (start_idx == -1)
6502 if (free_l2_count == l2_blocks)
6506 if (free_l2_count != l2_blocks)
6507 panic("%s: too many preinit mappings", __func__);
6509 va = preinit_map_va + (start_idx * L2_SIZE);
6510 for (i = start_idx; i < start_idx + l2_blocks; i++) {
6511 /* Mark entries as allocated */
6512 ppim = pmap_preinit_mapping + i;
6514 ppim->va = va + offset;
6519 pa = rounddown2(pa, L2_SIZE);
6521 for (i = 0; i < l2_blocks; i++) {
6522 pde = pmap_pde(kernel_pmap, va, &lvl);
6523 KASSERT(pde != NULL,
6524 ("pmap_mapbios: Invalid page entry, va: 0x%lx",
6527 ("pmap_mapbios: Invalid level %d", lvl));
6529 /* Insert L2_BLOCK */
6530 l2 = pmap_l1_to_l2(pde, va);
6531 old_l2e |= pmap_load_store(l2,
6532 PHYS_TO_PTE(pa) | ATTR_DEFAULT | ATTR_S1_XN |
6533 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) | L2_BLOCK);
6538 if ((old_l2e & ATTR_DESCR_VALID) != 0)
6539 pmap_s1_invalidate_all(kernel_pmap);
6542 * Because the old entries were invalid and the new
6543 * mappings are not executable, an isb is not required.
6548 va = preinit_map_va + (start_idx * L2_SIZE);
6551 /* kva_alloc may be used to map the pages */
6552 offset = pa & PAGE_MASK;
6553 size = round_page(offset + size);
6555 va = kva_alloc(size);
6557 panic("%s: Couldn't allocate KVA", __func__);
6559 pde = pmap_pde(kernel_pmap, va, &lvl);
6560 KASSERT(lvl == 2, ("pmap_mapbios: Invalid level %d", lvl));
6562 /* L3 table is linked */
6563 va = trunc_page(va);
6564 pa = trunc_page(pa);
6565 pmap_kenter(va, size, pa, memory_mapping_mode(pa));
6568 return ((void *)(va + offset));
6572 pmap_unmapbios(void *p, vm_size_t size)
6574 struct pmap_preinit_mapping *ppim;
6575 vm_offset_t offset, va, va_trunc;
6578 int i, lvl, l2_blocks, block;
6581 va = (vm_offset_t)p;
6583 (roundup2(va + size, L2_SIZE) - rounddown2(va, L2_SIZE)) >> L2_SHIFT;
6584 KASSERT(l2_blocks > 0, ("pmap_unmapbios: invalid size %lx", size));
6586 /* Remove preinit mapping */
6587 preinit_map = false;
6589 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6590 ppim = pmap_preinit_mapping + i;
6591 if (ppim->va == va) {
6592 KASSERT(ppim->size == size,
6593 ("pmap_unmapbios: size mismatch"));
6598 offset = block * L2_SIZE;
6599 va_trunc = rounddown2(va, L2_SIZE) + offset;
6601 /* Remove L2_BLOCK */
6602 pde = pmap_pde(kernel_pmap, va_trunc, &lvl);
6603 KASSERT(pde != NULL,
6604 ("pmap_unmapbios: Invalid page entry, va: 0x%lx",
6606 l2 = pmap_l1_to_l2(pde, va_trunc);
6609 if (block == (l2_blocks - 1))
6615 pmap_s1_invalidate_all(kernel_pmap);
6619 /* Unmap the pages reserved with kva_alloc. */
6620 if (vm_initialized) {
6621 offset = va & PAGE_MASK;
6622 size = round_page(offset + size);
6623 va = trunc_page(va);
6625 /* Unmap and invalidate the pages */
6626 pmap_kremove_device(va, size);
6633 * Sets the memory attribute for the specified page.
6636 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6639 m->md.pv_memattr = ma;
6642 * If "m" is a normal page, update its direct mapping. This update
6643 * can be relied upon to perform any cache operations that are
6644 * required for data coherence.
6646 if ((m->flags & PG_FICTITIOUS) == 0 &&
6647 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6648 m->md.pv_memattr) != 0)
6649 panic("memory attribute change on the direct map failed");
6653 * Changes the specified virtual address range's memory type to that given by
6654 * the parameter "mode". The specified virtual address range must be
6655 * completely contained within either the direct map or the kernel map. If
6656 * the virtual address range is contained within the kernel map, then the
6657 * memory type for each of the corresponding ranges of the direct map is also
6658 * changed. (The corresponding ranges of the direct map are those ranges that
6659 * map the same physical pages as the specified virtual address range.) These
6660 * changes to the direct map are necessary because Intel describes the
6661 * behavior of their processors as "undefined" if two or more mappings to the
6662 * same physical page have different memory types.
6664 * Returns zero if the change completed successfully, and either EINVAL or
6665 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6666 * of the virtual address range was not mapped, and ENOMEM is returned if
6667 * there was insufficient memory available to complete the change. In the
6668 * latter case, the memory type may have been changed on some part of the
6669 * virtual address range or the direct map.
6672 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6676 PMAP_LOCK(kernel_pmap);
6677 error = pmap_change_props_locked(va, size, PROT_NONE, mode, false);
6678 PMAP_UNLOCK(kernel_pmap);
6683 * Changes the specified virtual address range's protections to those
6684 * specified by "prot". Like pmap_change_attr(), protections for aliases
6685 * in the direct map are updated as well. Protections on aliasing mappings may
6686 * be a subset of the requested protections; for example, mappings in the direct
6687 * map are never executable.
6690 pmap_change_prot(vm_offset_t va, vm_size_t size, vm_prot_t prot)
6694 /* Only supported within the kernel map. */
6695 if (va < VM_MIN_KERNEL_ADDRESS)
6698 PMAP_LOCK(kernel_pmap);
6699 error = pmap_change_props_locked(va, size, prot, -1, false);
6700 PMAP_UNLOCK(kernel_pmap);
6705 pmap_change_props_locked(vm_offset_t va, vm_size_t size, vm_prot_t prot,
6706 int mode, bool skip_unmapped)
6708 vm_offset_t base, offset, tmpva;
6711 pt_entry_t pte, *ptep, *newpte;
6712 pt_entry_t bits, mask;
6715 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6716 base = trunc_page(va);
6717 offset = va & PAGE_MASK;
6718 size = round_page(offset + size);
6720 if (!VIRT_IN_DMAP(base) &&
6721 !(base >= VM_MIN_KERNEL_ADDRESS && base < VM_MAX_KERNEL_ADDRESS))
6727 bits = ATTR_S1_IDX(mode);
6728 mask = ATTR_S1_IDX_MASK;
6729 if (mode == VM_MEMATTR_DEVICE) {
6734 if (prot != VM_PROT_NONE) {
6735 /* Don't mark the DMAP as executable. It never is on arm64. */
6736 if (VIRT_IN_DMAP(base)) {
6737 prot &= ~VM_PROT_EXECUTE;
6739 * XXX Mark the DMAP as writable for now. We rely
6740 * on this in ddb & dtrace to insert breakpoint
6743 prot |= VM_PROT_WRITE;
6746 if ((prot & VM_PROT_WRITE) == 0) {
6747 bits |= ATTR_S1_AP(ATTR_S1_AP_RO);
6749 if ((prot & VM_PROT_EXECUTE) == 0) {
6750 bits |= ATTR_S1_PXN;
6752 bits |= ATTR_S1_UXN;
6753 mask |= ATTR_S1_AP_MASK | ATTR_S1_XN;
6756 for (tmpva = base; tmpva < base + size; ) {
6757 ptep = pmap_pte(kernel_pmap, tmpva, &lvl);
6758 if (ptep == NULL && !skip_unmapped) {
6760 } else if ((ptep == NULL && skip_unmapped) ||
6761 (pmap_load(ptep) & mask) == bits) {
6763 * We already have the correct attribute or there
6764 * is no memory mapped at this address and we are
6765 * skipping unmapped memory.
6769 panic("Invalid DMAP table level: %d\n", lvl);
6771 tmpva = (tmpva & ~L1_OFFSET) + L1_SIZE;
6774 tmpva = (tmpva & ~L2_OFFSET) + L2_SIZE;
6781 /* We can't demote/promote this entry */
6782 MPASS((pmap_load(ptep) & ATTR_SW_NO_PROMOTE) == 0);
6785 * Split the entry to an level 3 table, then
6786 * set the new attribute.
6790 panic("Invalid DMAP table level: %d\n", lvl);
6792 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
6793 if ((tmpva & L1_OFFSET) == 0 &&
6794 (base + size - tmpva) >= L1_SIZE) {
6798 newpte = pmap_demote_l1(kernel_pmap, ptep,
6799 tmpva & ~L1_OFFSET);
6802 ptep = pmap_l1_to_l2(ptep, tmpva);
6805 if ((tmpva & L2_OFFSET) == 0 &&
6806 (base + size - tmpva) >= L2_SIZE) {
6810 newpte = pmap_demote_l2(kernel_pmap, ptep,
6814 ptep = pmap_l2_to_l3(ptep, tmpva);
6817 pte_size = PAGE_SIZE;
6821 /* Update the entry */
6822 pte = pmap_load(ptep);
6826 pmap_update_entry(kernel_pmap, ptep, pte, tmpva,
6829 pa = PTE_TO_PHYS(pte);
6830 if (!VIRT_IN_DMAP(tmpva) && PHYS_IN_DMAP(pa)) {
6832 * Keep the DMAP memory in sync.
6834 rv = pmap_change_props_locked(
6835 PHYS_TO_DMAP(pa), pte_size,
6842 * If moving to a non-cacheable entry flush
6845 if (mode == VM_MEMATTR_UNCACHEABLE)
6846 cpu_dcache_wbinv_range(tmpva, pte_size);
6855 * Create an L2 table to map all addresses within an L1 mapping.
6858 pmap_demote_l1(pmap_t pmap, pt_entry_t *l1, vm_offset_t va)
6860 pt_entry_t *l2, newl2, oldl1;
6862 vm_paddr_t l2phys, phys;
6866 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6867 oldl1 = pmap_load(l1);
6868 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
6869 KASSERT((oldl1 & ATTR_DESCR_MASK) == L1_BLOCK,
6870 ("pmap_demote_l1: Demoting a non-block entry"));
6871 KASSERT((va & L1_OFFSET) == 0,
6872 ("pmap_demote_l1: Invalid virtual address %#lx", va));
6873 KASSERT((oldl1 & ATTR_SW_MANAGED) == 0,
6874 ("pmap_demote_l1: Level 1 table shouldn't be managed"));
6875 KASSERT((oldl1 & ATTR_SW_NO_PROMOTE) == 0,
6876 ("pmap_demote_l1: Demoting entry with no-demote flag set"));
6879 if (va <= (vm_offset_t)l1 && va + L1_SIZE > (vm_offset_t)l1) {
6880 tmpl1 = kva_alloc(PAGE_SIZE);
6885 if ((ml2 = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED)) ==
6887 CTR2(KTR_PMAP, "pmap_demote_l1: failure for va %#lx"
6888 " in pmap %p", va, pmap);
6893 l2phys = VM_PAGE_TO_PHYS(ml2);
6894 l2 = (pt_entry_t *)PHYS_TO_DMAP(l2phys);
6896 /* Address the range points at */
6897 phys = PTE_TO_PHYS(oldl1);
6898 /* The attributed from the old l1 table to be copied */
6899 newl2 = oldl1 & ATTR_MASK;
6901 /* Create the new entries */
6902 for (i = 0; i < Ln_ENTRIES; i++) {
6903 l2[i] = newl2 | phys;
6906 KASSERT(l2[0] == ((oldl1 & ~ATTR_DESCR_MASK) | L2_BLOCK),
6907 ("Invalid l2 page (%lx != %lx)", l2[0],
6908 (oldl1 & ~ATTR_DESCR_MASK) | L2_BLOCK));
6911 pmap_kenter(tmpl1, PAGE_SIZE,
6912 DMAP_TO_PHYS((vm_offset_t)l1) & ~L3_OFFSET,
6913 VM_MEMATTR_WRITE_BACK);
6914 l1 = (pt_entry_t *)(tmpl1 + ((vm_offset_t)l1 & PAGE_MASK));
6917 pmap_update_entry(pmap, l1, l2phys | L1_TABLE, va, PAGE_SIZE);
6921 pmap_kremove(tmpl1);
6922 kva_free(tmpl1, PAGE_SIZE);
6929 pmap_fill_l3(pt_entry_t *firstl3, pt_entry_t newl3)
6933 for (l3 = firstl3; l3 - firstl3 < Ln_ENTRIES; l3++) {
6940 pmap_demote_l2_check(pt_entry_t *firstl3p __unused, pt_entry_t newl3e __unused)
6944 pt_entry_t *xl3p, *yl3p;
6946 for (xl3p = firstl3p; xl3p < firstl3p + Ln_ENTRIES;
6947 xl3p++, newl3e += PAGE_SIZE) {
6948 if (PTE_TO_PHYS(pmap_load(xl3p)) != PTE_TO_PHYS(newl3e)) {
6949 printf("pmap_demote_l2: xl3e %zd and newl3e map "
6950 "different pages: found %#lx, expected %#lx\n",
6951 xl3p - firstl3p, pmap_load(xl3p), newl3e);
6952 printf("page table dump\n");
6953 for (yl3p = firstl3p; yl3p < firstl3p + Ln_ENTRIES;
6955 printf("%zd %#lx\n", yl3p - firstl3p,
6962 KASSERT(PTE_TO_PHYS(pmap_load(firstl3p)) == PTE_TO_PHYS(newl3e),
6963 ("pmap_demote_l2: firstl3 and newl3e map different physical"
6970 pmap_demote_l2_abort(pmap_t pmap, vm_offset_t va, pt_entry_t *l2,
6971 struct rwlock **lockp)
6973 struct spglist free;
6976 (void)pmap_remove_l2(pmap, l2, va, pmap_load(pmap_l1(pmap, va)), &free,
6978 vm_page_free_pages_toq(&free, true);
6982 * Create an L3 table to map all addresses within an L2 mapping.
6985 pmap_demote_l2_locked(pmap_t pmap, pt_entry_t *l2, vm_offset_t va,
6986 struct rwlock **lockp)
6988 pt_entry_t *l3, newl3, oldl2;
6993 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6994 PMAP_ASSERT_STAGE1(pmap);
6995 KASSERT(ADDR_IS_CANONICAL(va),
6996 ("%s: Address not in canonical form: %lx", __func__, va));
6999 oldl2 = pmap_load(l2);
7000 KASSERT((oldl2 & ATTR_DESCR_MASK) == L2_BLOCK,
7001 ("pmap_demote_l2: Demoting a non-block entry"));
7002 KASSERT((oldl2 & ATTR_SW_NO_PROMOTE) == 0,
7003 ("pmap_demote_l2: Demoting entry with no-demote flag set"));
7007 if (va <= (vm_offset_t)l2 && va + L2_SIZE > (vm_offset_t)l2) {
7008 tmpl2 = kva_alloc(PAGE_SIZE);
7014 * Invalidate the 2MB page mapping and return "failure" if the
7015 * mapping was never accessed.
7017 if ((oldl2 & ATTR_AF) == 0) {
7018 KASSERT((oldl2 & ATTR_SW_WIRED) == 0,
7019 ("pmap_demote_l2: a wired mapping is missing ATTR_AF"));
7020 pmap_demote_l2_abort(pmap, va, l2, lockp);
7021 CTR2(KTR_PMAP, "pmap_demote_l2: failure for va %#lx in pmap %p",
7026 if ((ml3 = pmap_remove_pt_page(pmap, va)) == NULL) {
7027 KASSERT((oldl2 & ATTR_SW_WIRED) == 0,
7028 ("pmap_demote_l2: page table page for a wired mapping"
7032 * If the page table page is missing and the mapping
7033 * is for a kernel address, the mapping must belong to
7034 * either the direct map or the early kernel memory.
7035 * Page table pages are preallocated for every other
7036 * part of the kernel address space, so the direct map
7037 * region and early kernel memory are the only parts of the
7038 * kernel address space that must be handled here.
7040 KASSERT(!ADDR_IS_KERNEL(va) || VIRT_IN_DMAP(va) ||
7041 (va >= VM_MIN_KERNEL_ADDRESS && va < kernel_vm_end),
7042 ("pmap_demote_l2: No saved mpte for va %#lx", va));
7045 * If the 2MB page mapping belongs to the direct map
7046 * region of the kernel's address space, then the page
7047 * allocation request specifies the highest possible
7048 * priority (VM_ALLOC_INTERRUPT). Otherwise, the
7049 * priority is normal.
7051 ml3 = vm_page_alloc_noobj(
7052 (VIRT_IN_DMAP(va) ? VM_ALLOC_INTERRUPT : 0) |
7056 * If the allocation of the new page table page fails,
7057 * invalidate the 2MB page mapping and return "failure".
7060 pmap_demote_l2_abort(pmap, va, l2, lockp);
7061 CTR2(KTR_PMAP, "pmap_demote_l2: failure for va %#lx"
7062 " in pmap %p", va, pmap);
7065 ml3->pindex = pmap_l2_pindex(va);
7067 if (!ADDR_IS_KERNEL(va)) {
7068 ml3->ref_count = NL3PG;
7069 pmap_resident_count_inc(pmap, 1);
7072 l3phys = VM_PAGE_TO_PHYS(ml3);
7073 l3 = (pt_entry_t *)PHYS_TO_DMAP(l3phys);
7074 newl3 = (oldl2 & ~ATTR_DESCR_MASK) | L3_PAGE;
7075 KASSERT((oldl2 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) !=
7076 (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM),
7077 ("pmap_demote_l2: L2 entry is writeable but not dirty"));
7080 * If the PTP is not leftover from an earlier promotion or it does not
7081 * have ATTR_AF set in every L3E, then fill it. The new L3Es will all
7084 * When pmap_update_entry() clears the old L2 mapping, it (indirectly)
7085 * performs a dsb(). That dsb() ensures that the stores for filling
7086 * "l3" are visible before "l3" is added to the page table.
7088 if (!vm_page_all_valid(ml3))
7089 pmap_fill_l3(l3, newl3);
7091 pmap_demote_l2_check(l3, newl3);
7094 * If the mapping has changed attributes, update the L3Es.
7096 if ((pmap_load(l3) & (ATTR_MASK & ~ATTR_AF)) != (newl3 & (ATTR_MASK &
7098 pmap_fill_l3(l3, newl3);
7101 * Map the temporary page so we don't lose access to the l2 table.
7104 pmap_kenter(tmpl2, PAGE_SIZE,
7105 DMAP_TO_PHYS((vm_offset_t)l2) & ~L3_OFFSET,
7106 VM_MEMATTR_WRITE_BACK);
7107 l2 = (pt_entry_t *)(tmpl2 + ((vm_offset_t)l2 & PAGE_MASK));
7111 * The spare PV entries must be reserved prior to demoting the
7112 * mapping, that is, prior to changing the PDE. Otherwise, the state
7113 * of the L2 and the PV lists will be inconsistent, which can result
7114 * in reclaim_pv_chunk() attempting to remove a PV entry from the
7115 * wrong PV list and pmap_pv_demote_l2() failing to find the expected
7116 * PV entry for the 2MB page mapping that is being demoted.
7118 if ((oldl2 & ATTR_SW_MANAGED) != 0)
7119 reserve_pv_entries(pmap, Ln_ENTRIES - 1, lockp);
7122 * Pass PAGE_SIZE so that a single TLB invalidation is performed on
7123 * the 2MB page mapping.
7125 pmap_update_entry(pmap, l2, l3phys | L2_TABLE, va, PAGE_SIZE);
7128 * Demote the PV entry.
7130 if ((oldl2 & ATTR_SW_MANAGED) != 0)
7131 pmap_pv_demote_l2(pmap, va, PTE_TO_PHYS(oldl2), lockp);
7133 atomic_add_long(&pmap_l2_demotions, 1);
7134 CTR3(KTR_PMAP, "pmap_demote_l2: success for va %#lx"
7135 " in pmap %p %lx", va, pmap, l3[0]);
7139 pmap_kremove(tmpl2);
7140 kva_free(tmpl2, PAGE_SIZE);
7148 pmap_demote_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va)
7150 struct rwlock *lock;
7154 l3 = pmap_demote_l2_locked(pmap, l2, va, &lock);
7161 * Perform the pmap work for mincore(2). If the page is not both referenced and
7162 * modified by this pmap, returns its physical address so that the caller can
7163 * find other mappings.
7166 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
7168 pt_entry_t *pte, tpte;
7169 vm_paddr_t mask, pa;
7173 PMAP_ASSERT_STAGE1(pmap);
7175 pte = pmap_pte(pmap, addr, &lvl);
7177 tpte = pmap_load(pte);
7190 panic("pmap_mincore: invalid level %d", lvl);
7193 managed = (tpte & ATTR_SW_MANAGED) != 0;
7194 val = MINCORE_INCORE;
7196 val |= MINCORE_PSIND(3 - lvl);
7197 if ((managed && pmap_pte_dirty(pmap, tpte)) || (!managed &&
7198 (tpte & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP(ATTR_S1_AP_RW)))
7199 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
7200 if ((tpte & ATTR_AF) == ATTR_AF)
7201 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
7203 pa = PTE_TO_PHYS(tpte) | (addr & mask);
7209 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
7210 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) && managed) {
7218 * Garbage collect every ASID that is neither active on a processor nor
7222 pmap_reset_asid_set(pmap_t pmap)
7225 int asid, cpuid, epoch;
7226 struct asid_set *set;
7227 enum pmap_stage stage;
7229 set = pmap->pm_asid_set;
7230 stage = pmap->pm_stage;
7232 set = pmap->pm_asid_set;
7233 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
7234 mtx_assert(&set->asid_set_mutex, MA_OWNED);
7237 * Ensure that the store to asid_epoch is globally visible before the
7238 * loads from pc_curpmap are performed.
7240 epoch = set->asid_epoch + 1;
7241 if (epoch == INT_MAX)
7243 set->asid_epoch = epoch;
7245 if (stage == PM_STAGE1) {
7246 __asm __volatile("tlbi vmalle1is");
7248 KASSERT(pmap_clean_stage2_tlbi != NULL,
7249 ("%s: Unset stage 2 tlb invalidation callback\n",
7251 pmap_clean_stage2_tlbi();
7254 bit_nclear(set->asid_set, ASID_FIRST_AVAILABLE,
7255 set->asid_set_size - 1);
7256 CPU_FOREACH(cpuid) {
7257 if (cpuid == curcpu)
7259 if (stage == PM_STAGE1) {
7260 curpmap = pcpu_find(cpuid)->pc_curpmap;
7261 PMAP_ASSERT_STAGE1(pmap);
7263 curpmap = pcpu_find(cpuid)->pc_curvmpmap;
7264 if (curpmap == NULL)
7266 PMAP_ASSERT_STAGE2(pmap);
7268 KASSERT(curpmap->pm_asid_set == set, ("Incorrect set"));
7269 asid = COOKIE_TO_ASID(curpmap->pm_cookie);
7272 bit_set(set->asid_set, asid);
7273 curpmap->pm_cookie = COOKIE_FROM(asid, epoch);
7278 * Allocate a new ASID for the specified pmap.
7281 pmap_alloc_asid(pmap_t pmap)
7283 struct asid_set *set;
7286 set = pmap->pm_asid_set;
7287 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
7289 mtx_lock_spin(&set->asid_set_mutex);
7292 * While this processor was waiting to acquire the asid set mutex,
7293 * pmap_reset_asid_set() running on another processor might have
7294 * updated this pmap's cookie to the current epoch. In which case, we
7295 * don't need to allocate a new ASID.
7297 if (COOKIE_TO_EPOCH(pmap->pm_cookie) == set->asid_epoch)
7300 bit_ffc_at(set->asid_set, set->asid_next, set->asid_set_size,
7302 if (new_asid == -1) {
7303 bit_ffc_at(set->asid_set, ASID_FIRST_AVAILABLE,
7304 set->asid_next, &new_asid);
7305 if (new_asid == -1) {
7306 pmap_reset_asid_set(pmap);
7307 bit_ffc_at(set->asid_set, ASID_FIRST_AVAILABLE,
7308 set->asid_set_size, &new_asid);
7309 KASSERT(new_asid != -1, ("ASID allocation failure"));
7312 bit_set(set->asid_set, new_asid);
7313 set->asid_next = new_asid + 1;
7314 pmap->pm_cookie = COOKIE_FROM(new_asid, set->asid_epoch);
7316 mtx_unlock_spin(&set->asid_set_mutex);
7319 static uint64_t __read_mostly ttbr_flags;
7322 * Compute the value that should be stored in ttbr0 to activate the specified
7323 * pmap. This value may change from time to time.
7326 pmap_to_ttbr0(pmap_t pmap)
7330 ttbr = pmap->pm_ttbr;
7331 ttbr |= ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
7338 pmap_set_cnp(void *arg)
7340 uint64_t ttbr0, ttbr1;
7343 cpuid = *(u_int *)arg;
7344 if (cpuid == curcpu) {
7346 * Set the flags while all CPUs are handling the
7347 * smp_rendezvous so will not call pmap_to_ttbr0. Any calls
7348 * to pmap_to_ttbr0 after this will have the CnP flag set.
7349 * The dsb after invalidating the TLB will act as a barrier
7350 * to ensure all CPUs can observe this change.
7352 ttbr_flags |= TTBR_CnP;
7355 ttbr0 = READ_SPECIALREG(ttbr0_el1);
7358 ttbr1 = READ_SPECIALREG(ttbr1_el1);
7361 /* Update ttbr{0,1}_el1 with the CnP flag */
7362 WRITE_SPECIALREG(ttbr0_el1, ttbr0);
7363 WRITE_SPECIALREG(ttbr1_el1, ttbr1);
7365 __asm __volatile("tlbi vmalle1is");
7371 * Defer enabling CnP until we have read the ID registers to know if it's
7372 * supported on all CPUs.
7375 pmap_init_cnp(void *dummy __unused)
7380 if (!get_kernel_reg(ID_AA64MMFR2_EL1, ®))
7383 if (ID_AA64MMFR2_CnP_VAL(reg) != ID_AA64MMFR2_CnP_NONE) {
7385 printf("Enabling CnP\n");
7387 smp_rendezvous(NULL, pmap_set_cnp, NULL, &cpuid);
7391 SYSINIT(pmap_init_cnp, SI_SUB_SMP, SI_ORDER_ANY, pmap_init_cnp, NULL);
7394 pmap_activate_int(pmap_t pmap)
7396 struct asid_set *set;
7399 KASSERT(PCPU_GET(curpmap) != NULL, ("no active pmap"));
7400 KASSERT(pmap != kernel_pmap, ("kernel pmap activation"));
7402 if ((pmap->pm_stage == PM_STAGE1 && pmap == PCPU_GET(curpmap)) ||
7403 (pmap->pm_stage == PM_STAGE2 && pmap == PCPU_GET(curvmpmap))) {
7405 * Handle the possibility that the old thread was preempted
7406 * after an "ic" or "tlbi" instruction but before it performed
7407 * a "dsb" instruction. If the old thread migrates to a new
7408 * processor, its completion of a "dsb" instruction on that
7409 * new processor does not guarantee that the "ic" or "tlbi"
7410 * instructions performed on the old processor have completed.
7416 set = pmap->pm_asid_set;
7417 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
7420 * Ensure that the store to curpmap is globally visible before the
7421 * load from asid_epoch is performed.
7423 if (pmap->pm_stage == PM_STAGE1)
7424 PCPU_SET(curpmap, pmap);
7426 PCPU_SET(curvmpmap, pmap);
7428 epoch = COOKIE_TO_EPOCH(pmap->pm_cookie);
7429 if (epoch >= 0 && epoch != set->asid_epoch)
7430 pmap_alloc_asid(pmap);
7432 if (pmap->pm_stage == PM_STAGE1) {
7433 set_ttbr0(pmap_to_ttbr0(pmap));
7434 if (PCPU_GET(bcast_tlbi_workaround) != 0)
7435 invalidate_local_icache();
7441 pmap_activate_vm(pmap_t pmap)
7444 PMAP_ASSERT_STAGE2(pmap);
7446 (void)pmap_activate_int(pmap);
7450 pmap_activate(struct thread *td)
7454 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7455 PMAP_ASSERT_STAGE1(pmap);
7457 (void)pmap_activate_int(pmap);
7462 * Activate the thread we are switching to.
7463 * To simplify the assembly in cpu_throw return the new threads pcb.
7466 pmap_switch(struct thread *new)
7468 pcpu_bp_harden bp_harden;
7471 /* Store the new curthread */
7472 PCPU_SET(curthread, new);
7474 /* And the new pcb */
7476 PCPU_SET(curpcb, pcb);
7479 * TODO: We may need to flush the cache here if switching
7480 * to a user process.
7483 if (pmap_activate_int(vmspace_pmap(new->td_proc->p_vmspace))) {
7485 * Stop userspace from training the branch predictor against
7486 * other processes. This will call into a CPU specific
7487 * function that clears the branch predictor state.
7489 bp_harden = PCPU_GET(bp_harden);
7490 if (bp_harden != NULL)
7498 pmap_sync_icache(pmap_t pmap, vm_offset_t va, vm_size_t sz)
7501 PMAP_ASSERT_STAGE1(pmap);
7502 KASSERT(ADDR_IS_CANONICAL(va),
7503 ("%s: Address not in canonical form: %lx", __func__, va));
7505 if (ADDR_IS_KERNEL(va)) {
7506 cpu_icache_sync_range(va, sz);
7511 /* Find the length of data in this page to flush */
7512 offset = va & PAGE_MASK;
7513 len = imin(PAGE_SIZE - offset, sz);
7516 /* Extract the physical address & find it in the DMAP */
7517 pa = pmap_extract(pmap, va);
7519 cpu_icache_sync_range(PHYS_TO_DMAP(pa), len);
7521 /* Move to the next page */
7524 /* Set the length for the next iteration */
7525 len = imin(PAGE_SIZE, sz);
7531 pmap_stage2_fault(pmap_t pmap, uint64_t esr, uint64_t far)
7534 pt_entry_t *ptep, pte;
7537 PMAP_ASSERT_STAGE2(pmap);
7540 /* Data and insn aborts use same encoding for FSC field. */
7541 dfsc = esr & ISS_DATA_DFSC_MASK;
7543 case ISS_DATA_DFSC_TF_L0:
7544 case ISS_DATA_DFSC_TF_L1:
7545 case ISS_DATA_DFSC_TF_L2:
7546 case ISS_DATA_DFSC_TF_L3:
7548 pdep = pmap_pde(pmap, far, &lvl);
7549 if (pdep == NULL || lvl != (dfsc - ISS_DATA_DFSC_TF_L1)) {
7556 ptep = pmap_l0_to_l1(pdep, far);
7559 ptep = pmap_l1_to_l2(pdep, far);
7562 ptep = pmap_l2_to_l3(pdep, far);
7565 panic("%s: Invalid pde level %d", __func__,lvl);
7569 case ISS_DATA_DFSC_AFF_L1:
7570 case ISS_DATA_DFSC_AFF_L2:
7571 case ISS_DATA_DFSC_AFF_L3:
7573 ptep = pmap_pte(pmap, far, &lvl);
7575 if (ptep != NULL && (pte = pmap_load(ptep)) != 0) {
7577 pmap_invalidate_vpipt_icache();
7580 * If accessing an executable page invalidate
7581 * the I-cache so it will be valid when we
7582 * continue execution in the guest. The D-cache
7583 * is assumed to already be clean to the Point
7586 if ((pte & ATTR_S2_XN_MASK) !=
7587 ATTR_S2_XN(ATTR_S2_XN_NONE)) {
7588 invalidate_icache();
7591 pmap_set_bits(ptep, ATTR_AF | ATTR_DESCR_VALID);
7602 pmap_fault(pmap_t pmap, uint64_t esr, uint64_t far)
7604 pt_entry_t pte, *ptep;
7611 ec = ESR_ELx_EXCEPTION(esr);
7613 case EXCP_INSN_ABORT_L:
7614 case EXCP_INSN_ABORT:
7615 case EXCP_DATA_ABORT_L:
7616 case EXCP_DATA_ABORT:
7622 if (pmap->pm_stage == PM_STAGE2)
7623 return (pmap_stage2_fault(pmap, esr, far));
7625 /* Data and insn aborts use same encoding for FSC field. */
7626 switch (esr & ISS_DATA_DFSC_MASK) {
7627 case ISS_DATA_DFSC_AFF_L1:
7628 case ISS_DATA_DFSC_AFF_L2:
7629 case ISS_DATA_DFSC_AFF_L3:
7631 ptep = pmap_pte(pmap, far, &lvl);
7633 pmap_set_bits(ptep, ATTR_AF);
7636 * XXXMJ as an optimization we could mark the entry
7637 * dirty if this is a write fault.
7642 case ISS_DATA_DFSC_PF_L1:
7643 case ISS_DATA_DFSC_PF_L2:
7644 case ISS_DATA_DFSC_PF_L3:
7645 if ((ec != EXCP_DATA_ABORT_L && ec != EXCP_DATA_ABORT) ||
7646 (esr & ISS_DATA_WnR) == 0)
7649 ptep = pmap_pte(pmap, far, &lvl);
7651 ((pte = pmap_load(ptep)) & ATTR_SW_DBM) != 0) {
7652 if ((pte & ATTR_S1_AP_RW_BIT) ==
7653 ATTR_S1_AP(ATTR_S1_AP_RO)) {
7654 pmap_clear_bits(ptep, ATTR_S1_AP_RW_BIT);
7655 pmap_s1_invalidate_page(pmap, far, true);
7661 case ISS_DATA_DFSC_TF_L0:
7662 case ISS_DATA_DFSC_TF_L1:
7663 case ISS_DATA_DFSC_TF_L2:
7664 case ISS_DATA_DFSC_TF_L3:
7666 * Retry the translation. A break-before-make sequence can
7667 * produce a transient fault.
7669 if (pmap == kernel_pmap) {
7671 * The translation fault may have occurred within a
7672 * critical section. Therefore, we must check the
7673 * address without acquiring the kernel pmap's lock.
7675 if (pmap_klookup(far, NULL))
7679 /* Ask the MMU to check the address. */
7680 intr = intr_disable();
7681 par = arm64_address_translate_s1e0r(far);
7686 * If the translation was successful, then we can
7687 * return success to the trap handler.
7689 if (PAR_SUCCESS(par))
7699 * Increase the starting virtual address of the given mapping if a
7700 * different alignment might result in more superpage mappings.
7703 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7704 vm_offset_t *addr, vm_size_t size)
7706 vm_offset_t superpage_offset;
7710 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7711 offset += ptoa(object->pg_color);
7712 superpage_offset = offset & L2_OFFSET;
7713 if (size - ((L2_SIZE - superpage_offset) & L2_OFFSET) < L2_SIZE ||
7714 (*addr & L2_OFFSET) == superpage_offset)
7716 if ((*addr & L2_OFFSET) < superpage_offset)
7717 *addr = (*addr & ~L2_OFFSET) + superpage_offset;
7719 *addr = ((*addr + L2_OFFSET) & ~L2_OFFSET) + superpage_offset;
7723 * Get the kernel virtual address of a set of physical pages. If there are
7724 * physical addresses not covered by the DMAP perform a transient mapping
7725 * that will be removed when calling pmap_unmap_io_transient.
7727 * \param page The pages the caller wishes to obtain the virtual
7728 * address on the kernel memory map.
7729 * \param vaddr On return contains the kernel virtual memory address
7730 * of the pages passed in the page parameter.
7731 * \param count Number of pages passed in.
7732 * \param can_fault true if the thread using the mapped pages can take
7733 * page faults, false otherwise.
7735 * \returns true if the caller must call pmap_unmap_io_transient when
7736 * finished or false otherwise.
7740 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7745 int error __diagused, i;
7748 * Allocate any KVA space that we need, this is done in a separate
7749 * loop to prevent calling vmem_alloc while pinned.
7751 needs_mapping = false;
7752 for (i = 0; i < count; i++) {
7753 paddr = VM_PAGE_TO_PHYS(page[i]);
7754 if (__predict_false(!PHYS_IN_DMAP(paddr))) {
7755 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7756 M_BESTFIT | M_WAITOK, &vaddr[i]);
7757 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7758 needs_mapping = true;
7760 vaddr[i] = PHYS_TO_DMAP(paddr);
7764 /* Exit early if everything is covered by the DMAP */
7770 for (i = 0; i < count; i++) {
7771 paddr = VM_PAGE_TO_PHYS(page[i]);
7772 if (!PHYS_IN_DMAP(paddr)) {
7774 "pmap_map_io_transient: TODO: Map out of DMAP data");
7778 return (needs_mapping);
7782 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7790 for (i = 0; i < count; i++) {
7791 paddr = VM_PAGE_TO_PHYS(page[i]);
7792 if (!PHYS_IN_DMAP(paddr)) {
7793 panic("ARM64TODO: pmap_unmap_io_transient: Unmap data");
7799 pmap_is_valid_memattr(pmap_t pmap __unused, vm_memattr_t mode)
7802 return (mode >= VM_MEMATTR_DEVICE && mode <= VM_MEMATTR_WRITE_THROUGH);
7806 static vm_paddr_t pmap_san_early_kernstart;
7807 static pd_entry_t *pmap_san_early_l2;
7809 void __nosanitizeaddress
7810 pmap_san_bootstrap(struct arm64_bootparams *abp)
7813 pmap_san_early_kernstart = KERNBASE - abp->kern_delta;
7814 kasan_init_early(abp->kern_stack, KSTACK_PAGES * PAGE_SIZE);
7817 #define SAN_BOOTSTRAP_L2_SIZE (1 * L2_SIZE)
7818 #define SAN_BOOTSTRAP_SIZE (2 * PAGE_SIZE)
7819 static vm_offset_t __nosanitizeaddress
7820 pmap_san_enter_bootstrap_alloc_l2(void)
7822 static uint8_t bootstrap_data[SAN_BOOTSTRAP_L2_SIZE] __aligned(L2_SIZE);
7823 static size_t offset = 0;
7826 if (offset + L2_SIZE > sizeof(bootstrap_data)) {
7827 panic("%s: out of memory for the bootstrap shadow map L2 entries",
7831 addr = (uintptr_t)&bootstrap_data[offset];
7837 * SAN L1 + L2 pages, maybe L3 entries later?
7839 static vm_offset_t __nosanitizeaddress
7840 pmap_san_enter_bootstrap_alloc_pages(int npages)
7842 static uint8_t bootstrap_data[SAN_BOOTSTRAP_SIZE] __aligned(PAGE_SIZE);
7843 static size_t offset = 0;
7846 if (offset + (npages * PAGE_SIZE) > sizeof(bootstrap_data)) {
7847 panic("%s: out of memory for the bootstrap shadow map",
7851 addr = (uintptr_t)&bootstrap_data[offset];
7852 offset += (npages * PAGE_SIZE);
7856 static void __nosanitizeaddress
7857 pmap_san_enter_bootstrap(void)
7859 vm_offset_t freemempos;
7862 freemempos = pmap_san_enter_bootstrap_alloc_pages(2);
7863 bs_state.freemempos = freemempos;
7864 bs_state.va = KASAN_MIN_ADDRESS;
7865 pmap_bootstrap_l1_table(&bs_state);
7866 pmap_san_early_l2 = bs_state.l2;
7870 pmap_san_enter_alloc_l3(void)
7874 m = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED |
7877 panic("%s: no memory to grow shadow map", __func__);
7882 pmap_san_enter_alloc_l2(void)
7884 return (vm_page_alloc_noobj_contig(VM_ALLOC_WIRED | VM_ALLOC_ZERO,
7885 Ln_ENTRIES, 0, ~0ul, L2_SIZE, 0, VM_MEMATTR_DEFAULT));
7888 void __nosanitizeaddress
7889 pmap_san_enter(vm_offset_t va)
7891 pd_entry_t *l1, *l2;
7895 if (virtual_avail == 0) {
7900 /* Temporary shadow map prior to pmap_bootstrap(). */
7901 first = pmap_san_early_l2 == NULL;
7903 pmap_san_enter_bootstrap();
7905 l2 = pmap_san_early_l2;
7906 slot = pmap_l2_index(va);
7908 if ((pmap_load(&l2[slot]) & ATTR_DESCR_VALID) == 0) {
7910 block = pmap_san_enter_bootstrap_alloc_l2();
7911 pmap_store(&l2[slot],
7912 PHYS_TO_PTE(pmap_early_vtophys(block)) |
7913 PMAP_SAN_PTE_BITS | L2_BLOCK);
7920 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
7921 l1 = pmap_l1(kernel_pmap, va);
7923 if ((pmap_load(l1) & ATTR_DESCR_VALID) == 0) {
7924 m = pmap_san_enter_alloc_l3();
7925 pmap_store(l1, PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) | L1_TABLE);
7927 l2 = pmap_l1_to_l2(l1, va);
7928 if ((pmap_load(l2) & ATTR_DESCR_VALID) == 0) {
7929 m = pmap_san_enter_alloc_l2();
7931 pmap_store(l2, PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) |
7932 PMAP_SAN_PTE_BITS | L2_BLOCK);
7934 m = pmap_san_enter_alloc_l3();
7935 pmap_store(l2, PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) |
7940 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK)
7942 l3 = pmap_l2_to_l3(l2, va);
7943 if ((pmap_load(l3) & ATTR_DESCR_VALID) != 0)
7945 m = pmap_san_enter_alloc_l3();
7946 pmap_store(l3, PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) |
7947 PMAP_SAN_PTE_BITS | L3_PAGE);
7953 * Track a range of the kernel's virtual address space that is contiguous
7954 * in various mapping attributes.
7956 struct pmap_kernel_map_range {
7966 sysctl_kmaps_dump(struct sbuf *sb, struct pmap_kernel_map_range *range,
7972 if (eva <= range->sva)
7975 index = range->attrs & ATTR_S1_IDX_MASK;
7977 case ATTR_S1_IDX(VM_MEMATTR_DEVICE_NP):
7980 case ATTR_S1_IDX(VM_MEMATTR_DEVICE):
7983 case ATTR_S1_IDX(VM_MEMATTR_UNCACHEABLE):
7986 case ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK):
7989 case ATTR_S1_IDX(VM_MEMATTR_WRITE_THROUGH):
7994 "%s: unknown memory type %x for range 0x%016lx-0x%016lx\n",
7995 __func__, index, range->sva, eva);
8000 sbuf_printf(sb, "0x%016lx-0x%016lx r%c%c%c%c %6s %d %d %d %d\n",
8002 (range->attrs & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP_RW ? 'w' : '-',
8003 (range->attrs & ATTR_S1_PXN) != 0 ? '-' : 'x',
8004 (range->attrs & ATTR_S1_UXN) != 0 ? '-' : 'X',
8005 (range->attrs & ATTR_S1_AP(ATTR_S1_AP_USER)) != 0 ? 'u' : 's',
8006 mode, range->l1blocks, range->l2blocks, range->l3contig,
8009 /* Reset to sentinel value. */
8010 range->sva = 0xfffffffffffffffful;
8014 * Determine whether the attributes specified by a page table entry match those
8015 * being tracked by the current range.
8018 sysctl_kmaps_match(struct pmap_kernel_map_range *range, pt_entry_t attrs)
8021 return (range->attrs == attrs);
8025 sysctl_kmaps_reinit(struct pmap_kernel_map_range *range, vm_offset_t va,
8029 memset(range, 0, sizeof(*range));
8031 range->attrs = attrs;
8034 /* Get the block/page attributes that correspond to the table attributes */
8036 sysctl_kmaps_table_attrs(pd_entry_t table)
8041 if ((table & TATTR_UXN_TABLE) != 0)
8042 attrs |= ATTR_S1_UXN;
8043 if ((table & TATTR_PXN_TABLE) != 0)
8044 attrs |= ATTR_S1_PXN;
8045 if ((table & TATTR_AP_TABLE_RO) != 0)
8046 attrs |= ATTR_S1_AP(ATTR_S1_AP_RO);
8051 /* Read the block/page attributes we care about */
8053 sysctl_kmaps_block_attrs(pt_entry_t block)
8055 return (block & (ATTR_S1_AP_MASK | ATTR_S1_XN | ATTR_S1_IDX_MASK));
8059 * Given a leaf PTE, derive the mapping's attributes. If they do not match
8060 * those of the current run, dump the address range and its attributes, and
8064 sysctl_kmaps_check(struct sbuf *sb, struct pmap_kernel_map_range *range,
8065 vm_offset_t va, pd_entry_t l0e, pd_entry_t l1e, pd_entry_t l2e,
8070 attrs = sysctl_kmaps_table_attrs(l0e);
8072 if ((l1e & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
8073 attrs |= sysctl_kmaps_block_attrs(l1e);
8076 attrs |= sysctl_kmaps_table_attrs(l1e);
8078 if ((l2e & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
8079 attrs |= sysctl_kmaps_block_attrs(l2e);
8082 attrs |= sysctl_kmaps_table_attrs(l2e);
8083 attrs |= sysctl_kmaps_block_attrs(l3e);
8086 if (range->sva > va || !sysctl_kmaps_match(range, attrs)) {
8087 sysctl_kmaps_dump(sb, range, va);
8088 sysctl_kmaps_reinit(range, va, attrs);
8093 sysctl_kmaps(SYSCTL_HANDLER_ARGS)
8095 struct pmap_kernel_map_range range;
8096 struct sbuf sbuf, *sb;
8097 pd_entry_t l0e, *l1, l1e, *l2, l2e;
8098 pt_entry_t *l3, l3e;
8101 int error, i, j, k, l;
8103 error = sysctl_wire_old_buffer(req, 0);
8107 sbuf_new_for_sysctl(sb, NULL, PAGE_SIZE, req);
8109 /* Sentinel value. */
8110 range.sva = 0xfffffffffffffffful;
8113 * Iterate over the kernel page tables without holding the kernel pmap
8114 * lock. Kernel page table pages are never freed, so at worst we will
8115 * observe inconsistencies in the output.
8117 for (sva = 0xffff000000000000ul, i = pmap_l0_index(sva); i < Ln_ENTRIES;
8119 if (i == pmap_l0_index(DMAP_MIN_ADDRESS))
8120 sbuf_printf(sb, "\nDirect map:\n");
8121 else if (i == pmap_l0_index(VM_MIN_KERNEL_ADDRESS))
8122 sbuf_printf(sb, "\nKernel map:\n");
8124 else if (i == pmap_l0_index(KASAN_MIN_ADDRESS))
8125 sbuf_printf(sb, "\nKASAN shadow map:\n");
8128 l0e = kernel_pmap->pm_l0[i];
8129 if ((l0e & ATTR_DESCR_VALID) == 0) {
8130 sysctl_kmaps_dump(sb, &range, sva);
8134 pa = PTE_TO_PHYS(l0e);
8135 l1 = (pd_entry_t *)PHYS_TO_DMAP(pa);
8137 for (j = pmap_l1_index(sva); j < Ln_ENTRIES; j++) {
8139 if ((l1e & ATTR_DESCR_VALID) == 0) {
8140 sysctl_kmaps_dump(sb, &range, sva);
8144 if ((l1e & ATTR_DESCR_MASK) == L1_BLOCK) {
8145 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
8146 sysctl_kmaps_check(sb, &range, sva, l0e, l1e,
8152 pa = PTE_TO_PHYS(l1e);
8153 l2 = (pd_entry_t *)PHYS_TO_DMAP(pa);
8155 for (k = pmap_l2_index(sva); k < Ln_ENTRIES; k++) {
8157 if ((l2e & ATTR_DESCR_VALID) == 0) {
8158 sysctl_kmaps_dump(sb, &range, sva);
8162 if ((l2e & ATTR_DESCR_MASK) == L2_BLOCK) {
8163 sysctl_kmaps_check(sb, &range, sva,
8169 pa = PTE_TO_PHYS(l2e);
8170 l3 = (pt_entry_t *)PHYS_TO_DMAP(pa);
8172 for (l = pmap_l3_index(sva); l < Ln_ENTRIES;
8173 l++, sva += L3_SIZE) {
8175 if ((l3e & ATTR_DESCR_VALID) == 0) {
8176 sysctl_kmaps_dump(sb, &range,
8180 sysctl_kmaps_check(sb, &range, sva,
8181 l0e, l1e, l2e, l3e);
8182 if ((l3e & ATTR_CONTIGUOUS) != 0)
8183 range.l3contig += l % 16 == 0 ?
8192 error = sbuf_finish(sb);
8196 SYSCTL_OID(_vm_pmap, OID_AUTO, kernel_maps,
8197 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
8198 NULL, 0, sysctl_kmaps, "A",
8199 "Dump kernel address layout");