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 * Routine: pmap_kextract
1955 * Extract the physical page address associated with the given kernel
1959 pmap_kextract(vm_offset_t va)
1963 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
1964 return (DMAP_TO_PHYS(va));
1966 if (pmap_klookup(va, &pa) == false)
1971 /***************************************************
1972 * Low level mapping routines.....
1973 ***************************************************/
1976 pmap_kenter(vm_offset_t sva, vm_size_t size, vm_paddr_t pa, int mode)
1979 pt_entry_t attr, old_l3e, *pte;
1983 KASSERT((pa & L3_OFFSET) == 0,
1984 ("pmap_kenter: Invalid physical address"));
1985 KASSERT((sva & L3_OFFSET) == 0,
1986 ("pmap_kenter: Invalid virtual address"));
1987 KASSERT((size & PAGE_MASK) == 0,
1988 ("pmap_kenter: Mapping is not page-sized"));
1990 attr = ATTR_DEFAULT | ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_S1_XN |
1991 ATTR_S1_IDX(mode) | L3_PAGE;
1995 pde = pmap_pde(kernel_pmap, va, &lvl);
1996 KASSERT(pde != NULL,
1997 ("pmap_kenter: Invalid page entry, va: 0x%lx", va));
1998 KASSERT(lvl == 2, ("pmap_kenter: Invalid level %d", lvl));
2000 pte = pmap_l2_to_l3(pde, va);
2001 old_l3e |= pmap_load_store(pte, PHYS_TO_PTE(pa) | attr);
2007 if ((old_l3e & ATTR_DESCR_VALID) != 0)
2008 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
2011 * Because the old entries were invalid and the new mappings
2012 * are not executable, an isb is not required.
2019 pmap_kenter_device(vm_offset_t sva, vm_size_t size, vm_paddr_t pa)
2022 pmap_kenter(sva, size, pa, VM_MEMATTR_DEVICE);
2026 * Remove a page from the kernel pagetables.
2029 pmap_kremove(vm_offset_t va)
2033 pte = pmap_pte_exists(kernel_pmap, va, 3, __func__);
2035 pmap_s1_invalidate_page(kernel_pmap, va, true);
2039 * Remove the specified range of mappings from the kernel address space.
2041 * Should only be applied to mappings that were created by pmap_kenter() or
2042 * pmap_kenter_device(). Nothing about this function is actually specific
2043 * to device mappings.
2046 pmap_kremove_device(vm_offset_t sva, vm_size_t size)
2051 KASSERT((sva & L3_OFFSET) == 0,
2052 ("pmap_kremove_device: Invalid virtual address"));
2053 KASSERT((size & PAGE_MASK) == 0,
2054 ("pmap_kremove_device: Mapping is not page-sized"));
2058 pte = pmap_pte_exists(kernel_pmap, va, 3, __func__);
2064 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
2068 * Used to map a range of physical addresses into kernel
2069 * virtual address space.
2071 * The value passed in '*virt' is a suggested virtual address for
2072 * the mapping. Architectures which can support a direct-mapped
2073 * physical to virtual region can return the appropriate address
2074 * within that region, leaving '*virt' unchanged. Other
2075 * architectures should map the pages starting at '*virt' and
2076 * update '*virt' with the first usable address after the mapped
2080 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2082 return PHYS_TO_DMAP(start);
2086 * Add a list of wired pages to the kva
2087 * this routine is only used for temporary
2088 * kernel mappings that do not need to have
2089 * page modification or references recorded.
2090 * Note that old mappings are simply written
2091 * over. The page *must* be wired.
2092 * Note: SMP coherent. Uses a ranged shootdown IPI.
2095 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2098 pt_entry_t attr, old_l3e, pa, *pte;
2105 for (i = 0; i < count; i++) {
2106 pde = pmap_pde(kernel_pmap, va, &lvl);
2107 KASSERT(pde != NULL,
2108 ("pmap_qenter: Invalid page entry, va: 0x%lx", va));
2110 ("pmap_qenter: Invalid level %d", lvl));
2113 pa = VM_PAGE_TO_PHYS(m);
2114 attr = ATTR_DEFAULT | ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_S1_XN |
2115 ATTR_S1_IDX(m->md.pv_memattr) | L3_PAGE;
2116 pte = pmap_l2_to_l3(pde, va);
2117 old_l3e |= pmap_load_store(pte, PHYS_TO_PTE(pa) | attr);
2121 if ((old_l3e & ATTR_DESCR_VALID) != 0)
2122 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
2125 * Because the old entries were invalid and the new mappings
2126 * are not executable, an isb is not required.
2133 * This routine tears out page mappings from the
2134 * kernel -- it is meant only for temporary mappings.
2137 pmap_qremove(vm_offset_t sva, int count)
2142 KASSERT(ADDR_IS_CANONICAL(sva),
2143 ("%s: Address not in canonical form: %lx", __func__, sva));
2144 KASSERT(ADDR_IS_KERNEL(sva), ("usermode va %lx", sva));
2147 while (count-- > 0) {
2148 pte = pmap_pte_exists(kernel_pmap, va, 3, NULL);
2155 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
2158 /***************************************************
2159 * Page table page management routines.....
2160 ***************************************************/
2162 * Schedule the specified unused page table page to be freed. Specifically,
2163 * add the page to the specified list of pages that will be released to the
2164 * physical memory manager after the TLB has been updated.
2166 static __inline void
2167 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2168 boolean_t set_PG_ZERO)
2172 m->flags |= PG_ZERO;
2174 m->flags &= ~PG_ZERO;
2175 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2179 * Decrements a page table page's reference count, which is used to record the
2180 * number of valid page table entries within the page. If the reference count
2181 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2182 * page table page was unmapped and FALSE otherwise.
2184 static inline boolean_t
2185 pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2189 if (m->ref_count == 0) {
2190 _pmap_unwire_l3(pmap, va, m, free);
2197 _pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2200 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2202 * unmap the page table page
2204 if (m->pindex >= (NUL2E + NUL1E)) {
2208 l0 = pmap_l0(pmap, va);
2210 } else if (m->pindex >= NUL2E) {
2214 l1 = pmap_l1(pmap, va);
2220 l2 = pmap_l2(pmap, va);
2223 pmap_resident_count_dec(pmap, 1);
2224 if (m->pindex < NUL2E) {
2225 /* We just released an l3, unhold the matching l2 */
2226 pd_entry_t *l1, tl1;
2229 l1 = pmap_l1(pmap, va);
2230 tl1 = pmap_load(l1);
2231 l2pg = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tl1));
2232 pmap_unwire_l3(pmap, va, l2pg, free);
2233 } else if (m->pindex < (NUL2E + NUL1E)) {
2234 /* We just released an l2, unhold the matching l1 */
2235 pd_entry_t *l0, tl0;
2238 l0 = pmap_l0(pmap, va);
2239 tl0 = pmap_load(l0);
2240 l1pg = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tl0));
2241 pmap_unwire_l3(pmap, va, l1pg, free);
2243 pmap_invalidate_page(pmap, va, false);
2246 * Put page on a list so that it is released after
2247 * *ALL* TLB shootdown is done
2249 pmap_add_delayed_free_list(m, free, TRUE);
2253 * After removing a page table entry, this routine is used to
2254 * conditionally free the page, and manage the reference count.
2257 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2258 struct spglist *free)
2262 KASSERT(ADDR_IS_CANONICAL(va),
2263 ("%s: Address not in canonical form: %lx", __func__, va));
2264 if (ADDR_IS_KERNEL(va))
2266 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2267 mpte = PHYS_TO_VM_PAGE(PTE_TO_PHYS(ptepde));
2268 return (pmap_unwire_l3(pmap, va, mpte, free));
2272 * Release a page table page reference after a failed attempt to create a
2276 pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
2278 struct spglist free;
2281 if (pmap_unwire_l3(pmap, va, mpte, &free))
2282 vm_page_free_pages_toq(&free, true);
2286 pmap_pinit0(pmap_t pmap)
2289 PMAP_LOCK_INIT(pmap);
2290 bzero(&pmap->pm_stats, sizeof(pmap->pm_stats));
2291 pmap->pm_l0_paddr = READ_SPECIALREG(ttbr0_el1);
2292 pmap->pm_l0 = (pd_entry_t *)PHYS_TO_DMAP(pmap->pm_l0_paddr);
2293 TAILQ_INIT(&pmap->pm_pvchunk);
2294 vm_radix_init(&pmap->pm_root);
2295 pmap->pm_cookie = COOKIE_FROM(ASID_RESERVED_FOR_PID_0, INT_MIN);
2296 pmap->pm_stage = PM_STAGE1;
2297 pmap->pm_levels = 4;
2298 pmap->pm_ttbr = pmap->pm_l0_paddr;
2299 pmap->pm_asid_set = &asids;
2301 PCPU_SET(curpmap, pmap);
2305 pmap_pinit_stage(pmap_t pmap, enum pmap_stage stage, int levels)
2310 * allocate the l0 page
2312 m = vm_page_alloc_noobj(VM_ALLOC_WAITOK | VM_ALLOC_WIRED |
2314 pmap->pm_l0_paddr = VM_PAGE_TO_PHYS(m);
2315 pmap->pm_l0 = (pd_entry_t *)PHYS_TO_DMAP(pmap->pm_l0_paddr);
2317 TAILQ_INIT(&pmap->pm_pvchunk);
2318 vm_radix_init(&pmap->pm_root);
2319 bzero(&pmap->pm_stats, sizeof(pmap->pm_stats));
2320 pmap->pm_cookie = COOKIE_FROM(-1, INT_MAX);
2322 MPASS(levels == 3 || levels == 4);
2323 pmap->pm_levels = levels;
2324 pmap->pm_stage = stage;
2327 pmap->pm_asid_set = &asids;
2330 pmap->pm_asid_set = &vmids;
2333 panic("%s: Invalid pmap type %d", __func__, stage);
2337 /* XXX Temporarily disable deferred ASID allocation. */
2338 pmap_alloc_asid(pmap);
2341 * Allocate the level 1 entry to use as the root. This will increase
2342 * the refcount on the level 1 page so it won't be removed until
2343 * pmap_release() is called.
2345 if (pmap->pm_levels == 3) {
2347 m = _pmap_alloc_l3(pmap, NUL2E + NUL1E, NULL);
2350 pmap->pm_ttbr = VM_PAGE_TO_PHYS(m);
2356 pmap_pinit(pmap_t pmap)
2359 return (pmap_pinit_stage(pmap, PM_STAGE1, 4));
2363 * This routine is called if the desired page table page does not exist.
2365 * If page table page allocation fails, this routine may sleep before
2366 * returning NULL. It sleeps only if a lock pointer was given.
2368 * Note: If a page allocation fails at page table level two or three,
2369 * one or two pages may be held during the wait, only to be released
2370 * afterwards. This conservative approach is easily argued to avoid
2374 _pmap_alloc_l3(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2376 vm_page_t m, l1pg, l2pg;
2378 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2381 * Allocate a page table page.
2383 if ((m = vm_page_alloc_noobj(VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2384 if (lockp != NULL) {
2385 RELEASE_PV_LIST_LOCK(lockp);
2392 * Indicate the need to retry. While waiting, the page table
2393 * page may have been allocated.
2397 m->pindex = ptepindex;
2400 * Because of AArch64's weak memory consistency model, we must have a
2401 * barrier here to ensure that the stores for zeroing "m", whether by
2402 * pmap_zero_page() or an earlier function, are visible before adding
2403 * "m" to the page table. Otherwise, a page table walk by another
2404 * processor's MMU could see the mapping to "m" and a stale, non-zero
2410 * Map the pagetable page into the process address space, if
2411 * it isn't already there.
2414 if (ptepindex >= (NUL2E + NUL1E)) {
2415 pd_entry_t *l0p, l0e;
2416 vm_pindex_t l0index;
2418 l0index = ptepindex - (NUL2E + NUL1E);
2419 l0p = &pmap->pm_l0[l0index];
2420 KASSERT((pmap_load(l0p) & ATTR_DESCR_VALID) == 0,
2421 ("%s: L0 entry %#lx is valid", __func__, pmap_load(l0p)));
2422 l0e = PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) | L0_TABLE;
2425 * Mark all kernel memory as not accessible from userspace
2426 * and userspace memory as not executable from the kernel.
2427 * This has been done for the bootstrap L0 entries in
2430 if (pmap == kernel_pmap)
2431 l0e |= TATTR_UXN_TABLE | TATTR_AP_TABLE_NO_EL0;
2433 l0e |= TATTR_PXN_TABLE;
2434 pmap_store(l0p, l0e);
2435 } else if (ptepindex >= NUL2E) {
2436 vm_pindex_t l0index, l1index;
2437 pd_entry_t *l0, *l1;
2440 l1index = ptepindex - NUL2E;
2441 l0index = l1index >> Ln_ENTRIES_SHIFT;
2443 l0 = &pmap->pm_l0[l0index];
2444 tl0 = pmap_load(l0);
2446 /* recurse for allocating page dir */
2447 if (_pmap_alloc_l3(pmap, NUL2E + NUL1E + l0index,
2449 vm_page_unwire_noq(m);
2450 vm_page_free_zero(m);
2454 l1pg = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tl0));
2458 l1 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(pmap_load(l0)));
2459 l1 = &l1[ptepindex & Ln_ADDR_MASK];
2460 KASSERT((pmap_load(l1) & ATTR_DESCR_VALID) == 0,
2461 ("%s: L1 entry %#lx is valid", __func__, pmap_load(l1)));
2462 pmap_store(l1, PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) | L1_TABLE);
2464 vm_pindex_t l0index, l1index;
2465 pd_entry_t *l0, *l1, *l2;
2466 pd_entry_t tl0, tl1;
2468 l1index = ptepindex >> Ln_ENTRIES_SHIFT;
2469 l0index = l1index >> Ln_ENTRIES_SHIFT;
2471 l0 = &pmap->pm_l0[l0index];
2472 tl0 = pmap_load(l0);
2474 /* recurse for allocating page dir */
2475 if (_pmap_alloc_l3(pmap, NUL2E + l1index,
2477 vm_page_unwire_noq(m);
2478 vm_page_free_zero(m);
2481 tl0 = pmap_load(l0);
2482 l1 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(tl0));
2483 l1 = &l1[l1index & Ln_ADDR_MASK];
2485 l1 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(tl0));
2486 l1 = &l1[l1index & Ln_ADDR_MASK];
2487 tl1 = pmap_load(l1);
2489 /* recurse for allocating page dir */
2490 if (_pmap_alloc_l3(pmap, NUL2E + l1index,
2492 vm_page_unwire_noq(m);
2493 vm_page_free_zero(m);
2497 l2pg = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tl1));
2502 l2 = (pd_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(pmap_load(l1)));
2503 l2 = &l2[ptepindex & Ln_ADDR_MASK];
2504 KASSERT((pmap_load(l2) & ATTR_DESCR_VALID) == 0,
2505 ("%s: L2 entry %#lx is valid", __func__, pmap_load(l2)));
2506 pmap_store(l2, PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) | L2_TABLE);
2509 pmap_resident_count_inc(pmap, 1);
2515 pmap_alloc_l2(pmap_t pmap, vm_offset_t va, vm_page_t *l2pgp,
2516 struct rwlock **lockp)
2518 pd_entry_t *l1, *l2;
2520 vm_pindex_t l2pindex;
2522 KASSERT(ADDR_IS_CANONICAL(va),
2523 ("%s: Address not in canonical form: %lx", __func__, va));
2526 l1 = pmap_l1(pmap, va);
2527 if (l1 != NULL && (pmap_load(l1) & ATTR_DESCR_MASK) == L1_TABLE) {
2528 l2 = pmap_l1_to_l2(l1, va);
2529 if (!ADDR_IS_KERNEL(va)) {
2530 /* Add a reference to the L2 page. */
2531 l2pg = PHYS_TO_VM_PAGE(PTE_TO_PHYS(pmap_load(l1)));
2535 } else if (!ADDR_IS_KERNEL(va)) {
2536 /* Allocate a L2 page. */
2537 l2pindex = pmap_l2_pindex(va) >> Ln_ENTRIES_SHIFT;
2538 l2pg = _pmap_alloc_l3(pmap, NUL2E + l2pindex, lockp);
2545 l2 = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(l2pg));
2546 l2 = &l2[pmap_l2_index(va)];
2548 panic("pmap_alloc_l2: missing page table page for va %#lx",
2555 pmap_alloc_l3(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2557 vm_pindex_t ptepindex;
2558 pd_entry_t *pde, tpde;
2566 * Calculate pagetable page index
2568 ptepindex = pmap_l2_pindex(va);
2571 * Get the page directory entry
2573 pde = pmap_pde(pmap, va, &lvl);
2576 * If the page table page is mapped, we just increment the hold count,
2577 * and activate it. If we get a level 2 pde it will point to a level 3
2585 pte = pmap_l0_to_l1(pde, va);
2586 KASSERT(pmap_load(pte) == 0,
2587 ("pmap_alloc_l3: TODO: l0 superpages"));
2592 pte = pmap_l1_to_l2(pde, va);
2593 KASSERT(pmap_load(pte) == 0,
2594 ("pmap_alloc_l3: TODO: l1 superpages"));
2598 tpde = pmap_load(pde);
2600 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tpde));
2606 panic("pmap_alloc_l3: Invalid level %d", lvl);
2610 * Here if the pte page isn't mapped, or if it has been deallocated.
2612 m = _pmap_alloc_l3(pmap, ptepindex, lockp);
2613 if (m == NULL && lockp != NULL)
2619 /***************************************************
2620 * Pmap allocation/deallocation routines.
2621 ***************************************************/
2624 * Release any resources held by the given physical map.
2625 * Called when a pmap initialized by pmap_pinit is being released.
2626 * Should only be called if the map contains no valid mappings.
2629 pmap_release(pmap_t pmap)
2631 boolean_t rv __diagused;
2632 struct spglist free;
2633 struct asid_set *set;
2637 if (pmap->pm_levels != 4) {
2638 PMAP_ASSERT_STAGE2(pmap);
2639 KASSERT(pmap->pm_stats.resident_count == 1,
2640 ("pmap_release: pmap resident count %ld != 0",
2641 pmap->pm_stats.resident_count));
2642 KASSERT((pmap->pm_l0[0] & ATTR_DESCR_VALID) == ATTR_DESCR_VALID,
2643 ("pmap_release: Invalid l0 entry: %lx", pmap->pm_l0[0]));
2646 m = PHYS_TO_VM_PAGE(pmap->pm_ttbr);
2648 rv = pmap_unwire_l3(pmap, 0, m, &free);
2651 vm_page_free_pages_toq(&free, true);
2654 KASSERT(pmap->pm_stats.resident_count == 0,
2655 ("pmap_release: pmap resident count %ld != 0",
2656 pmap->pm_stats.resident_count));
2657 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2658 ("pmap_release: pmap has reserved page table page(s)"));
2660 set = pmap->pm_asid_set;
2661 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
2664 * Allow the ASID to be reused. In stage 2 VMIDs we don't invalidate
2665 * the entries when removing them so rely on a later tlb invalidation.
2666 * this will happen when updating the VMID generation. Because of this
2667 * we don't reuse VMIDs within a generation.
2669 if (pmap->pm_stage == PM_STAGE1) {
2670 mtx_lock_spin(&set->asid_set_mutex);
2671 if (COOKIE_TO_EPOCH(pmap->pm_cookie) == set->asid_epoch) {
2672 asid = COOKIE_TO_ASID(pmap->pm_cookie);
2673 KASSERT(asid >= ASID_FIRST_AVAILABLE &&
2674 asid < set->asid_set_size,
2675 ("pmap_release: pmap cookie has out-of-range asid"));
2676 bit_clear(set->asid_set, asid);
2678 mtx_unlock_spin(&set->asid_set_mutex);
2681 m = PHYS_TO_VM_PAGE(pmap->pm_l0_paddr);
2682 vm_page_unwire_noq(m);
2683 vm_page_free_zero(m);
2687 kvm_size(SYSCTL_HANDLER_ARGS)
2689 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2691 return sysctl_handle_long(oidp, &ksize, 0, req);
2693 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
2694 0, 0, kvm_size, "LU",
2698 kvm_free(SYSCTL_HANDLER_ARGS)
2700 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2702 return sysctl_handle_long(oidp, &kfree, 0, req);
2704 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
2705 0, 0, kvm_free, "LU",
2706 "Amount of KVM free");
2709 * grow the number of kernel page table entries, if needed
2712 pmap_growkernel(vm_offset_t addr)
2716 pd_entry_t *l0, *l1, *l2;
2718 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2720 addr = roundup2(addr, L2_SIZE);
2721 if (addr - 1 >= vm_map_max(kernel_map))
2722 addr = vm_map_max(kernel_map);
2723 if (kernel_vm_end < addr)
2724 kasan_shadow_map(kernel_vm_end, addr - kernel_vm_end);
2725 while (kernel_vm_end < addr) {
2726 l0 = pmap_l0(kernel_pmap, kernel_vm_end);
2727 KASSERT(pmap_load(l0) != 0,
2728 ("pmap_growkernel: No level 0 kernel entry"));
2730 l1 = pmap_l0_to_l1(l0, kernel_vm_end);
2731 if (pmap_load(l1) == 0) {
2732 /* We need a new PDP entry */
2733 nkpg = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT |
2734 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2736 panic("pmap_growkernel: no memory to grow kernel");
2737 nkpg->pindex = kernel_vm_end >> L1_SHIFT;
2738 /* See the dmb() in _pmap_alloc_l3(). */
2740 paddr = VM_PAGE_TO_PHYS(nkpg);
2741 pmap_store(l1, PHYS_TO_PTE(paddr) | L1_TABLE);
2742 continue; /* try again */
2744 l2 = pmap_l1_to_l2(l1, kernel_vm_end);
2745 if (pmap_load(l2) != 0) {
2746 kernel_vm_end = (kernel_vm_end + L2_SIZE) & ~L2_OFFSET;
2747 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
2748 kernel_vm_end = vm_map_max(kernel_map);
2754 nkpg = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED |
2757 panic("pmap_growkernel: no memory to grow kernel");
2758 nkpg->pindex = kernel_vm_end >> L2_SHIFT;
2759 /* See the dmb() in _pmap_alloc_l3(). */
2761 paddr = VM_PAGE_TO_PHYS(nkpg);
2762 pmap_store(l2, PHYS_TO_PTE(paddr) | L2_TABLE);
2764 kernel_vm_end = (kernel_vm_end + L2_SIZE) & ~L2_OFFSET;
2765 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
2766 kernel_vm_end = vm_map_max(kernel_map);
2772 /***************************************************
2773 * page management routines.
2774 ***************************************************/
2776 static const uint64_t pc_freemask[_NPCM] = {
2777 [0 ... _NPCM - 2] = PC_FREEN,
2778 [_NPCM - 1] = PC_FREEL
2782 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2784 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2785 "Current number of pv entry chunks");
2786 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2787 "Current number of pv entry chunks allocated");
2788 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2789 "Current number of pv entry chunks frees");
2790 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
2791 "Number of times tried to get a chunk page but failed.");
2793 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
2794 static int pv_entry_spare;
2796 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2797 "Current number of pv entry frees");
2798 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
2799 "Current number of pv entry allocs");
2800 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2801 "Current number of pv entries");
2802 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2803 "Current number of spare pv entries");
2807 * We are in a serious low memory condition. Resort to
2808 * drastic measures to free some pages so we can allocate
2809 * another pv entry chunk.
2811 * Returns NULL if PV entries were reclaimed from the specified pmap.
2813 * We do not, however, unmap 2mpages because subsequent accesses will
2814 * allocate per-page pv entries until repromotion occurs, thereby
2815 * exacerbating the shortage of free pv entries.
2818 reclaim_pv_chunk_domain(pmap_t locked_pmap, struct rwlock **lockp, int domain)
2820 struct pv_chunks_list *pvc;
2821 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
2822 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
2823 struct md_page *pvh;
2825 pmap_t next_pmap, pmap;
2826 pt_entry_t *pte, tpte;
2830 struct spglist free;
2832 int bit, field, freed, lvl;
2834 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2835 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
2840 bzero(&pc_marker_b, sizeof(pc_marker_b));
2841 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
2842 pc_marker = (struct pv_chunk *)&pc_marker_b;
2843 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
2845 pvc = &pv_chunks[domain];
2846 mtx_lock(&pvc->pvc_lock);
2847 pvc->active_reclaims++;
2848 TAILQ_INSERT_HEAD(&pvc->pvc_list, pc_marker, pc_lru);
2849 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc_marker_end, pc_lru);
2850 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
2851 SLIST_EMPTY(&free)) {
2852 next_pmap = pc->pc_pmap;
2853 if (next_pmap == NULL) {
2855 * The next chunk is a marker. However, it is
2856 * not our marker, so active_reclaims must be
2857 * > 1. Consequently, the next_chunk code
2858 * will not rotate the pv_chunks list.
2862 mtx_unlock(&pvc->pvc_lock);
2865 * A pv_chunk can only be removed from the pc_lru list
2866 * when both pvc->pvc_lock is owned and the
2867 * corresponding pmap is locked.
2869 if (pmap != next_pmap) {
2870 if (pmap != NULL && pmap != locked_pmap)
2873 /* Avoid deadlock and lock recursion. */
2874 if (pmap > locked_pmap) {
2875 RELEASE_PV_LIST_LOCK(lockp);
2877 mtx_lock(&pvc->pvc_lock);
2879 } else if (pmap != locked_pmap) {
2880 if (PMAP_TRYLOCK(pmap)) {
2881 mtx_lock(&pvc->pvc_lock);
2884 pmap = NULL; /* pmap is not locked */
2885 mtx_lock(&pvc->pvc_lock);
2886 pc = TAILQ_NEXT(pc_marker, pc_lru);
2888 pc->pc_pmap != next_pmap)
2896 * Destroy every non-wired, 4 KB page mapping in the chunk.
2899 for (field = 0; field < _NPCM; field++) {
2900 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2901 inuse != 0; inuse &= ~(1UL << bit)) {
2902 bit = ffsl(inuse) - 1;
2903 pv = &pc->pc_pventry[field * 64 + bit];
2905 pde = pmap_pde(pmap, va, &lvl);
2908 pte = pmap_l2_to_l3(pde, va);
2909 tpte = pmap_load(pte);
2910 if ((tpte & ATTR_SW_WIRED) != 0)
2912 tpte = pmap_load_clear(pte);
2913 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(tpte));
2914 if (pmap_pte_dirty(pmap, tpte))
2916 if ((tpte & ATTR_AF) != 0) {
2917 pmap_s1_invalidate_page(pmap, va, true);
2918 vm_page_aflag_set(m, PGA_REFERENCED);
2920 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
2921 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
2923 if (TAILQ_EMPTY(&m->md.pv_list) &&
2924 (m->flags & PG_FICTITIOUS) == 0) {
2925 pvh = page_to_pvh(m);
2926 if (TAILQ_EMPTY(&pvh->pv_list)) {
2927 vm_page_aflag_clear(m,
2931 pc->pc_map[field] |= 1UL << bit;
2932 pmap_unuse_pt(pmap, va, pmap_load(pde), &free);
2937 mtx_lock(&pvc->pvc_lock);
2940 /* Every freed mapping is for a 4 KB page. */
2941 pmap_resident_count_dec(pmap, freed);
2942 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
2943 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
2944 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
2945 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2946 if (pc_is_free(pc)) {
2947 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
2948 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
2949 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
2950 /* Entire chunk is free; return it. */
2951 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
2952 dump_drop_page(m_pc->phys_addr);
2953 mtx_lock(&pvc->pvc_lock);
2954 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
2957 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2958 mtx_lock(&pvc->pvc_lock);
2959 /* One freed pv entry in locked_pmap is sufficient. */
2960 if (pmap == locked_pmap)
2964 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
2965 TAILQ_INSERT_AFTER(&pvc->pvc_list, pc, pc_marker, pc_lru);
2966 if (pvc->active_reclaims == 1 && pmap != NULL) {
2968 * Rotate the pv chunks list so that we do not
2969 * scan the same pv chunks that could not be
2970 * freed (because they contained a wired
2971 * and/or superpage mapping) on every
2972 * invocation of reclaim_pv_chunk().
2974 while ((pc = TAILQ_FIRST(&pvc->pvc_list)) != pc_marker){
2975 MPASS(pc->pc_pmap != NULL);
2976 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
2977 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
2981 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
2982 TAILQ_REMOVE(&pvc->pvc_list, pc_marker_end, pc_lru);
2983 pvc->active_reclaims--;
2984 mtx_unlock(&pvc->pvc_lock);
2985 if (pmap != NULL && pmap != locked_pmap)
2987 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
2988 m_pc = SLIST_FIRST(&free);
2989 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2990 /* Recycle a freed page table page. */
2991 m_pc->ref_count = 1;
2993 vm_page_free_pages_toq(&free, true);
2998 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
3003 domain = PCPU_GET(domain);
3004 for (i = 0; i < vm_ndomains; i++) {
3005 m = reclaim_pv_chunk_domain(locked_pmap, lockp, domain);
3008 domain = (domain + 1) % vm_ndomains;
3015 * free the pv_entry back to the free list
3018 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3020 struct pv_chunk *pc;
3021 int idx, field, bit;
3023 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3024 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3025 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3026 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3027 pc = pv_to_chunk(pv);
3028 idx = pv - &pc->pc_pventry[0];
3031 pc->pc_map[field] |= 1ul << bit;
3032 if (!pc_is_free(pc)) {
3033 /* 98% of the time, pc is already at the head of the list. */
3034 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3035 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3036 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3040 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3045 free_pv_chunk_dequeued(struct pv_chunk *pc)
3049 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3050 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3051 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3052 /* entire chunk is free, return it */
3053 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3054 dump_drop_page(m->phys_addr);
3055 vm_page_unwire_noq(m);
3060 free_pv_chunk(struct pv_chunk *pc)
3062 struct pv_chunks_list *pvc;
3064 pvc = &pv_chunks[pc_to_domain(pc)];
3065 mtx_lock(&pvc->pvc_lock);
3066 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
3067 mtx_unlock(&pvc->pvc_lock);
3068 free_pv_chunk_dequeued(pc);
3072 free_pv_chunk_batch(struct pv_chunklist *batch)
3074 struct pv_chunks_list *pvc;
3075 struct pv_chunk *pc, *npc;
3078 for (i = 0; i < vm_ndomains; i++) {
3079 if (TAILQ_EMPTY(&batch[i]))
3081 pvc = &pv_chunks[i];
3082 mtx_lock(&pvc->pvc_lock);
3083 TAILQ_FOREACH(pc, &batch[i], pc_list) {
3084 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
3086 mtx_unlock(&pvc->pvc_lock);
3089 for (i = 0; i < vm_ndomains; i++) {
3090 TAILQ_FOREACH_SAFE(pc, &batch[i], pc_list, npc) {
3091 free_pv_chunk_dequeued(pc);
3097 * Returns a new PV entry, allocating a new PV chunk from the system when
3098 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3099 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3102 * The given PV list lock may be released.
3105 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3107 struct pv_chunks_list *pvc;
3110 struct pv_chunk *pc;
3113 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3114 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3116 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3118 for (field = 0; field < _NPCM; field++) {
3119 if (pc->pc_map[field]) {
3120 bit = ffsl(pc->pc_map[field]) - 1;
3124 if (field < _NPCM) {
3125 pv = &pc->pc_pventry[field * 64 + bit];
3126 pc->pc_map[field] &= ~(1ul << bit);
3127 /* If this was the last item, move it to tail */
3128 if (pc_is_full(pc)) {
3129 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3130 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3133 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3134 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3138 /* No free items, allocate another chunk */
3139 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
3141 if (lockp == NULL) {
3142 PV_STAT(pc_chunk_tryfail++);
3145 m = reclaim_pv_chunk(pmap, lockp);
3149 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3150 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3151 dump_add_page(m->phys_addr);
3152 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3154 memcpy(pc->pc_map, pc_freemask, sizeof(pc_freemask));
3155 pc->pc_map[0] &= ~1ul; /* preallocated bit 0 */
3156 pvc = &pv_chunks[vm_page_domain(m)];
3157 mtx_lock(&pvc->pvc_lock);
3158 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
3159 mtx_unlock(&pvc->pvc_lock);
3160 pv = &pc->pc_pventry[0];
3161 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3162 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3163 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3168 * Ensure that the number of spare PV entries in the specified pmap meets or
3169 * exceeds the given count, "needed".
3171 * The given PV list lock may be released.
3174 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3176 struct pv_chunks_list *pvc;
3177 struct pch new_tail[PMAP_MEMDOM];
3178 struct pv_chunk *pc;
3183 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3184 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3187 * Newly allocated PV chunks must be stored in a private list until
3188 * the required number of PV chunks have been allocated. Otherwise,
3189 * reclaim_pv_chunk() could recycle one of these chunks. In
3190 * contrast, these chunks must be added to the pmap upon allocation.
3192 for (i = 0; i < PMAP_MEMDOM; i++)
3193 TAILQ_INIT(&new_tail[i]);
3196 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3197 bit_count((bitstr_t *)pc->pc_map, 0,
3198 sizeof(pc->pc_map) * NBBY, &free);
3202 if (avail >= needed)
3205 for (reclaimed = false; avail < needed; avail += _NPCPV) {
3206 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
3208 m = reclaim_pv_chunk(pmap, lockp);
3213 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3214 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3215 dump_add_page(m->phys_addr);
3216 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3218 memcpy(pc->pc_map, pc_freemask, sizeof(pc_freemask));
3219 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3220 TAILQ_INSERT_TAIL(&new_tail[vm_page_domain(m)], pc, pc_lru);
3221 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3224 * The reclaim might have freed a chunk from the current pmap.
3225 * If that chunk contained available entries, we need to
3226 * re-count the number of available entries.
3231 for (i = 0; i < vm_ndomains; i++) {
3232 if (TAILQ_EMPTY(&new_tail[i]))
3234 pvc = &pv_chunks[i];
3235 mtx_lock(&pvc->pvc_lock);
3236 TAILQ_CONCAT(&pvc->pvc_list, &new_tail[i], pc_lru);
3237 mtx_unlock(&pvc->pvc_lock);
3242 * First find and then remove the pv entry for the specified pmap and virtual
3243 * address from the specified pv list. Returns the pv entry if found and NULL
3244 * otherwise. This operation can be performed on pv lists for either 4KB or
3245 * 2MB page mappings.
3247 static __inline pv_entry_t
3248 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3252 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3253 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3254 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3263 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3264 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3265 * entries for each of the 4KB page mappings.
3268 pmap_pv_demote_l2(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3269 struct rwlock **lockp)
3271 struct md_page *pvh;
3272 struct pv_chunk *pc;
3274 vm_offset_t va_last;
3278 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3279 KASSERT((va & L2_OFFSET) == 0,
3280 ("pmap_pv_demote_l2: va is not 2mpage aligned"));
3281 KASSERT((pa & L2_OFFSET) == 0,
3282 ("pmap_pv_demote_l2: pa is not 2mpage aligned"));
3283 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3286 * Transfer the 2mpage's pv entry for this mapping to the first
3287 * page's pv list. Once this transfer begins, the pv list lock
3288 * must not be released until the last pv entry is reinstantiated.
3290 pvh = pa_to_pvh(pa);
3291 pv = pmap_pvh_remove(pvh, pmap, va);
3292 KASSERT(pv != NULL, ("pmap_pv_demote_l2: pv not found"));
3293 m = PHYS_TO_VM_PAGE(pa);
3294 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3296 /* Instantiate the remaining Ln_ENTRIES - 1 pv entries. */
3297 PV_STAT(atomic_add_long(&pv_entry_allocs, Ln_ENTRIES - 1));
3298 va_last = va + L2_SIZE - PAGE_SIZE;
3300 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3301 KASSERT(!pc_is_full(pc), ("pmap_pv_demote_l2: missing spare"));
3302 for (field = 0; field < _NPCM; field++) {
3303 while (pc->pc_map[field]) {
3304 bit = ffsl(pc->pc_map[field]) - 1;
3305 pc->pc_map[field] &= ~(1ul << bit);
3306 pv = &pc->pc_pventry[field * 64 + bit];
3310 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3311 ("pmap_pv_demote_l2: page %p is not managed", m));
3312 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3318 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3319 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3322 if (pc_is_full(pc)) {
3323 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3324 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3326 PV_STAT(atomic_add_long(&pv_entry_count, Ln_ENTRIES - 1));
3327 PV_STAT(atomic_subtract_int(&pv_entry_spare, Ln_ENTRIES - 1));
3331 * First find and then destroy the pv entry for the specified pmap and virtual
3332 * address. This operation can be performed on pv lists for either 4KB or 2MB
3336 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3340 pv = pmap_pvh_remove(pvh, pmap, va);
3341 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3342 free_pv_entry(pmap, pv);
3346 * Conditionally create the PV entry for a 4KB page mapping if the required
3347 * memory can be allocated without resorting to reclamation.
3350 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3351 struct rwlock **lockp)
3355 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3356 /* Pass NULL instead of the lock pointer to disable reclamation. */
3357 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3359 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3360 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3368 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3369 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3370 * false if the PV entry cannot be allocated without resorting to reclamation.
3373 pmap_pv_insert_l2(pmap_t pmap, vm_offset_t va, pd_entry_t l2e, u_int flags,
3374 struct rwlock **lockp)
3376 struct md_page *pvh;
3380 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3381 /* Pass NULL instead of the lock pointer to disable reclamation. */
3382 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3383 NULL : lockp)) == NULL)
3386 pa = PTE_TO_PHYS(l2e);
3387 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3388 pvh = pa_to_pvh(pa);
3389 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3395 pmap_remove_kernel_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va)
3397 pt_entry_t newl2, oldl2 __diagused;
3401 KASSERT(!VIRT_IN_DMAP(va), ("removing direct mapping of %#lx", va));
3402 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3403 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3405 ml3 = pmap_remove_pt_page(pmap, va);
3407 panic("pmap_remove_kernel_l2: Missing pt page");
3409 ml3pa = VM_PAGE_TO_PHYS(ml3);
3410 newl2 = PHYS_TO_PTE(ml3pa) | L2_TABLE;
3413 * If this page table page was unmapped by a promotion, then it
3414 * contains valid mappings. Zero it to invalidate those mappings.
3416 if (vm_page_any_valid(ml3))
3417 pagezero((void *)PHYS_TO_DMAP(ml3pa));
3420 * Demote the mapping. The caller must have already invalidated the
3421 * mapping (i.e., the "break" in break-before-make).
3423 oldl2 = pmap_load_store(l2, newl2);
3424 KASSERT(oldl2 == 0, ("%s: found existing mapping at %p: %#lx",
3425 __func__, l2, oldl2));
3429 * pmap_remove_l2: Do the things to unmap a level 2 superpage.
3432 pmap_remove_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva,
3433 pd_entry_t l1e, struct spglist *free, struct rwlock **lockp)
3435 struct md_page *pvh;
3437 vm_page_t m, ml3, mt;
3439 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3440 KASSERT((sva & L2_OFFSET) == 0, ("pmap_remove_l2: sva is not aligned"));
3441 old_l2 = pmap_load_clear(l2);
3442 KASSERT((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK,
3443 ("pmap_remove_l2: L2e %lx is not a block mapping", old_l2));
3446 * Since a promotion must break the 4KB page mappings before making
3447 * the 2MB page mapping, a pmap_s1_invalidate_page() suffices.
3449 pmap_s1_invalidate_page(pmap, sva, true);
3451 if (old_l2 & ATTR_SW_WIRED)
3452 pmap->pm_stats.wired_count -= L2_SIZE / PAGE_SIZE;
3453 pmap_resident_count_dec(pmap, L2_SIZE / PAGE_SIZE);
3454 if (old_l2 & ATTR_SW_MANAGED) {
3455 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(old_l2));
3456 pvh = page_to_pvh(m);
3457 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3458 pmap_pvh_free(pvh, pmap, sva);
3459 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++) {
3460 if (pmap_pte_dirty(pmap, old_l2))
3462 if (old_l2 & ATTR_AF)
3463 vm_page_aflag_set(mt, PGA_REFERENCED);
3464 if (TAILQ_EMPTY(&mt->md.pv_list) &&
3465 TAILQ_EMPTY(&pvh->pv_list))
3466 vm_page_aflag_clear(mt, PGA_WRITEABLE);
3469 if (pmap == kernel_pmap) {
3470 pmap_remove_kernel_l2(pmap, l2, sva);
3472 ml3 = pmap_remove_pt_page(pmap, sva);
3474 KASSERT(vm_page_any_valid(ml3),
3475 ("pmap_remove_l2: l3 page not promoted"));
3476 pmap_resident_count_dec(pmap, 1);
3477 KASSERT(ml3->ref_count == NL3PG,
3478 ("pmap_remove_l2: l3 page ref count error"));
3480 pmap_add_delayed_free_list(ml3, free, FALSE);
3483 return (pmap_unuse_pt(pmap, sva, l1e, free));
3487 * pmap_remove_l3: do the things to unmap a page in a process
3490 pmap_remove_l3(pmap_t pmap, pt_entry_t *l3, vm_offset_t va,
3491 pd_entry_t l2e, struct spglist *free, struct rwlock **lockp)
3493 struct md_page *pvh;
3497 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3498 old_l3 = pmap_load_clear(l3);
3499 pmap_s1_invalidate_page(pmap, va, true);
3500 if (old_l3 & ATTR_SW_WIRED)
3501 pmap->pm_stats.wired_count -= 1;
3502 pmap_resident_count_dec(pmap, 1);
3503 if (old_l3 & ATTR_SW_MANAGED) {
3504 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(old_l3));
3505 if (pmap_pte_dirty(pmap, old_l3))
3507 if (old_l3 & ATTR_AF)
3508 vm_page_aflag_set(m, PGA_REFERENCED);
3509 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3510 pmap_pvh_free(&m->md, pmap, va);
3511 if (TAILQ_EMPTY(&m->md.pv_list) &&
3512 (m->flags & PG_FICTITIOUS) == 0) {
3513 pvh = page_to_pvh(m);
3514 if (TAILQ_EMPTY(&pvh->pv_list))
3515 vm_page_aflag_clear(m, PGA_WRITEABLE);
3518 return (pmap_unuse_pt(pmap, va, l2e, free));
3522 * Remove the specified range of addresses from the L3 page table that is
3523 * identified by the given L2 entry.
3526 pmap_remove_l3_range(pmap_t pmap, pd_entry_t l2e, vm_offset_t sva,
3527 vm_offset_t eva, struct spglist *free, struct rwlock **lockp)
3529 struct md_page *pvh;
3530 struct rwlock *new_lock;
3531 pt_entry_t *l3, old_l3;
3535 KASSERT(ADDR_IS_CANONICAL(sva),
3536 ("%s: Start address not in canonical form: %lx", __func__, sva));
3537 KASSERT(ADDR_IS_CANONICAL(eva) || eva == VM_MAX_USER_ADDRESS,
3538 ("%s: End address not in canonical form: %lx", __func__, eva));
3540 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3541 KASSERT(rounddown2(sva, L2_SIZE) + L2_SIZE == roundup2(eva, L2_SIZE),
3542 ("pmap_remove_l3_range: range crosses an L3 page table boundary"));
3543 l3pg = !ADDR_IS_KERNEL(sva) ? PHYS_TO_VM_PAGE(PTE_TO_PHYS(l2e)) : NULL;
3545 for (l3 = pmap_l2_to_l3(&l2e, sva); sva != eva; l3++, sva += L3_SIZE) {
3546 if (!pmap_l3_valid(pmap_load(l3))) {
3548 pmap_invalidate_range(pmap, va, sva, true);
3553 old_l3 = pmap_load_clear(l3);
3554 if ((old_l3 & ATTR_SW_WIRED) != 0)
3555 pmap->pm_stats.wired_count--;
3556 pmap_resident_count_dec(pmap, 1);
3557 if ((old_l3 & ATTR_SW_MANAGED) != 0) {
3558 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(old_l3));
3559 if (pmap_pte_dirty(pmap, old_l3))
3561 if ((old_l3 & ATTR_AF) != 0)
3562 vm_page_aflag_set(m, PGA_REFERENCED);
3563 new_lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3564 if (new_lock != *lockp) {
3565 if (*lockp != NULL) {
3567 * Pending TLB invalidations must be
3568 * performed before the PV list lock is
3569 * released. Otherwise, a concurrent
3570 * pmap_remove_all() on a physical page
3571 * could return while a stale TLB entry
3572 * still provides access to that page.
3575 pmap_invalidate_range(pmap, va,
3584 pmap_pvh_free(&m->md, pmap, sva);
3585 if (TAILQ_EMPTY(&m->md.pv_list) &&
3586 (m->flags & PG_FICTITIOUS) == 0) {
3587 pvh = page_to_pvh(m);
3588 if (TAILQ_EMPTY(&pvh->pv_list))
3589 vm_page_aflag_clear(m, PGA_WRITEABLE);
3592 if (l3pg != NULL && pmap_unwire_l3(pmap, sva, l3pg, free)) {
3594 * _pmap_unwire_l3() has already invalidated the TLB
3595 * entries at all levels for "sva". So, we need not
3596 * perform "sva += L3_SIZE;" here. Moreover, we need
3597 * not perform "va = sva;" if "sva" is at the start
3598 * of a new valid range consisting of a single page.
3606 pmap_invalidate_range(pmap, va, sva, true);
3610 * Remove the given range of addresses from the specified map.
3612 * It is assumed that the start and end are properly
3613 * rounded to the page size.
3616 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3618 struct rwlock *lock;
3619 vm_offset_t va_next;
3620 pd_entry_t *l0, *l1, *l2;
3621 pt_entry_t l3_paddr;
3622 struct spglist free;
3625 * Perform an unsynchronized read. This is, however, safe.
3627 if (pmap->pm_stats.resident_count == 0)
3635 for (; sva < eva; sva = va_next) {
3636 if (pmap->pm_stats.resident_count == 0)
3639 l0 = pmap_l0(pmap, sva);
3640 if (pmap_load(l0) == 0) {
3641 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
3647 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
3650 l1 = pmap_l0_to_l1(l0, sva);
3651 if (pmap_load(l1) == 0)
3653 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
3654 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
3655 KASSERT(va_next <= eva,
3656 ("partial update of non-transparent 1G page "
3657 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
3658 pmap_load(l1), sva, eva, va_next));
3659 MPASS(pmap != kernel_pmap);
3660 MPASS((pmap_load(l1) & ATTR_SW_MANAGED) == 0);
3662 pmap_s1_invalidate_page(pmap, sva, true);
3663 pmap_resident_count_dec(pmap, L1_SIZE / PAGE_SIZE);
3664 pmap_unuse_pt(pmap, sva, pmap_load(l0), &free);
3669 * Calculate index for next page table.
3671 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
3675 l2 = pmap_l1_to_l2(l1, sva);
3679 l3_paddr = pmap_load(l2);
3681 if ((l3_paddr & ATTR_DESCR_MASK) == L2_BLOCK) {
3682 if (sva + L2_SIZE == va_next && eva >= va_next) {
3683 pmap_remove_l2(pmap, l2, sva, pmap_load(l1),
3686 } else if (pmap_demote_l2_locked(pmap, l2, sva,
3689 l3_paddr = pmap_load(l2);
3693 * Weed out invalid mappings.
3695 if ((l3_paddr & ATTR_DESCR_MASK) != L2_TABLE)
3699 * Limit our scan to either the end of the va represented
3700 * by the current page table page, or to the end of the
3701 * range being removed.
3706 pmap_remove_l3_range(pmap, l3_paddr, sva, va_next, &free,
3712 vm_page_free_pages_toq(&free, true);
3716 * Remove the given range of addresses as part of a logical unmap
3717 * operation. This has the effect of calling pmap_remove(), but
3718 * also clears any metadata that should persist for the lifetime
3719 * of a logical mapping.
3722 pmap_map_delete(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3724 pmap_remove(pmap, sva, eva);
3728 * Routine: pmap_remove_all
3730 * Removes this physical page from
3731 * all physical maps in which it resides.
3732 * Reflects back modify bits to the pager.
3735 * Original versions of this routine were very
3736 * inefficient because they iteratively called
3737 * pmap_remove (slow...)
3741 pmap_remove_all(vm_page_t m)
3743 struct md_page *pvh;
3746 struct rwlock *lock;
3747 pd_entry_t *pde, tpde;
3748 pt_entry_t *pte, tpte;
3750 struct spglist free;
3751 int lvl, pvh_gen, md_gen;
3753 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3754 ("pmap_remove_all: page %p is not managed", m));
3756 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3757 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
3760 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
3762 if (!PMAP_TRYLOCK(pmap)) {
3763 pvh_gen = pvh->pv_gen;
3767 if (pvh_gen != pvh->pv_gen) {
3773 pte = pmap_pte_exists(pmap, va, 2, __func__);
3774 pmap_demote_l2_locked(pmap, pte, va, &lock);
3777 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3779 if (!PMAP_TRYLOCK(pmap)) {
3780 pvh_gen = pvh->pv_gen;
3781 md_gen = m->md.pv_gen;
3785 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
3790 pmap_resident_count_dec(pmap, 1);
3792 pde = pmap_pde(pmap, pv->pv_va, &lvl);
3793 KASSERT(pde != NULL,
3794 ("pmap_remove_all: no page directory entry found"));
3796 ("pmap_remove_all: invalid pde level %d", lvl));
3797 tpde = pmap_load(pde);
3799 pte = pmap_l2_to_l3(pde, pv->pv_va);
3800 tpte = pmap_load_clear(pte);
3801 if (tpte & ATTR_SW_WIRED)
3802 pmap->pm_stats.wired_count--;
3803 if ((tpte & ATTR_AF) != 0) {
3804 pmap_invalidate_page(pmap, pv->pv_va, true);
3805 vm_page_aflag_set(m, PGA_REFERENCED);
3809 * Update the vm_page_t clean and reference bits.
3811 if (pmap_pte_dirty(pmap, tpte))
3813 pmap_unuse_pt(pmap, pv->pv_va, tpde, &free);
3814 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3816 free_pv_entry(pmap, pv);
3819 vm_page_aflag_clear(m, PGA_WRITEABLE);
3821 vm_page_free_pages_toq(&free, true);
3825 * Masks and sets bits in a level 2 page table entries in the specified pmap
3828 pmap_protect_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva, pt_entry_t mask,
3834 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3835 PMAP_ASSERT_STAGE1(pmap);
3836 KASSERT((sva & L2_OFFSET) == 0,
3837 ("pmap_protect_l2: sva is not 2mpage aligned"));
3838 old_l2 = pmap_load(l2);
3839 KASSERT((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK,
3840 ("pmap_protect_l2: L2e %lx is not a block mapping", old_l2));
3843 * Return if the L2 entry already has the desired access restrictions
3846 if ((old_l2 & mask) == nbits)
3849 while (!atomic_fcmpset_64(l2, &old_l2, (old_l2 & ~mask) | nbits))
3853 * When a dirty read/write superpage mapping is write protected,
3854 * update the dirty field of each of the superpage's constituent 4KB
3857 if ((old_l2 & ATTR_SW_MANAGED) != 0 &&
3858 (nbits & ATTR_S1_AP(ATTR_S1_AP_RO)) != 0 &&
3859 pmap_pte_dirty(pmap, old_l2)) {
3860 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(old_l2));
3861 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
3866 * Since a promotion must break the 4KB page mappings before making
3867 * the 2MB page mapping, a pmap_s1_invalidate_page() suffices.
3869 pmap_s1_invalidate_page(pmap, sva, true);
3873 * Masks and sets bits in last level page table entries in the specified
3877 pmap_mask_set_locked(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, pt_entry_t mask,
3878 pt_entry_t nbits, bool invalidate)
3880 vm_offset_t va, va_next;
3881 pd_entry_t *l0, *l1, *l2;
3882 pt_entry_t *l3p, l3;
3884 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3885 for (; sva < eva; sva = va_next) {
3886 l0 = pmap_l0(pmap, sva);
3887 if (pmap_load(l0) == 0) {
3888 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
3894 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
3897 l1 = pmap_l0_to_l1(l0, sva);
3898 if (pmap_load(l1) == 0)
3900 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
3901 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
3902 KASSERT(va_next <= eva,
3903 ("partial update of non-transparent 1G page "
3904 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
3905 pmap_load(l1), sva, eva, va_next));
3906 MPASS((pmap_load(l1) & ATTR_SW_MANAGED) == 0);
3907 if ((pmap_load(l1) & mask) != nbits) {
3908 pmap_store(l1, (pmap_load(l1) & ~mask) | nbits);
3910 pmap_s1_invalidate_page(pmap, sva, true);
3915 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
3919 l2 = pmap_l1_to_l2(l1, sva);
3920 if (pmap_load(l2) == 0)
3923 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK) {
3924 if (sva + L2_SIZE == va_next && eva >= va_next) {
3925 pmap_protect_l2(pmap, l2, sva, mask, nbits);
3927 } else if (pmap_demote_l2(pmap, l2, sva) == NULL)
3930 KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
3931 ("pmap_protect: Invalid L2 entry after demotion"));
3937 for (l3p = pmap_l2_to_l3(l2, sva); sva != va_next; l3p++,
3939 l3 = pmap_load(l3p);
3942 * Go to the next L3 entry if the current one is
3943 * invalid or already has the desired access
3944 * restrictions in place. (The latter case occurs
3945 * frequently. For example, in a "buildworld"
3946 * workload, almost 1 out of 4 L3 entries already
3947 * have the desired restrictions.)
3949 if (!pmap_l3_valid(l3) || (l3 & mask) == nbits) {
3950 if (va != va_next) {
3952 pmap_s1_invalidate_range(pmap,
3959 while (!atomic_fcmpset_64(l3p, &l3, (l3 & ~mask) |
3964 * When a dirty read/write mapping is write protected,
3965 * update the page's dirty field.
3967 if ((l3 & ATTR_SW_MANAGED) != 0 &&
3968 (nbits & ATTR_S1_AP(ATTR_S1_AP_RO)) != 0 &&
3969 pmap_pte_dirty(pmap, l3))
3970 vm_page_dirty(PHYS_TO_VM_PAGE(PTE_TO_PHYS(l3)));
3975 if (va != va_next && invalidate)
3976 pmap_s1_invalidate_range(pmap, va, sva, true);
3981 pmap_mask_set(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, pt_entry_t mask,
3982 pt_entry_t nbits, bool invalidate)
3985 pmap_mask_set_locked(pmap, sva, eva, mask, nbits, invalidate);
3990 * Set the physical protection on the
3991 * specified range of this map as requested.
3994 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
3996 pt_entry_t mask, nbits;
3998 PMAP_ASSERT_STAGE1(pmap);
3999 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4000 if (prot == VM_PROT_NONE) {
4001 pmap_remove(pmap, sva, eva);
4006 if ((prot & VM_PROT_WRITE) == 0) {
4007 mask |= ATTR_S1_AP_RW_BIT | ATTR_SW_DBM;
4008 nbits |= ATTR_S1_AP(ATTR_S1_AP_RO);
4010 if ((prot & VM_PROT_EXECUTE) == 0) {
4012 nbits |= ATTR_S1_XN;
4017 pmap_mask_set(pmap, sva, eva, mask, nbits, true);
4021 pmap_disable_promotion(vm_offset_t sva, vm_size_t size)
4024 MPASS((sva & L3_OFFSET) == 0);
4025 MPASS(((sva + size) & L3_OFFSET) == 0);
4027 pmap_mask_set(kernel_pmap, sva, sva + size, ATTR_SW_NO_PROMOTE,
4028 ATTR_SW_NO_PROMOTE, false);
4032 * Inserts the specified page table page into the specified pmap's collection
4033 * of idle page table pages. Each of a pmap's page table pages is responsible
4034 * for mapping a distinct range of virtual addresses. The pmap's collection is
4035 * ordered by this virtual address range.
4037 * If "promoted" is false, then the page table page "mpte" must be zero filled;
4038 * "mpte"'s valid field will be set to 0.
4040 * If "promoted" is true and "all_l3e_AF_set" is false, then "mpte" must
4041 * contain valid mappings with identical attributes except for ATTR_AF;
4042 * "mpte"'s valid field will be set to 1.
4044 * If "promoted" and "all_l3e_AF_set" are both true, then "mpte" must contain
4045 * valid mappings with identical attributes including ATTR_AF; "mpte"'s valid
4046 * field will be set to VM_PAGE_BITS_ALL.
4049 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted,
4050 bool all_l3e_AF_set)
4053 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4054 KASSERT(promoted || !all_l3e_AF_set,
4055 ("a zero-filled PTP can't have ATTR_AF set in every PTE"));
4056 mpte->valid = promoted ? (all_l3e_AF_set ? VM_PAGE_BITS_ALL : 1) : 0;
4057 return (vm_radix_insert(&pmap->pm_root, mpte));
4061 * Removes the page table page mapping the specified virtual address from the
4062 * specified pmap's collection of idle page table pages, and returns it.
4063 * Otherwise, returns NULL if there is no page table page corresponding to the
4064 * specified virtual address.
4066 static __inline vm_page_t
4067 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
4070 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4071 return (vm_radix_remove(&pmap->pm_root, pmap_l2_pindex(va)));
4075 * Performs a break-before-make update of a pmap entry. This is needed when
4076 * either promoting or demoting pages to ensure the TLB doesn't get into an
4077 * inconsistent state.
4080 pmap_update_entry(pmap_t pmap, pd_entry_t *pte, pd_entry_t newpte,
4081 vm_offset_t va, vm_size_t size)
4085 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4087 if ((newpte & ATTR_SW_NO_PROMOTE) != 0)
4088 panic("%s: Updating non-promote pte", __func__);
4091 * Ensure we don't get switched out with the page table in an
4092 * inconsistent state. We also need to ensure no interrupts fire
4093 * as they may make use of an address we are about to invalidate.
4095 intr = intr_disable();
4098 * Clear the old mapping's valid bit, but leave the rest of the entry
4099 * unchanged, so that a lockless, concurrent pmap_kextract() can still
4100 * lookup the physical address.
4102 pmap_clear_bits(pte, ATTR_DESCR_VALID);
4105 * When promoting, the L{1,2}_TABLE entry that is being replaced might
4106 * be cached, so we invalidate intermediate entries as well as final
4109 pmap_s1_invalidate_range(pmap, va, va + size, false);
4111 /* Create the new mapping */
4112 pmap_store(pte, newpte);
4118 #if VM_NRESERVLEVEL > 0
4120 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
4121 * replace the many pv entries for the 4KB page mappings by a single pv entry
4122 * for the 2MB page mapping.
4125 pmap_pv_promote_l2(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
4126 struct rwlock **lockp)
4128 struct md_page *pvh;
4130 vm_offset_t va_last;
4133 KASSERT((pa & L2_OFFSET) == 0,
4134 ("pmap_pv_promote_l2: pa is not 2mpage aligned"));
4135 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
4138 * Transfer the first page's pv entry for this mapping to the 2mpage's
4139 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
4140 * a transfer avoids the possibility that get_pv_entry() calls
4141 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
4142 * mappings that is being promoted.
4144 m = PHYS_TO_VM_PAGE(pa);
4145 va = va & ~L2_OFFSET;
4146 pv = pmap_pvh_remove(&m->md, pmap, va);
4147 KASSERT(pv != NULL, ("pmap_pv_promote_l2: pv not found"));
4148 pvh = page_to_pvh(m);
4149 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
4151 /* Free the remaining NPTEPG - 1 pv entries. */
4152 va_last = va + L2_SIZE - PAGE_SIZE;
4156 pmap_pvh_free(&m->md, pmap, va);
4157 } while (va < va_last);
4161 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4162 * single level 2 table entry to a single 2MB page mapping. For promotion
4163 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4164 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4165 * identical characteristics.
4168 pmap_promote_l2(pmap_t pmap, pd_entry_t *l2, vm_offset_t va, vm_page_t mpte,
4169 struct rwlock **lockp)
4171 pt_entry_t all_l3e_AF, *firstl3, *l3, newl2, oldl3, pa;
4173 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4176 * Currently, this function only supports promotion on stage 1 pmaps
4177 * because it tests stage 1 specific fields and performs a break-
4178 * before-make sequence that is incorrect for stage 2 pmaps.
4180 if (pmap->pm_stage != PM_STAGE1 || !pmap_ps_enabled(pmap))
4184 * Examine the first L3E in the specified PTP. Abort if this L3E is
4185 * ineligible for promotion...
4187 firstl3 = (pt_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(pmap_load(l2)));
4188 newl2 = pmap_load(firstl3);
4189 if ((newl2 & ATTR_SW_NO_PROMOTE) != 0)
4191 /* ... is not the first physical page within an L2 block */
4192 if ((PTE_TO_PHYS(newl2) & L2_OFFSET) != 0 ||
4193 ((newl2 & ATTR_DESCR_MASK) != L3_PAGE)) { /* ... or is invalid */
4194 atomic_add_long(&pmap_l2_p_failures, 1);
4195 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
4196 " in pmap %p", va, pmap);
4201 * Both here and in the below "for" loop, to allow for repromotion
4202 * after MADV_FREE, conditionally write protect a clean L3E before
4203 * possibly aborting the promotion due to other L3E attributes. Why?
4204 * Suppose that MADV_FREE is applied to a part of a superpage, the
4205 * address range [S, E). pmap_advise() will demote the superpage
4206 * mapping, destroy the 4KB page mapping at the end of [S, E), and
4207 * set AP_RO and clear AF in the L3Es for the rest of [S, E). Later,
4208 * imagine that the memory in [S, E) is recycled, but the last 4KB
4209 * page in [S, E) is not the last to be rewritten, or simply accessed.
4210 * In other words, there is still a 4KB page in [S, E), call it P,
4211 * that is writeable but AP_RO is set and AF is clear in P's L3E.
4212 * Unless we write protect P before aborting the promotion, if and
4213 * when P is finally rewritten, there won't be a page fault to trigger
4217 if ((newl2 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
4218 (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM)) {
4220 * When the mapping is clean, i.e., ATTR_S1_AP_RO is set,
4221 * ATTR_SW_DBM can be cleared without a TLB invalidation.
4223 if (!atomic_fcmpset_64(firstl3, &newl2, newl2 & ~ATTR_SW_DBM))
4225 newl2 &= ~ATTR_SW_DBM;
4226 CTR2(KTR_PMAP, "pmap_promote_l2: protect for va %#lx"
4227 " in pmap %p", va & ~L2_OFFSET, pmap);
4231 * Examine each of the other L3Es in the specified PTP. Abort if this
4232 * L3E maps an unexpected 4KB physical page or does not have identical
4233 * characteristics to the first L3E. If ATTR_AF is not set in every
4234 * PTE, then request that the PTP be refilled on demotion.
4236 all_l3e_AF = newl2 & ATTR_AF;
4237 pa = (PTE_TO_PHYS(newl2) | (newl2 & ATTR_DESCR_MASK))
4238 + L2_SIZE - PAGE_SIZE;
4239 for (l3 = firstl3 + NL3PG - 1; l3 > firstl3; l3--) {
4240 oldl3 = pmap_load(l3);
4241 if ((PTE_TO_PHYS(oldl3) | (oldl3 & ATTR_DESCR_MASK)) != pa) {
4242 atomic_add_long(&pmap_l2_p_failures, 1);
4243 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
4244 " in pmap %p", va, pmap);
4248 if ((oldl3 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
4249 (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM)) {
4251 * When the mapping is clean, i.e., ATTR_S1_AP_RO is
4252 * set, ATTR_SW_DBM can be cleared without a TLB
4255 if (!atomic_fcmpset_64(l3, &oldl3, oldl3 &
4258 oldl3 &= ~ATTR_SW_DBM;
4260 if ((oldl3 & (ATTR_MASK & ~ATTR_AF)) != (newl2 & (ATTR_MASK &
4262 atomic_add_long(&pmap_l2_p_failures, 1);
4263 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
4264 " in pmap %p", va, pmap);
4267 all_l3e_AF &= oldl3;
4272 * Unless all PTEs have ATTR_AF set, clear it from the superpage
4273 * mapping, so that promotions triggered by speculative mappings,
4274 * such as pmap_enter_quick(), don't automatically mark the
4275 * underlying pages as referenced.
4277 newl2 &= ~ATTR_AF | all_l3e_AF;
4280 * Save the page table page in its current state until the L2
4281 * mapping the superpage is demoted by pmap_demote_l2() or
4282 * destroyed by pmap_remove_l3().
4285 mpte = PHYS_TO_VM_PAGE(PTE_TO_PHYS(pmap_load(l2)));
4286 KASSERT(mpte >= vm_page_array &&
4287 mpte < &vm_page_array[vm_page_array_size],
4288 ("pmap_promote_l2: page table page is out of range"));
4289 KASSERT(mpte->pindex == pmap_l2_pindex(va),
4290 ("pmap_promote_l2: page table page's pindex is wrong"));
4291 if (pmap_insert_pt_page(pmap, mpte, true, all_l3e_AF != 0)) {
4292 atomic_add_long(&pmap_l2_p_failures, 1);
4294 "pmap_promote_l2: failure for va %#lx in pmap %p", va,
4299 if ((newl2 & ATTR_SW_MANAGED) != 0)
4300 pmap_pv_promote_l2(pmap, va, PTE_TO_PHYS(newl2), lockp);
4302 newl2 &= ~ATTR_DESCR_MASK;
4305 pmap_update_entry(pmap, l2, newl2, va & ~L2_OFFSET, L2_SIZE);
4307 atomic_add_long(&pmap_l2_promotions, 1);
4308 CTR2(KTR_PMAP, "pmap_promote_l2: success for va %#lx in pmap %p", va,
4312 #endif /* VM_NRESERVLEVEL > 0 */
4315 pmap_enter_largepage(pmap_t pmap, vm_offset_t va, pt_entry_t newpte, int flags,
4318 pd_entry_t *l0p, *l1p, *l2p, origpte;
4321 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4322 KASSERT(psind > 0 && psind < MAXPAGESIZES,
4323 ("psind %d unexpected", psind));
4324 KASSERT((PTE_TO_PHYS(newpte) & (pagesizes[psind] - 1)) == 0,
4325 ("unaligned phys address %#lx newpte %#lx psind %d",
4326 PTE_TO_PHYS(newpte), newpte, psind));
4330 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
4332 l0p = pmap_l0(pmap, va);
4333 if ((pmap_load(l0p) & ATTR_DESCR_VALID) == 0) {
4334 mp = _pmap_alloc_l3(pmap, pmap_l0_pindex(va), NULL);
4336 if ((flags & PMAP_ENTER_NOSLEEP) != 0)
4337 return (KERN_RESOURCE_SHORTAGE);
4343 l1p = pmap_l0_to_l1(l0p, va);
4344 KASSERT(l1p != NULL, ("va %#lx lost l1 entry", va));
4345 origpte = pmap_load(l1p);
4347 l1p = pmap_l0_to_l1(l0p, va);
4348 KASSERT(l1p != NULL, ("va %#lx lost l1 entry", va));
4349 origpte = pmap_load(l1p);
4350 if ((origpte & ATTR_DESCR_VALID) == 0) {
4351 mp = PHYS_TO_VM_PAGE(
4352 PTE_TO_PHYS(pmap_load(l0p)));
4356 KASSERT((PTE_TO_PHYS(origpte) == PTE_TO_PHYS(newpte) &&
4357 (origpte & ATTR_DESCR_MASK) == L1_BLOCK) ||
4358 (origpte & ATTR_DESCR_VALID) == 0,
4359 ("va %#lx changing 1G phys page l1 %#lx newpte %#lx",
4360 va, origpte, newpte));
4361 pmap_store(l1p, newpte);
4362 } else /* (psind == 1) */ {
4363 l2p = pmap_l2(pmap, va);
4365 mp = _pmap_alloc_l3(pmap, pmap_l1_pindex(va), NULL);
4367 if ((flags & PMAP_ENTER_NOSLEEP) != 0)
4368 return (KERN_RESOURCE_SHORTAGE);
4374 l2p = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
4375 l2p = &l2p[pmap_l2_index(va)];
4376 origpte = pmap_load(l2p);
4378 l1p = pmap_l1(pmap, va);
4379 origpte = pmap_load(l2p);
4380 if ((origpte & ATTR_DESCR_VALID) == 0) {
4381 mp = PHYS_TO_VM_PAGE(
4382 PTE_TO_PHYS(pmap_load(l1p)));
4386 KASSERT((origpte & ATTR_DESCR_VALID) == 0 ||
4387 ((origpte & ATTR_DESCR_MASK) == L2_BLOCK &&
4388 PTE_TO_PHYS(origpte) == PTE_TO_PHYS(newpte)),
4389 ("va %#lx changing 2M phys page l2 %#lx newpte %#lx",
4390 va, origpte, newpte));
4391 pmap_store(l2p, newpte);
4395 if ((origpte & ATTR_DESCR_VALID) == 0)
4396 pmap_resident_count_inc(pmap, pagesizes[psind] / PAGE_SIZE);
4397 if ((newpte & ATTR_SW_WIRED) != 0 && (origpte & ATTR_SW_WIRED) == 0)
4398 pmap->pm_stats.wired_count += pagesizes[psind] / PAGE_SIZE;
4399 else if ((newpte & ATTR_SW_WIRED) == 0 &&
4400 (origpte & ATTR_SW_WIRED) != 0)
4401 pmap->pm_stats.wired_count -= pagesizes[psind] / PAGE_SIZE;
4403 return (KERN_SUCCESS);
4407 * Insert the given physical page (p) at
4408 * the specified virtual address (v) in the
4409 * target physical map with the protection requested.
4411 * If specified, the page will be wired down, meaning
4412 * that the related pte can not be reclaimed.
4414 * NB: This is the only routine which MAY NOT lazy-evaluate
4415 * or lose information. That is, this routine must actually
4416 * insert this page into the given map NOW.
4419 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4420 u_int flags, int8_t psind)
4422 struct rwlock *lock;
4424 pt_entry_t new_l3, orig_l3;
4425 pt_entry_t *l2, *l3;
4432 KASSERT(ADDR_IS_CANONICAL(va),
4433 ("%s: Address not in canonical form: %lx", __func__, va));
4435 va = trunc_page(va);
4436 if ((m->oflags & VPO_UNMANAGED) == 0)
4437 VM_PAGE_OBJECT_BUSY_ASSERT(m);
4438 pa = VM_PAGE_TO_PHYS(m);
4439 new_l3 = (pt_entry_t)(PHYS_TO_PTE(pa) | ATTR_DEFAULT | L3_PAGE);
4440 new_l3 |= pmap_pte_memattr(pmap, m->md.pv_memattr);
4441 new_l3 |= pmap_pte_prot(pmap, prot);
4443 if ((flags & PMAP_ENTER_WIRED) != 0)
4444 new_l3 |= ATTR_SW_WIRED;
4445 if (pmap->pm_stage == PM_STAGE1) {
4446 if (!ADDR_IS_KERNEL(va))
4447 new_l3 |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
4449 new_l3 |= ATTR_S1_UXN;
4450 if (pmap != kernel_pmap)
4451 new_l3 |= ATTR_S1_nG;
4454 * Clear the access flag on executable mappings, this will be
4455 * set later when the page is accessed. The fault handler is
4456 * required to invalidate the I-cache.
4458 * TODO: Switch to the valid flag to allow hardware management
4459 * of the access flag. Much of the pmap code assumes the
4460 * valid flag is set and fails to destroy the old page tables
4461 * correctly if it is clear.
4463 if (prot & VM_PROT_EXECUTE)
4466 if ((m->oflags & VPO_UNMANAGED) == 0) {
4467 new_l3 |= ATTR_SW_MANAGED;
4468 if ((prot & VM_PROT_WRITE) != 0) {
4469 new_l3 |= ATTR_SW_DBM;
4470 if ((flags & VM_PROT_WRITE) == 0) {
4471 if (pmap->pm_stage == PM_STAGE1)
4472 new_l3 |= ATTR_S1_AP(ATTR_S1_AP_RO);
4475 ~ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
4480 CTR2(KTR_PMAP, "pmap_enter: %.16lx -> %.16lx", va, pa);
4484 if ((flags & PMAP_ENTER_LARGEPAGE) != 0) {
4485 KASSERT((m->oflags & VPO_UNMANAGED) != 0,
4486 ("managed largepage va %#lx flags %#x", va, flags));
4489 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
4491 } else /* (psind == 1) */
4493 rv = pmap_enter_largepage(pmap, va, new_l3, flags, psind);
4497 /* Assert the required virtual and physical alignment. */
4498 KASSERT((va & L2_OFFSET) == 0, ("pmap_enter: va unaligned"));
4499 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4500 rv = pmap_enter_l2(pmap, va, (new_l3 & ~L3_PAGE) | L2_BLOCK,
4507 * In the case that a page table page is not
4508 * resident, we are creating it here.
4511 pde = pmap_pde(pmap, va, &lvl);
4512 if (pde != NULL && lvl == 2) {
4513 l3 = pmap_l2_to_l3(pde, va);
4514 if (!ADDR_IS_KERNEL(va) && mpte == NULL) {
4515 mpte = PHYS_TO_VM_PAGE(PTE_TO_PHYS(pmap_load(pde)));
4519 } else if (pde != NULL && lvl == 1) {
4520 l2 = pmap_l1_to_l2(pde, va);
4521 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK &&
4522 (l3 = pmap_demote_l2_locked(pmap, l2, va, &lock)) != NULL) {
4523 l3 = &l3[pmap_l3_index(va)];
4524 if (!ADDR_IS_KERNEL(va)) {
4525 mpte = PHYS_TO_VM_PAGE(
4526 PTE_TO_PHYS(pmap_load(l2)));
4531 /* We need to allocate an L3 table. */
4533 if (!ADDR_IS_KERNEL(va)) {
4534 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4537 * We use _pmap_alloc_l3() instead of pmap_alloc_l3() in order
4538 * to handle the possibility that a superpage mapping for "va"
4539 * was created while we slept.
4541 mpte = _pmap_alloc_l3(pmap, pmap_l2_pindex(va),
4542 nosleep ? NULL : &lock);
4543 if (mpte == NULL && nosleep) {
4544 CTR0(KTR_PMAP, "pmap_enter: mpte == NULL");
4545 rv = KERN_RESOURCE_SHORTAGE;
4550 panic("pmap_enter: missing L3 table for kernel va %#lx", va);
4553 orig_l3 = pmap_load(l3);
4554 opa = PTE_TO_PHYS(orig_l3);
4558 * Is the specified virtual address already mapped?
4560 if (pmap_l3_valid(orig_l3)) {
4562 * Wiring change, just update stats. We don't worry about
4563 * wiring PT pages as they remain resident as long as there
4564 * are valid mappings in them. Hence, if a user page is wired,
4565 * the PT page will be also.
4567 if ((flags & PMAP_ENTER_WIRED) != 0 &&
4568 (orig_l3 & ATTR_SW_WIRED) == 0)
4569 pmap->pm_stats.wired_count++;
4570 else if ((flags & PMAP_ENTER_WIRED) == 0 &&
4571 (orig_l3 & ATTR_SW_WIRED) != 0)
4572 pmap->pm_stats.wired_count--;
4575 * Remove the extra PT page reference.
4579 KASSERT(mpte->ref_count > 0,
4580 ("pmap_enter: missing reference to page table page,"
4585 * Has the physical page changed?
4589 * No, might be a protection or wiring change.
4591 if ((orig_l3 & ATTR_SW_MANAGED) != 0 &&
4592 (new_l3 & ATTR_SW_DBM) != 0)
4593 vm_page_aflag_set(m, PGA_WRITEABLE);
4598 * The physical page has changed. Temporarily invalidate
4601 orig_l3 = pmap_load_clear(l3);
4602 KASSERT(PTE_TO_PHYS(orig_l3) == opa,
4603 ("pmap_enter: unexpected pa update for %#lx", va));
4604 if ((orig_l3 & ATTR_SW_MANAGED) != 0) {
4605 om = PHYS_TO_VM_PAGE(opa);
4608 * The pmap lock is sufficient to synchronize with
4609 * concurrent calls to pmap_page_test_mappings() and
4610 * pmap_ts_referenced().
4612 if (pmap_pte_dirty(pmap, orig_l3))
4614 if ((orig_l3 & ATTR_AF) != 0) {
4615 pmap_invalidate_page(pmap, va, true);
4616 vm_page_aflag_set(om, PGA_REFERENCED);
4618 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, om);
4619 pv = pmap_pvh_remove(&om->md, pmap, va);
4620 if ((m->oflags & VPO_UNMANAGED) != 0)
4621 free_pv_entry(pmap, pv);
4622 if ((om->a.flags & PGA_WRITEABLE) != 0 &&
4623 TAILQ_EMPTY(&om->md.pv_list) &&
4624 ((om->flags & PG_FICTITIOUS) != 0 ||
4625 TAILQ_EMPTY(&page_to_pvh(om)->pv_list)))
4626 vm_page_aflag_clear(om, PGA_WRITEABLE);
4628 KASSERT((orig_l3 & ATTR_AF) != 0,
4629 ("pmap_enter: unmanaged mapping lacks ATTR_AF"));
4630 pmap_invalidate_page(pmap, va, true);
4635 * Increment the counters.
4637 if ((new_l3 & ATTR_SW_WIRED) != 0)
4638 pmap->pm_stats.wired_count++;
4639 pmap_resident_count_inc(pmap, 1);
4642 * Enter on the PV list if part of our managed memory.
4644 if ((m->oflags & VPO_UNMANAGED) == 0) {
4646 pv = get_pv_entry(pmap, &lock);
4649 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
4650 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4652 if ((new_l3 & ATTR_SW_DBM) != 0)
4653 vm_page_aflag_set(m, PGA_WRITEABLE);
4657 if (pmap->pm_stage == PM_STAGE1) {
4659 * Sync icache if exec permission and attribute
4660 * VM_MEMATTR_WRITE_BACK is set. Do it now, before the mapping
4661 * is stored and made valid for hardware table walk. If done
4662 * later, then other can access this page before caches are
4663 * properly synced. Don't do it for kernel memory which is
4664 * mapped with exec permission even if the memory isn't going
4665 * to hold executable code. The only time when icache sync is
4666 * needed is after kernel module is loaded and the relocation
4667 * info is processed. And it's done in elf_cpu_load_file().
4669 if ((prot & VM_PROT_EXECUTE) && pmap != kernel_pmap &&
4670 m->md.pv_memattr == VM_MEMATTR_WRITE_BACK &&
4671 (opa != pa || (orig_l3 & ATTR_S1_XN))) {
4672 PMAP_ASSERT_STAGE1(pmap);
4673 cpu_icache_sync_range(PHYS_TO_DMAP(pa), PAGE_SIZE);
4676 cpu_dcache_wb_range(PHYS_TO_DMAP(pa), PAGE_SIZE);
4680 * Update the L3 entry
4682 if (pmap_l3_valid(orig_l3)) {
4683 KASSERT(opa == pa, ("pmap_enter: invalid update"));
4684 if ((orig_l3 & ~ATTR_AF) != (new_l3 & ~ATTR_AF)) {
4685 /* same PA, different attributes */
4686 orig_l3 = pmap_load_store(l3, new_l3);
4687 pmap_invalidate_page(pmap, va, true);
4688 if ((orig_l3 & ATTR_SW_MANAGED) != 0 &&
4689 pmap_pte_dirty(pmap, orig_l3))
4694 * This can happens if multiple threads simultaneously
4695 * access not yet mapped page. This bad for performance
4696 * since this can cause full demotion-NOP-promotion
4698 * Another possible reasons are:
4699 * - VM and pmap memory layout are diverged
4700 * - tlb flush is missing somewhere and CPU doesn't see
4703 CTR4(KTR_PMAP, "%s: already mapped page - "
4704 "pmap %p va 0x%#lx pte 0x%lx",
4705 __func__, pmap, va, new_l3);
4709 pmap_store(l3, new_l3);
4713 #if VM_NRESERVLEVEL > 0
4715 * If both the page table page and the reservation are fully
4716 * populated, then attempt promotion.
4718 if ((mpte == NULL || mpte->ref_count == NL3PG) &&
4719 (m->flags & PG_FICTITIOUS) == 0 &&
4720 vm_reserv_level_iffullpop(m) == 0)
4721 (void)pmap_promote_l2(pmap, pde, va, mpte, &lock);
4733 * Tries to create a read- and/or execute-only 2MB page mapping. Returns
4734 * KERN_SUCCESS if the mapping was created. Otherwise, returns an error
4735 * value. See pmap_enter_l2() for the possible error values when "no sleep",
4736 * "no replace", and "no reclaim" are specified.
4739 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4740 struct rwlock **lockp)
4744 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4745 PMAP_ASSERT_STAGE1(pmap);
4746 KASSERT(ADDR_IS_CANONICAL(va),
4747 ("%s: Address not in canonical form: %lx", __func__, va));
4749 new_l2 = (pd_entry_t)(PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) | ATTR_DEFAULT |
4750 ATTR_S1_IDX(m->md.pv_memattr) | ATTR_S1_AP(ATTR_S1_AP_RO) |
4752 if ((m->oflags & VPO_UNMANAGED) == 0) {
4753 new_l2 |= ATTR_SW_MANAGED;
4756 if ((prot & VM_PROT_EXECUTE) == 0 ||
4757 m->md.pv_memattr == VM_MEMATTR_DEVICE)
4758 new_l2 |= ATTR_S1_XN;
4759 if (!ADDR_IS_KERNEL(va))
4760 new_l2 |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
4762 new_l2 |= ATTR_S1_UXN;
4763 if (pmap != kernel_pmap)
4764 new_l2 |= ATTR_S1_nG;
4765 return (pmap_enter_l2(pmap, va, new_l2, PMAP_ENTER_NOSLEEP |
4766 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, m, lockp));
4770 * Returns true if every page table entry in the specified page table is
4774 pmap_every_pte_zero(vm_paddr_t pa)
4776 pt_entry_t *pt_end, *pte;
4778 KASSERT((pa & PAGE_MASK) == 0, ("pa is misaligned"));
4779 pte = (pt_entry_t *)PHYS_TO_DMAP(pa);
4780 for (pt_end = pte + Ln_ENTRIES; pte < pt_end; pte++) {
4788 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
4789 * the mapping was created, and one of KERN_FAILURE, KERN_NO_SPACE, or
4790 * KERN_RESOURCE_SHORTAGE otherwise. Returns KERN_FAILURE if
4791 * PMAP_ENTER_NOREPLACE was specified and a 4KB page mapping already exists
4792 * within the 2MB virtual address range starting at the specified virtual
4793 * address. Returns KERN_NO_SPACE if PMAP_ENTER_NOREPLACE was specified and a
4794 * 2MB page mapping already exists at the specified virtual address. Returns
4795 * KERN_RESOURCE_SHORTAGE if either (1) PMAP_ENTER_NOSLEEP was specified and a
4796 * page table page allocation failed or (2) PMAP_ENTER_NORECLAIM was specified
4797 * and a PV entry allocation failed.
4800 pmap_enter_l2(pmap_t pmap, vm_offset_t va, pd_entry_t new_l2, u_int flags,
4801 vm_page_t m, struct rwlock **lockp)
4803 struct spglist free;
4804 pd_entry_t *l2, old_l2;
4808 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4809 KASSERT(ADDR_IS_CANONICAL(va),
4810 ("%s: Address not in canonical form: %lx", __func__, va));
4812 if ((l2 = pmap_alloc_l2(pmap, va, &l2pg, (flags &
4813 PMAP_ENTER_NOSLEEP) != 0 ? NULL : lockp)) == NULL) {
4814 CTR2(KTR_PMAP, "pmap_enter_l2: failure for va %#lx in pmap %p",
4816 return (KERN_RESOURCE_SHORTAGE);
4820 * If there are existing mappings, either abort or remove them.
4822 if ((old_l2 = pmap_load(l2)) != 0) {
4823 KASSERT(l2pg == NULL || l2pg->ref_count > 1,
4824 ("pmap_enter_l2: l2pg's ref count is too low"));
4825 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
4826 if ((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK) {
4830 "pmap_enter_l2: no space for va %#lx"
4831 " in pmap %p", va, pmap);
4832 return (KERN_NO_SPACE);
4833 } else if (!ADDR_IS_KERNEL(va) ||
4834 !pmap_every_pte_zero(PTE_TO_PHYS(old_l2))) {
4838 "pmap_enter_l2: failure for va %#lx"
4839 " in pmap %p", va, pmap);
4840 return (KERN_FAILURE);
4844 if ((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK)
4845 (void)pmap_remove_l2(pmap, l2, va,
4846 pmap_load(pmap_l1(pmap, va)), &free, lockp);
4848 pmap_remove_l3_range(pmap, old_l2, va, va + L2_SIZE,
4850 if (!ADDR_IS_KERNEL(va)) {
4851 vm_page_free_pages_toq(&free, true);
4852 KASSERT(pmap_load(l2) == 0,
4853 ("pmap_enter_l2: non-zero L2 entry %p", l2));
4855 KASSERT(SLIST_EMPTY(&free),
4856 ("pmap_enter_l2: freed kernel page table page"));
4859 * Both pmap_remove_l2() and pmap_remove_l3_range()
4860 * will leave the kernel page table page zero filled.
4861 * Nonetheless, the TLB could have an intermediate
4862 * entry for the kernel page table page, so request
4863 * an invalidation at all levels after clearing
4864 * the L2_TABLE entry.
4866 mt = PHYS_TO_VM_PAGE(PTE_TO_PHYS(pmap_load(l2)));
4867 if (pmap_insert_pt_page(pmap, mt, false, false))
4868 panic("pmap_enter_l2: trie insert failed");
4870 pmap_s1_invalidate_page(pmap, va, false);
4875 * Allocate leaf ptpage for wired userspace pages.
4878 if ((new_l2 & ATTR_SW_WIRED) != 0 && pmap != kernel_pmap) {
4879 uwptpg = vm_page_alloc_noobj(VM_ALLOC_WIRED);
4880 if (uwptpg == NULL) {
4881 return (KERN_RESOURCE_SHORTAGE);
4883 uwptpg->pindex = pmap_l2_pindex(va);
4884 if (pmap_insert_pt_page(pmap, uwptpg, true, false)) {
4885 vm_page_unwire_noq(uwptpg);
4886 vm_page_free(uwptpg);
4887 return (KERN_RESOURCE_SHORTAGE);
4889 pmap_resident_count_inc(pmap, 1);
4890 uwptpg->ref_count = NL3PG;
4892 if ((new_l2 & ATTR_SW_MANAGED) != 0) {
4894 * Abort this mapping if its PV entry could not be created.
4896 if (!pmap_pv_insert_l2(pmap, va, new_l2, flags, lockp)) {
4898 pmap_abort_ptp(pmap, va, l2pg);
4899 if (uwptpg != NULL) {
4900 mt = pmap_remove_pt_page(pmap, va);
4901 KASSERT(mt == uwptpg,
4902 ("removed pt page %p, expected %p", mt,
4904 pmap_resident_count_dec(pmap, 1);
4905 uwptpg->ref_count = 1;
4906 vm_page_unwire_noq(uwptpg);
4907 vm_page_free(uwptpg);
4910 "pmap_enter_l2: failure for va %#lx in pmap %p",
4912 return (KERN_RESOURCE_SHORTAGE);
4914 if ((new_l2 & ATTR_SW_DBM) != 0)
4915 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
4916 vm_page_aflag_set(mt, PGA_WRITEABLE);
4920 * Increment counters.
4922 if ((new_l2 & ATTR_SW_WIRED) != 0)
4923 pmap->pm_stats.wired_count += L2_SIZE / PAGE_SIZE;
4924 pmap->pm_stats.resident_count += L2_SIZE / PAGE_SIZE;
4927 * Conditionally sync the icache. See pmap_enter() for details.
4929 if ((new_l2 & ATTR_S1_XN) == 0 && (PTE_TO_PHYS(new_l2) !=
4930 PTE_TO_PHYS(old_l2) || (old_l2 & ATTR_S1_XN) != 0) &&
4931 pmap != kernel_pmap && m->md.pv_memattr == VM_MEMATTR_WRITE_BACK) {
4932 cpu_icache_sync_range(PHYS_TO_DMAP(PTE_TO_PHYS(new_l2)),
4937 * Map the superpage.
4939 pmap_store(l2, new_l2);
4942 atomic_add_long(&pmap_l2_mappings, 1);
4943 CTR2(KTR_PMAP, "pmap_enter_l2: success for va %#lx in pmap %p",
4946 return (KERN_SUCCESS);
4950 * Maps a sequence of resident pages belonging to the same object.
4951 * The sequence begins with the given page m_start. This page is
4952 * mapped at the given virtual address start. Each subsequent page is
4953 * mapped at a virtual address that is offset from start by the same
4954 * amount as the page is offset from m_start within the object. The
4955 * last page in the sequence is the page with the largest offset from
4956 * m_start that can be mapped at a virtual address less than the given
4957 * virtual address end. Not every virtual page between start and end
4958 * is mapped; only those for which a resident page exists with the
4959 * corresponding offset from m_start are mapped.
4962 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
4963 vm_page_t m_start, vm_prot_t prot)
4965 struct rwlock *lock;
4968 vm_pindex_t diff, psize;
4971 VM_OBJECT_ASSERT_LOCKED(m_start->object);
4973 psize = atop(end - start);
4978 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
4979 va = start + ptoa(diff);
4980 if ((va & L2_OFFSET) == 0 && va + L2_SIZE <= end &&
4981 m->psind == 1 && pmap_ps_enabled(pmap) &&
4982 ((rv = pmap_enter_2mpage(pmap, va, m, prot, &lock)) ==
4983 KERN_SUCCESS || rv == KERN_NO_SPACE))
4984 m = &m[L2_SIZE / PAGE_SIZE - 1];
4986 mpte = pmap_enter_quick_locked(pmap, va, m, prot, mpte,
4988 m = TAILQ_NEXT(m, listq);
4996 * this code makes some *MAJOR* assumptions:
4997 * 1. Current pmap & pmap exists.
5000 * 4. No page table pages.
5001 * but is *MUCH* faster than pmap_enter...
5005 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
5007 struct rwlock *lock;
5011 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
5018 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
5019 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
5022 pt_entry_t *l1, *l2, *l3, l3_val;
5026 KASSERT(!VA_IS_CLEANMAP(va) ||
5027 (m->oflags & VPO_UNMANAGED) != 0,
5028 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
5029 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5030 PMAP_ASSERT_STAGE1(pmap);
5031 KASSERT(ADDR_IS_CANONICAL(va),
5032 ("%s: Address not in canonical form: %lx", __func__, va));
5035 CTR2(KTR_PMAP, "pmap_enter_quick_locked: %p %lx", pmap, va);
5037 * In the case that a page table page is not
5038 * resident, we are creating it here.
5040 if (!ADDR_IS_KERNEL(va)) {
5041 vm_pindex_t l2pindex;
5044 * Calculate pagetable page index
5046 l2pindex = pmap_l2_pindex(va);
5047 if (mpte && (mpte->pindex == l2pindex)) {
5051 * If the page table page is mapped, we just increment
5052 * the hold count, and activate it. Otherwise, we
5053 * attempt to allocate a page table page, passing NULL
5054 * instead of the PV list lock pointer because we don't
5055 * intend to sleep. If this attempt fails, we don't
5056 * retry. Instead, we give up.
5058 l1 = pmap_l1(pmap, va);
5059 if (l1 != NULL && pmap_load(l1) != 0) {
5060 if ((pmap_load(l1) & ATTR_DESCR_MASK) ==
5063 l2 = pmap_l1_to_l2(l1, va);
5064 if (pmap_load(l2) != 0) {
5065 if ((pmap_load(l2) & ATTR_DESCR_MASK) ==
5068 mpte = PHYS_TO_VM_PAGE(
5069 PTE_TO_PHYS(pmap_load(l2)));
5072 mpte = _pmap_alloc_l3(pmap, l2pindex,
5078 mpte = _pmap_alloc_l3(pmap, l2pindex, NULL);
5083 l3 = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
5084 l3 = &l3[pmap_l3_index(va)];
5087 pde = pmap_pde(kernel_pmap, va, &lvl);
5088 KASSERT(pde != NULL,
5089 ("pmap_enter_quick_locked: Invalid page entry, va: 0x%lx",
5092 ("pmap_enter_quick_locked: Invalid level %d", lvl));
5093 l3 = pmap_l2_to_l3(pde, va);
5097 * Abort if a mapping already exists.
5099 if (pmap_load(l3) != 0) {
5106 * Enter on the PV list if part of our managed memory.
5108 if ((m->oflags & VPO_UNMANAGED) == 0 &&
5109 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
5111 pmap_abort_ptp(pmap, va, mpte);
5116 * Increment counters
5118 pmap_resident_count_inc(pmap, 1);
5120 pa = VM_PAGE_TO_PHYS(m);
5121 l3_val = PHYS_TO_PTE(pa) | ATTR_DEFAULT | ATTR_S1_IDX(m->md.pv_memattr) |
5122 ATTR_S1_AP(ATTR_S1_AP_RO) | L3_PAGE;
5123 if ((prot & VM_PROT_EXECUTE) == 0 ||
5124 m->md.pv_memattr == VM_MEMATTR_DEVICE)
5125 l3_val |= ATTR_S1_XN;
5126 if (!ADDR_IS_KERNEL(va))
5127 l3_val |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
5129 l3_val |= ATTR_S1_UXN;
5130 if (pmap != kernel_pmap)
5131 l3_val |= ATTR_S1_nG;
5134 * Now validate mapping with RO protection
5136 if ((m->oflags & VPO_UNMANAGED) == 0) {
5137 l3_val |= ATTR_SW_MANAGED;
5141 /* Sync icache before the mapping is stored to PTE */
5142 if ((prot & VM_PROT_EXECUTE) && pmap != kernel_pmap &&
5143 m->md.pv_memattr == VM_MEMATTR_WRITE_BACK)
5144 cpu_icache_sync_range(PHYS_TO_DMAP(pa), PAGE_SIZE);
5146 pmap_store(l3, l3_val);
5149 #if VM_NRESERVLEVEL > 0
5151 * If both the PTP and the reservation are fully populated, then
5152 * attempt promotion.
5154 if ((mpte == NULL || mpte->ref_count == NL3PG) &&
5155 (m->flags & PG_FICTITIOUS) == 0 &&
5156 vm_reserv_level_iffullpop(m) == 0) {
5158 l2 = pmap_pde(pmap, va, &lvl);
5161 * If promotion succeeds, then the next call to this function
5162 * should not be given the unmapped PTP as a hint.
5164 if (pmap_promote_l2(pmap, l2, va, mpte, lockp))
5173 * This code maps large physical mmap regions into the
5174 * processor address space. Note that some shortcuts
5175 * are taken, but the code works.
5178 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
5179 vm_pindex_t pindex, vm_size_t size)
5182 VM_OBJECT_ASSERT_WLOCKED(object);
5183 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
5184 ("pmap_object_init_pt: non-device object"));
5188 * Clear the wired attribute from the mappings for the specified range of
5189 * addresses in the given pmap. Every valid mapping within that range
5190 * must have the wired attribute set. In contrast, invalid mappings
5191 * cannot have the wired attribute set, so they are ignored.
5193 * The wired attribute of the page table entry is not a hardware feature,
5194 * so there is no need to invalidate any TLB entries.
5197 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5199 vm_offset_t va_next;
5200 pd_entry_t *l0, *l1, *l2;
5204 for (; sva < eva; sva = va_next) {
5205 l0 = pmap_l0(pmap, sva);
5206 if (pmap_load(l0) == 0) {
5207 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
5213 l1 = pmap_l0_to_l1(l0, sva);
5214 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
5217 if (pmap_load(l1) == 0)
5220 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
5221 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
5222 KASSERT(va_next <= eva,
5223 ("partial update of non-transparent 1G page "
5224 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
5225 pmap_load(l1), sva, eva, va_next));
5226 MPASS(pmap != kernel_pmap);
5227 MPASS((pmap_load(l1) & (ATTR_SW_MANAGED |
5228 ATTR_SW_WIRED)) == ATTR_SW_WIRED);
5229 pmap_clear_bits(l1, ATTR_SW_WIRED);
5230 pmap->pm_stats.wired_count -= L1_SIZE / PAGE_SIZE;
5234 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
5238 l2 = pmap_l1_to_l2(l1, sva);
5239 if (pmap_load(l2) == 0)
5242 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK) {
5243 if ((pmap_load(l2) & ATTR_SW_WIRED) == 0)
5244 panic("pmap_unwire: l2 %#jx is missing "
5245 "ATTR_SW_WIRED", (uintmax_t)pmap_load(l2));
5248 * Are we unwiring the entire large page? If not,
5249 * demote the mapping and fall through.
5251 if (sva + L2_SIZE == va_next && eva >= va_next) {
5252 pmap_clear_bits(l2, ATTR_SW_WIRED);
5253 pmap->pm_stats.wired_count -= L2_SIZE /
5256 } else if (pmap_demote_l2(pmap, l2, sva) == NULL)
5257 panic("pmap_unwire: demotion failed");
5259 KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
5260 ("pmap_unwire: Invalid l2 entry after demotion"));
5264 for (l3 = pmap_l2_to_l3(l2, sva); sva != va_next; l3++,
5266 if (pmap_load(l3) == 0)
5268 if ((pmap_load(l3) & ATTR_SW_WIRED) == 0)
5269 panic("pmap_unwire: l3 %#jx is missing "
5270 "ATTR_SW_WIRED", (uintmax_t)pmap_load(l3));
5273 * ATTR_SW_WIRED must be cleared atomically. Although
5274 * the pmap lock synchronizes access to ATTR_SW_WIRED,
5275 * the System MMU may write to the entry concurrently.
5277 pmap_clear_bits(l3, ATTR_SW_WIRED);
5278 pmap->pm_stats.wired_count--;
5285 * Copy the range specified by src_addr/len
5286 * from the source map to the range dst_addr/len
5287 * in the destination map.
5289 * This routine is only advisory and need not do anything.
5291 * Because the executable mappings created by this routine are copied,
5292 * it should not have to flush the instruction cache.
5295 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5296 vm_offset_t src_addr)
5298 struct rwlock *lock;
5299 pd_entry_t *l0, *l1, *l2, srcptepaddr;
5300 pt_entry_t *dst_pte, mask, nbits, ptetemp, *src_pte;
5301 vm_offset_t addr, end_addr, va_next;
5302 vm_page_t dst_m, dstmpte, srcmpte;
5304 PMAP_ASSERT_STAGE1(dst_pmap);
5305 PMAP_ASSERT_STAGE1(src_pmap);
5307 if (dst_addr != src_addr)
5309 end_addr = src_addr + len;
5311 if (dst_pmap < src_pmap) {
5312 PMAP_LOCK(dst_pmap);
5313 PMAP_LOCK(src_pmap);
5315 PMAP_LOCK(src_pmap);
5316 PMAP_LOCK(dst_pmap);
5318 for (addr = src_addr; addr < end_addr; addr = va_next) {
5319 l0 = pmap_l0(src_pmap, addr);
5320 if (pmap_load(l0) == 0) {
5321 va_next = (addr + L0_SIZE) & ~L0_OFFSET;
5327 va_next = (addr + L1_SIZE) & ~L1_OFFSET;
5330 l1 = pmap_l0_to_l1(l0, addr);
5331 if (pmap_load(l1) == 0)
5333 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
5334 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
5335 KASSERT(va_next <= end_addr,
5336 ("partial update of non-transparent 1G page "
5337 "l1 %#lx addr %#lx end_addr %#lx va_next %#lx",
5338 pmap_load(l1), addr, end_addr, va_next));
5339 srcptepaddr = pmap_load(l1);
5340 l1 = pmap_l1(dst_pmap, addr);
5342 if (_pmap_alloc_l3(dst_pmap,
5343 pmap_l0_pindex(addr), NULL) == NULL)
5345 l1 = pmap_l1(dst_pmap, addr);
5347 l0 = pmap_l0(dst_pmap, addr);
5348 dst_m = PHYS_TO_VM_PAGE(
5349 PTE_TO_PHYS(pmap_load(l0)));
5352 KASSERT(pmap_load(l1) == 0,
5353 ("1G mapping present in dst pmap "
5354 "l1 %#lx addr %#lx end_addr %#lx va_next %#lx",
5355 pmap_load(l1), addr, end_addr, va_next));
5356 pmap_store(l1, srcptepaddr & ~ATTR_SW_WIRED);
5357 pmap_resident_count_inc(dst_pmap, L1_SIZE / PAGE_SIZE);
5361 va_next = (addr + L2_SIZE) & ~L2_OFFSET;
5364 l2 = pmap_l1_to_l2(l1, addr);
5365 srcptepaddr = pmap_load(l2);
5366 if (srcptepaddr == 0)
5368 if ((srcptepaddr & ATTR_DESCR_MASK) == L2_BLOCK) {
5370 * We can only virtual copy whole superpages.
5372 if ((addr & L2_OFFSET) != 0 ||
5373 addr + L2_SIZE > end_addr)
5375 l2 = pmap_alloc_l2(dst_pmap, addr, &dst_m, NULL);
5378 if (pmap_load(l2) == 0 &&
5379 ((srcptepaddr & ATTR_SW_MANAGED) == 0 ||
5380 pmap_pv_insert_l2(dst_pmap, addr, srcptepaddr,
5381 PMAP_ENTER_NORECLAIM, &lock))) {
5383 * We leave the dirty bit unchanged because
5384 * managed read/write superpage mappings are
5385 * required to be dirty. However, managed
5386 * superpage mappings are not required to
5387 * have their accessed bit set, so we clear
5388 * it because we don't know if this mapping
5391 srcptepaddr &= ~ATTR_SW_WIRED;
5392 if ((srcptepaddr & ATTR_SW_MANAGED) != 0)
5393 srcptepaddr &= ~ATTR_AF;
5394 pmap_store(l2, srcptepaddr);
5395 pmap_resident_count_inc(dst_pmap, L2_SIZE /
5397 atomic_add_long(&pmap_l2_mappings, 1);
5399 pmap_abort_ptp(dst_pmap, addr, dst_m);
5402 KASSERT((srcptepaddr & ATTR_DESCR_MASK) == L2_TABLE,
5403 ("pmap_copy: invalid L2 entry"));
5404 srcmpte = PHYS_TO_VM_PAGE(PTE_TO_PHYS(srcptepaddr));
5405 KASSERT(srcmpte->ref_count > 0,
5406 ("pmap_copy: source page table page is unused"));
5407 if (va_next > end_addr)
5409 src_pte = (pt_entry_t *)PHYS_TO_DMAP(PTE_TO_PHYS(srcptepaddr));
5410 src_pte = &src_pte[pmap_l3_index(addr)];
5412 for (; addr < va_next; addr += PAGE_SIZE, src_pte++) {
5413 ptetemp = pmap_load(src_pte);
5416 * We only virtual copy managed pages.
5418 if ((ptetemp & ATTR_SW_MANAGED) == 0)
5421 if (dstmpte != NULL) {
5422 KASSERT(dstmpte->pindex == pmap_l2_pindex(addr),
5423 ("dstmpte pindex/addr mismatch"));
5424 dstmpte->ref_count++;
5425 } else if ((dstmpte = pmap_alloc_l3(dst_pmap, addr,
5428 dst_pte = (pt_entry_t *)
5429 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5430 dst_pte = &dst_pte[pmap_l3_index(addr)];
5431 if (pmap_load(dst_pte) == 0 &&
5432 pmap_try_insert_pv_entry(dst_pmap, addr,
5433 PHYS_TO_VM_PAGE(PTE_TO_PHYS(ptetemp)), &lock)) {
5435 * Clear the wired, modified, and accessed
5436 * (referenced) bits during the copy.
5438 mask = ATTR_AF | ATTR_SW_WIRED;
5440 if ((ptetemp & ATTR_SW_DBM) != 0)
5441 nbits |= ATTR_S1_AP_RW_BIT;
5442 pmap_store(dst_pte, (ptetemp & ~mask) | nbits);
5443 pmap_resident_count_inc(dst_pmap, 1);
5445 pmap_abort_ptp(dst_pmap, addr, dstmpte);
5448 /* Have we copied all of the valid mappings? */
5449 if (dstmpte->ref_count >= srcmpte->ref_count)
5455 * XXX This barrier may not be needed because the destination pmap is
5462 PMAP_UNLOCK(src_pmap);
5463 PMAP_UNLOCK(dst_pmap);
5467 * pmap_zero_page zeros the specified hardware page by mapping
5468 * the page into KVM and using bzero to clear its contents.
5471 pmap_zero_page(vm_page_t m)
5473 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5475 pagezero((void *)va);
5479 * pmap_zero_page_area zeros the specified hardware page by mapping
5480 * the page into KVM and using bzero to clear its contents.
5482 * off and size may not cover an area beyond a single hardware page.
5485 pmap_zero_page_area(vm_page_t m, int off, int size)
5487 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5489 if (off == 0 && size == PAGE_SIZE)
5490 pagezero((void *)va);
5492 bzero((char *)va + off, size);
5496 * pmap_copy_page copies the specified (machine independent)
5497 * page by mapping the page into virtual memory and using
5498 * bcopy to copy the page, one machine dependent page at a
5502 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5504 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5505 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5507 pagecopy((void *)src, (void *)dst);
5510 int unmapped_buf_allowed = 1;
5513 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5514 vm_offset_t b_offset, int xfersize)
5518 vm_paddr_t p_a, p_b;
5519 vm_offset_t a_pg_offset, b_pg_offset;
5522 while (xfersize > 0) {
5523 a_pg_offset = a_offset & PAGE_MASK;
5524 m_a = ma[a_offset >> PAGE_SHIFT];
5525 p_a = m_a->phys_addr;
5526 b_pg_offset = b_offset & PAGE_MASK;
5527 m_b = mb[b_offset >> PAGE_SHIFT];
5528 p_b = m_b->phys_addr;
5529 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5530 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5531 if (__predict_false(!PHYS_IN_DMAP(p_a))) {
5532 panic("!DMAP a %lx", p_a);
5534 a_cp = (char *)PHYS_TO_DMAP(p_a) + a_pg_offset;
5536 if (__predict_false(!PHYS_IN_DMAP(p_b))) {
5537 panic("!DMAP b %lx", p_b);
5539 b_cp = (char *)PHYS_TO_DMAP(p_b) + b_pg_offset;
5541 bcopy(a_cp, b_cp, cnt);
5549 pmap_quick_enter_page(vm_page_t m)
5552 return (PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)));
5556 pmap_quick_remove_page(vm_offset_t addr)
5561 * Returns true if the pmap's pv is one of the first
5562 * 16 pvs linked to from this page. This count may
5563 * be changed upwards or downwards in the future; it
5564 * is only necessary that true be returned for a small
5565 * subset of pmaps for proper page aging.
5568 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5570 struct md_page *pvh;
5571 struct rwlock *lock;
5576 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5577 ("pmap_page_exists_quick: page %p is not managed", m));
5579 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5581 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5582 if (PV_PMAP(pv) == pmap) {
5590 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5591 pvh = page_to_pvh(m);
5592 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5593 if (PV_PMAP(pv) == pmap) {
5607 * pmap_page_wired_mappings:
5609 * Return the number of managed mappings to the given physical page
5613 pmap_page_wired_mappings(vm_page_t m)
5615 struct rwlock *lock;
5616 struct md_page *pvh;
5620 int count, md_gen, pvh_gen;
5622 if ((m->oflags & VPO_UNMANAGED) != 0)
5624 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5628 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5630 if (!PMAP_TRYLOCK(pmap)) {
5631 md_gen = m->md.pv_gen;
5635 if (md_gen != m->md.pv_gen) {
5640 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
5641 if ((pmap_load(pte) & ATTR_SW_WIRED) != 0)
5645 if ((m->flags & PG_FICTITIOUS) == 0) {
5646 pvh = page_to_pvh(m);
5647 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5649 if (!PMAP_TRYLOCK(pmap)) {
5650 md_gen = m->md.pv_gen;
5651 pvh_gen = pvh->pv_gen;
5655 if (md_gen != m->md.pv_gen ||
5656 pvh_gen != pvh->pv_gen) {
5661 pte = pmap_pte_exists(pmap, pv->pv_va, 2, __func__);
5662 if ((pmap_load(pte) & ATTR_SW_WIRED) != 0)
5672 * Returns true if the given page is mapped individually or as part of
5673 * a 2mpage. Otherwise, returns false.
5676 pmap_page_is_mapped(vm_page_t m)
5678 struct rwlock *lock;
5681 if ((m->oflags & VPO_UNMANAGED) != 0)
5683 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5685 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5686 ((m->flags & PG_FICTITIOUS) == 0 &&
5687 !TAILQ_EMPTY(&page_to_pvh(m)->pv_list));
5693 * Destroy all managed, non-wired mappings in the given user-space
5694 * pmap. This pmap cannot be active on any processor besides the
5697 * This function cannot be applied to the kernel pmap. Moreover, it
5698 * is not intended for general use. It is only to be used during
5699 * process termination. Consequently, it can be implemented in ways
5700 * that make it faster than pmap_remove(). First, it can more quickly
5701 * destroy mappings by iterating over the pmap's collection of PV
5702 * entries, rather than searching the page table. Second, it doesn't
5703 * have to test and clear the page table entries atomically, because
5704 * no processor is currently accessing the user address space. In
5705 * particular, a page table entry's dirty bit won't change state once
5706 * this function starts.
5709 pmap_remove_pages(pmap_t pmap)
5712 pt_entry_t *pte, tpte;
5713 struct spglist free;
5714 struct pv_chunklist free_chunks[PMAP_MEMDOM];
5715 vm_page_t m, ml3, mt;
5717 struct md_page *pvh;
5718 struct pv_chunk *pc, *npc;
5719 struct rwlock *lock;
5721 uint64_t inuse, bitmask;
5722 int allfree, field, i, idx, lvl;
5728 for (i = 0; i < PMAP_MEMDOM; i++)
5729 TAILQ_INIT(&free_chunks[i]);
5732 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5735 for (field = 0; field < _NPCM; field++) {
5736 inuse = ~pc->pc_map[field] & pc_freemask[field];
5737 while (inuse != 0) {
5738 bit = ffsl(inuse) - 1;
5739 bitmask = 1UL << bit;
5740 idx = field * 64 + bit;
5741 pv = &pc->pc_pventry[idx];
5744 pde = pmap_pde(pmap, pv->pv_va, &lvl);
5745 KASSERT(pde != NULL,
5746 ("Attempting to remove an unmapped page"));
5750 pte = pmap_l1_to_l2(pde, pv->pv_va);
5751 tpte = pmap_load(pte);
5752 KASSERT((tpte & ATTR_DESCR_MASK) ==
5754 ("Attempting to remove an invalid "
5755 "block: %lx", tpte));
5758 pte = pmap_l2_to_l3(pde, pv->pv_va);
5759 tpte = pmap_load(pte);
5760 KASSERT((tpte & ATTR_DESCR_MASK) ==
5762 ("Attempting to remove an invalid "
5763 "page: %lx", tpte));
5767 "Invalid page directory level: %d",
5772 * We cannot remove wired pages from a process' mapping at this time
5774 if (tpte & ATTR_SW_WIRED) {
5780 pc->pc_map[field] |= bitmask;
5783 * Because this pmap is not active on other
5784 * processors, the dirty bit cannot have
5785 * changed state since we last loaded pte.
5789 pa = PTE_TO_PHYS(tpte);
5791 m = PHYS_TO_VM_PAGE(pa);
5792 KASSERT(m->phys_addr == pa,
5793 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5794 m, (uintmax_t)m->phys_addr,
5797 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5798 m < &vm_page_array[vm_page_array_size],
5799 ("pmap_remove_pages: bad pte %#jx",
5803 * Update the vm_page_t clean/reference bits.
5805 if (pmap_pte_dirty(pmap, tpte)) {
5808 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
5817 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5821 pmap_resident_count_dec(pmap,
5822 L2_SIZE / PAGE_SIZE);
5823 pvh = page_to_pvh(m);
5824 TAILQ_REMOVE(&pvh->pv_list, pv,pv_next);
5826 if (TAILQ_EMPTY(&pvh->pv_list)) {
5827 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
5828 if ((mt->a.flags & PGA_WRITEABLE) != 0 &&
5829 TAILQ_EMPTY(&mt->md.pv_list))
5830 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5832 ml3 = pmap_remove_pt_page(pmap,
5835 KASSERT(vm_page_any_valid(ml3),
5836 ("pmap_remove_pages: l3 page not promoted"));
5837 pmap_resident_count_dec(pmap,1);
5838 KASSERT(ml3->ref_count == NL3PG,
5839 ("pmap_remove_pages: l3 page ref count error"));
5841 pmap_add_delayed_free_list(ml3,
5846 pmap_resident_count_dec(pmap, 1);
5847 TAILQ_REMOVE(&m->md.pv_list, pv,
5850 if ((m->a.flags & PGA_WRITEABLE) != 0 &&
5851 TAILQ_EMPTY(&m->md.pv_list) &&
5852 (m->flags & PG_FICTITIOUS) == 0) {
5853 pvh = page_to_pvh(m);
5854 if (TAILQ_EMPTY(&pvh->pv_list))
5855 vm_page_aflag_clear(m,
5860 pmap_unuse_pt(pmap, pv->pv_va, pmap_load(pde),
5865 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5866 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5867 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5869 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5870 TAILQ_INSERT_TAIL(&free_chunks[pc_to_domain(pc)], pc,
5876 pmap_invalidate_all(pmap);
5877 free_pv_chunk_batch(free_chunks);
5879 vm_page_free_pages_toq(&free, true);
5883 * This is used to check if a page has been accessed or modified.
5886 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
5888 struct rwlock *lock;
5890 struct md_page *pvh;
5891 pt_entry_t *pte, mask, value;
5893 int md_gen, pvh_gen;
5897 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5900 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5902 PMAP_ASSERT_STAGE1(pmap);
5903 if (!PMAP_TRYLOCK(pmap)) {
5904 md_gen = m->md.pv_gen;
5908 if (md_gen != m->md.pv_gen) {
5913 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
5917 mask |= ATTR_S1_AP_RW_BIT;
5918 value |= ATTR_S1_AP(ATTR_S1_AP_RW);
5921 mask |= ATTR_AF | ATTR_DESCR_MASK;
5922 value |= ATTR_AF | L3_PAGE;
5924 rv = (pmap_load(pte) & mask) == value;
5929 if ((m->flags & PG_FICTITIOUS) == 0) {
5930 pvh = page_to_pvh(m);
5931 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5933 PMAP_ASSERT_STAGE1(pmap);
5934 if (!PMAP_TRYLOCK(pmap)) {
5935 md_gen = m->md.pv_gen;
5936 pvh_gen = pvh->pv_gen;
5940 if (md_gen != m->md.pv_gen ||
5941 pvh_gen != pvh->pv_gen) {
5946 pte = pmap_pte_exists(pmap, pv->pv_va, 2, __func__);
5950 mask |= ATTR_S1_AP_RW_BIT;
5951 value |= ATTR_S1_AP(ATTR_S1_AP_RW);
5954 mask |= ATTR_AF | ATTR_DESCR_MASK;
5955 value |= ATTR_AF | L2_BLOCK;
5957 rv = (pmap_load(pte) & mask) == value;
5971 * Return whether or not the specified physical page was modified
5972 * in any physical maps.
5975 pmap_is_modified(vm_page_t m)
5978 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5979 ("pmap_is_modified: page %p is not managed", m));
5982 * If the page is not busied then this check is racy.
5984 if (!pmap_page_is_write_mapped(m))
5986 return (pmap_page_test_mappings(m, FALSE, TRUE));
5990 * pmap_is_prefaultable:
5992 * Return whether or not the specified virtual address is eligible
5996 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
6004 * Return TRUE if and only if the L3 entry for the specified virtual
6005 * address is allocated but invalid.
6009 pde = pmap_pde(pmap, addr, &lvl);
6010 if (pde != NULL && lvl == 2) {
6011 pte = pmap_l2_to_l3(pde, addr);
6012 rv = pmap_load(pte) == 0;
6019 * pmap_is_referenced:
6021 * Return whether or not the specified physical page was referenced
6022 * in any physical maps.
6025 pmap_is_referenced(vm_page_t m)
6028 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6029 ("pmap_is_referenced: page %p is not managed", m));
6030 return (pmap_page_test_mappings(m, TRUE, FALSE));
6034 * Clear the write and modified bits in each of the given page's mappings.
6037 pmap_remove_write(vm_page_t m)
6039 struct md_page *pvh;
6041 struct rwlock *lock;
6042 pv_entry_t next_pv, pv;
6043 pt_entry_t oldpte, *pte, set, clear, mask, val;
6045 int md_gen, pvh_gen;
6047 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6048 ("pmap_remove_write: page %p is not managed", m));
6049 vm_page_assert_busied(m);
6051 if (!pmap_page_is_write_mapped(m))
6053 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6054 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
6057 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6059 PMAP_ASSERT_STAGE1(pmap);
6060 if (!PMAP_TRYLOCK(pmap)) {
6061 pvh_gen = pvh->pv_gen;
6065 if (pvh_gen != pvh->pv_gen) {
6071 pte = pmap_pte_exists(pmap, va, 2, __func__);
6072 if ((pmap_load(pte) & ATTR_SW_DBM) != 0)
6073 (void)pmap_demote_l2_locked(pmap, pte, va, &lock);
6074 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6075 ("inconsistent pv lock %p %p for page %p",
6076 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6079 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6081 if (!PMAP_TRYLOCK(pmap)) {
6082 pvh_gen = pvh->pv_gen;
6083 md_gen = m->md.pv_gen;
6087 if (pvh_gen != pvh->pv_gen ||
6088 md_gen != m->md.pv_gen) {
6093 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
6094 oldpte = pmap_load(pte);
6095 if ((oldpte & ATTR_SW_DBM) != 0) {
6096 if (pmap->pm_stage == PM_STAGE1) {
6097 set = ATTR_S1_AP_RW_BIT;
6099 mask = ATTR_S1_AP_RW_BIT;
6100 val = ATTR_S1_AP(ATTR_S1_AP_RW);
6103 clear = ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
6104 mask = ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
6105 val = ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
6107 clear |= ATTR_SW_DBM;
6108 while (!atomic_fcmpset_64(pte, &oldpte,
6109 (oldpte | set) & ~clear))
6112 if ((oldpte & mask) == val)
6114 pmap_invalidate_page(pmap, pv->pv_va, true);
6119 vm_page_aflag_clear(m, PGA_WRITEABLE);
6123 * pmap_ts_referenced:
6125 * Return a count of reference bits for a page, clearing those bits.
6126 * It is not necessary for every reference bit to be cleared, but it
6127 * is necessary that 0 only be returned when there are truly no
6128 * reference bits set.
6130 * As an optimization, update the page's dirty field if a modified bit is
6131 * found while counting reference bits. This opportunistic update can be
6132 * performed at low cost and can eliminate the need for some future calls
6133 * to pmap_is_modified(). However, since this function stops after
6134 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
6135 * dirty pages. Those dirty pages will only be detected by a future call
6136 * to pmap_is_modified().
6139 pmap_ts_referenced(vm_page_t m)
6141 struct md_page *pvh;
6144 struct rwlock *lock;
6145 pt_entry_t *pte, tpte;
6148 int cleared, md_gen, not_cleared, pvh_gen;
6149 struct spglist free;
6151 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6152 ("pmap_ts_referenced: page %p is not managed", m));
6155 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
6156 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6160 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6161 goto small_mappings;
6167 if (!PMAP_TRYLOCK(pmap)) {
6168 pvh_gen = pvh->pv_gen;
6172 if (pvh_gen != pvh->pv_gen) {
6178 pte = pmap_pte_exists(pmap, va, 2, __func__);
6179 tpte = pmap_load(pte);
6180 if (pmap_pte_dirty(pmap, tpte)) {
6182 * Although "tpte" is mapping a 2MB page, because
6183 * this function is called at a 4KB page granularity,
6184 * we only update the 4KB page under test.
6188 if ((tpte & ATTR_AF) != 0) {
6189 pa = VM_PAGE_TO_PHYS(m);
6192 * Since this reference bit is shared by 512 4KB pages,
6193 * it should not be cleared every time it is tested.
6194 * Apply a simple "hash" function on the physical page
6195 * number, the virtual superpage number, and the pmap
6196 * address to select one 4KB page out of the 512 on
6197 * which testing the reference bit will result in
6198 * clearing that reference bit. This function is
6199 * designed to avoid the selection of the same 4KB page
6200 * for every 2MB page mapping.
6202 * On demotion, a mapping that hasn't been referenced
6203 * is simply destroyed. To avoid the possibility of a
6204 * subsequent page fault on a demoted wired mapping,
6205 * always leave its reference bit set. Moreover,
6206 * since the superpage is wired, the current state of
6207 * its reference bit won't affect page replacement.
6209 if ((((pa >> PAGE_SHIFT) ^ (va >> L2_SHIFT) ^
6210 (uintptr_t)pmap) & (Ln_ENTRIES - 1)) == 0 &&
6211 (tpte & ATTR_SW_WIRED) == 0) {
6212 pmap_clear_bits(pte, ATTR_AF);
6213 pmap_invalidate_page(pmap, va, true);
6219 /* Rotate the PV list if it has more than one entry. */
6220 if (TAILQ_NEXT(pv, pv_next) != NULL) {
6221 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6222 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6225 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6227 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6229 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6236 if (!PMAP_TRYLOCK(pmap)) {
6237 pvh_gen = pvh->pv_gen;
6238 md_gen = m->md.pv_gen;
6242 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6247 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
6248 tpte = pmap_load(pte);
6249 if (pmap_pte_dirty(pmap, tpte))
6251 if ((tpte & ATTR_AF) != 0) {
6252 if ((tpte & ATTR_SW_WIRED) == 0) {
6253 pmap_clear_bits(pte, ATTR_AF);
6254 pmap_invalidate_page(pmap, pv->pv_va, true);
6260 /* Rotate the PV list if it has more than one entry. */
6261 if (TAILQ_NEXT(pv, pv_next) != NULL) {
6262 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6263 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6266 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6267 not_cleared < PMAP_TS_REFERENCED_MAX);
6270 vm_page_free_pages_toq(&free, true);
6271 return (cleared + not_cleared);
6275 * Apply the given advice to the specified range of addresses within the
6276 * given pmap. Depending on the advice, clear the referenced and/or
6277 * modified flags in each mapping and set the mapped page's dirty field.
6280 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6282 struct rwlock *lock;
6283 vm_offset_t va, va_next;
6285 pd_entry_t *l0, *l1, *l2, oldl2;
6286 pt_entry_t *l3, oldl3;
6288 PMAP_ASSERT_STAGE1(pmap);
6290 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6294 for (; sva < eva; sva = va_next) {
6295 l0 = pmap_l0(pmap, sva);
6296 if (pmap_load(l0) == 0) {
6297 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
6303 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
6306 l1 = pmap_l0_to_l1(l0, sva);
6307 if (pmap_load(l1) == 0)
6309 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
6310 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
6314 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
6317 l2 = pmap_l1_to_l2(l1, sva);
6318 oldl2 = pmap_load(l2);
6321 if ((oldl2 & ATTR_DESCR_MASK) == L2_BLOCK) {
6322 if ((oldl2 & ATTR_SW_MANAGED) == 0)
6325 if (!pmap_demote_l2_locked(pmap, l2, sva, &lock)) {
6330 * The 2MB page mapping was destroyed.
6336 * Unless the page mappings are wired, remove the
6337 * mapping to a single page so that a subsequent
6338 * access may repromote. Choosing the last page
6339 * within the address range [sva, min(va_next, eva))
6340 * generally results in more repromotions. Since the
6341 * underlying page table page is fully populated, this
6342 * removal never frees a page table page.
6344 if ((oldl2 & ATTR_SW_WIRED) == 0) {
6350 ("pmap_advise: no address gap"));
6351 l3 = pmap_l2_to_l3(l2, va);
6352 KASSERT(pmap_load(l3) != 0,
6353 ("pmap_advise: invalid PTE"));
6354 pmap_remove_l3(pmap, l3, va, pmap_load(l2),
6360 KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
6361 ("pmap_advise: invalid L2 entry after demotion"));
6365 for (l3 = pmap_l2_to_l3(l2, sva); sva != va_next; l3++,
6367 oldl3 = pmap_load(l3);
6368 if ((oldl3 & (ATTR_SW_MANAGED | ATTR_DESCR_MASK)) !=
6369 (ATTR_SW_MANAGED | L3_PAGE))
6371 else if (pmap_pte_dirty(pmap, oldl3)) {
6372 if (advice == MADV_DONTNEED) {
6374 * Future calls to pmap_is_modified()
6375 * can be avoided by making the page
6378 m = PHYS_TO_VM_PAGE(PTE_TO_PHYS(oldl3));
6381 while (!atomic_fcmpset_long(l3, &oldl3,
6382 (oldl3 & ~ATTR_AF) |
6383 ATTR_S1_AP(ATTR_S1_AP_RO)))
6385 } else if ((oldl3 & ATTR_AF) != 0)
6386 pmap_clear_bits(l3, ATTR_AF);
6393 if (va != va_next) {
6394 pmap_s1_invalidate_range(pmap, va, sva, true);
6399 pmap_s1_invalidate_range(pmap, va, sva, true);
6405 * Clear the modify bits on the specified physical page.
6408 pmap_clear_modify(vm_page_t m)
6410 struct md_page *pvh;
6411 struct rwlock *lock;
6413 pv_entry_t next_pv, pv;
6414 pd_entry_t *l2, oldl2;
6415 pt_entry_t *l3, oldl3;
6417 int md_gen, pvh_gen;
6419 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6420 ("pmap_clear_modify: page %p is not managed", m));
6421 vm_page_assert_busied(m);
6423 if (!pmap_page_is_write_mapped(m))
6425 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
6426 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6429 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6431 PMAP_ASSERT_STAGE1(pmap);
6432 if (!PMAP_TRYLOCK(pmap)) {
6433 pvh_gen = pvh->pv_gen;
6437 if (pvh_gen != pvh->pv_gen) {
6443 l2 = pmap_l2(pmap, va);
6444 oldl2 = pmap_load(l2);
6445 /* If oldl2 has ATTR_SW_DBM set, then it is also dirty. */
6446 if ((oldl2 & ATTR_SW_DBM) != 0 &&
6447 pmap_demote_l2_locked(pmap, l2, va, &lock) &&
6448 (oldl2 & ATTR_SW_WIRED) == 0) {
6450 * Write protect the mapping to a single page so that
6451 * a subsequent write access may repromote.
6453 va += VM_PAGE_TO_PHYS(m) - PTE_TO_PHYS(oldl2);
6454 l3 = pmap_l2_to_l3(l2, va);
6455 oldl3 = pmap_load(l3);
6456 while (!atomic_fcmpset_long(l3, &oldl3,
6457 (oldl3 & ~ATTR_SW_DBM) | ATTR_S1_AP(ATTR_S1_AP_RO)))
6460 pmap_s1_invalidate_page(pmap, va, true);
6464 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6466 PMAP_ASSERT_STAGE1(pmap);
6467 if (!PMAP_TRYLOCK(pmap)) {
6468 md_gen = m->md.pv_gen;
6469 pvh_gen = pvh->pv_gen;
6473 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6478 l2 = pmap_l2(pmap, pv->pv_va);
6479 l3 = pmap_l2_to_l3(l2, pv->pv_va);
6480 oldl3 = pmap_load(l3);
6481 if ((oldl3 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) == ATTR_SW_DBM){
6482 pmap_set_bits(l3, ATTR_S1_AP(ATTR_S1_AP_RO));
6483 pmap_s1_invalidate_page(pmap, pv->pv_va, true);
6491 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6493 struct pmap_preinit_mapping *ppim;
6494 vm_offset_t va, offset;
6495 pd_entry_t old_l2e, *pde;
6497 int i, lvl, l2_blocks, free_l2_count, start_idx;
6499 if (!vm_initialized) {
6501 * No L3 ptables so map entire L2 blocks where start VA is:
6502 * preinit_map_va + start_idx * L2_SIZE
6503 * There may be duplicate mappings (multiple VA -> same PA) but
6504 * ARM64 dcache is always PIPT so that's acceptable.
6509 /* Calculate how many L2 blocks are needed for the mapping */
6510 l2_blocks = (roundup2(pa + size, L2_SIZE) -
6511 rounddown2(pa, L2_SIZE)) >> L2_SHIFT;
6513 offset = pa & L2_OFFSET;
6515 if (preinit_map_va == 0)
6518 /* Map 2MiB L2 blocks from reserved VA space */
6522 /* Find enough free contiguous VA space */
6523 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6524 ppim = pmap_preinit_mapping + i;
6525 if (free_l2_count > 0 && ppim->pa != 0) {
6526 /* Not enough space here */
6532 if (ppim->pa == 0) {
6534 if (start_idx == -1)
6537 if (free_l2_count == l2_blocks)
6541 if (free_l2_count != l2_blocks)
6542 panic("%s: too many preinit mappings", __func__);
6544 va = preinit_map_va + (start_idx * L2_SIZE);
6545 for (i = start_idx; i < start_idx + l2_blocks; i++) {
6546 /* Mark entries as allocated */
6547 ppim = pmap_preinit_mapping + i;
6549 ppim->va = va + offset;
6554 pa = rounddown2(pa, L2_SIZE);
6556 for (i = 0; i < l2_blocks; i++) {
6557 pde = pmap_pde(kernel_pmap, va, &lvl);
6558 KASSERT(pde != NULL,
6559 ("pmap_mapbios: Invalid page entry, va: 0x%lx",
6562 ("pmap_mapbios: Invalid level %d", lvl));
6564 /* Insert L2_BLOCK */
6565 l2 = pmap_l1_to_l2(pde, va);
6566 old_l2e |= pmap_load_store(l2,
6567 PHYS_TO_PTE(pa) | ATTR_DEFAULT | ATTR_S1_XN |
6568 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) | L2_BLOCK);
6573 if ((old_l2e & ATTR_DESCR_VALID) != 0)
6574 pmap_s1_invalidate_all(kernel_pmap);
6577 * Because the old entries were invalid and the new
6578 * mappings are not executable, an isb is not required.
6583 va = preinit_map_va + (start_idx * L2_SIZE);
6586 /* kva_alloc may be used to map the pages */
6587 offset = pa & PAGE_MASK;
6588 size = round_page(offset + size);
6590 va = kva_alloc(size);
6592 panic("%s: Couldn't allocate KVA", __func__);
6594 pde = pmap_pde(kernel_pmap, va, &lvl);
6595 KASSERT(lvl == 2, ("pmap_mapbios: Invalid level %d", lvl));
6597 /* L3 table is linked */
6598 va = trunc_page(va);
6599 pa = trunc_page(pa);
6600 pmap_kenter(va, size, pa, memory_mapping_mode(pa));
6603 return ((void *)(va + offset));
6607 pmap_unmapbios(void *p, vm_size_t size)
6609 struct pmap_preinit_mapping *ppim;
6610 vm_offset_t offset, va, va_trunc;
6613 int i, lvl, l2_blocks, block;
6616 va = (vm_offset_t)p;
6618 (roundup2(va + size, L2_SIZE) - rounddown2(va, L2_SIZE)) >> L2_SHIFT;
6619 KASSERT(l2_blocks > 0, ("pmap_unmapbios: invalid size %lx", size));
6621 /* Remove preinit mapping */
6622 preinit_map = false;
6624 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6625 ppim = pmap_preinit_mapping + i;
6626 if (ppim->va == va) {
6627 KASSERT(ppim->size == size,
6628 ("pmap_unmapbios: size mismatch"));
6633 offset = block * L2_SIZE;
6634 va_trunc = rounddown2(va, L2_SIZE) + offset;
6636 /* Remove L2_BLOCK */
6637 pde = pmap_pde(kernel_pmap, va_trunc, &lvl);
6638 KASSERT(pde != NULL,
6639 ("pmap_unmapbios: Invalid page entry, va: 0x%lx",
6641 l2 = pmap_l1_to_l2(pde, va_trunc);
6644 if (block == (l2_blocks - 1))
6650 pmap_s1_invalidate_all(kernel_pmap);
6654 /* Unmap the pages reserved with kva_alloc. */
6655 if (vm_initialized) {
6656 offset = va & PAGE_MASK;
6657 size = round_page(offset + size);
6658 va = trunc_page(va);
6660 /* Unmap and invalidate the pages */
6661 pmap_kremove_device(va, size);
6668 * Sets the memory attribute for the specified page.
6671 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6674 m->md.pv_memattr = ma;
6677 * If "m" is a normal page, update its direct mapping. This update
6678 * can be relied upon to perform any cache operations that are
6679 * required for data coherence.
6681 if ((m->flags & PG_FICTITIOUS) == 0 &&
6682 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6683 m->md.pv_memattr) != 0)
6684 panic("memory attribute change on the direct map failed");
6688 * Changes the specified virtual address range's memory type to that given by
6689 * the parameter "mode". The specified virtual address range must be
6690 * completely contained within either the direct map or the kernel map. If
6691 * the virtual address range is contained within the kernel map, then the
6692 * memory type for each of the corresponding ranges of the direct map is also
6693 * changed. (The corresponding ranges of the direct map are those ranges that
6694 * map the same physical pages as the specified virtual address range.) These
6695 * changes to the direct map are necessary because Intel describes the
6696 * behavior of their processors as "undefined" if two or more mappings to the
6697 * same physical page have different memory types.
6699 * Returns zero if the change completed successfully, and either EINVAL or
6700 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6701 * of the virtual address range was not mapped, and ENOMEM is returned if
6702 * there was insufficient memory available to complete the change. In the
6703 * latter case, the memory type may have been changed on some part of the
6704 * virtual address range or the direct map.
6707 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6711 PMAP_LOCK(kernel_pmap);
6712 error = pmap_change_props_locked(va, size, PROT_NONE, mode, false);
6713 PMAP_UNLOCK(kernel_pmap);
6718 * Changes the specified virtual address range's protections to those
6719 * specified by "prot". Like pmap_change_attr(), protections for aliases
6720 * in the direct map are updated as well. Protections on aliasing mappings may
6721 * be a subset of the requested protections; for example, mappings in the direct
6722 * map are never executable.
6725 pmap_change_prot(vm_offset_t va, vm_size_t size, vm_prot_t prot)
6729 /* Only supported within the kernel map. */
6730 if (va < VM_MIN_KERNEL_ADDRESS)
6733 PMAP_LOCK(kernel_pmap);
6734 error = pmap_change_props_locked(va, size, prot, -1, false);
6735 PMAP_UNLOCK(kernel_pmap);
6740 pmap_change_props_locked(vm_offset_t va, vm_size_t size, vm_prot_t prot,
6741 int mode, bool skip_unmapped)
6743 vm_offset_t base, offset, tmpva;
6746 pt_entry_t pte, *ptep, *newpte;
6747 pt_entry_t bits, mask;
6750 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6751 base = trunc_page(va);
6752 offset = va & PAGE_MASK;
6753 size = round_page(offset + size);
6755 if (!VIRT_IN_DMAP(base) &&
6756 !(base >= VM_MIN_KERNEL_ADDRESS && base < VM_MAX_KERNEL_ADDRESS))
6762 bits = ATTR_S1_IDX(mode);
6763 mask = ATTR_S1_IDX_MASK;
6764 if (mode == VM_MEMATTR_DEVICE) {
6769 if (prot != VM_PROT_NONE) {
6770 /* Don't mark the DMAP as executable. It never is on arm64. */
6771 if (VIRT_IN_DMAP(base)) {
6772 prot &= ~VM_PROT_EXECUTE;
6774 * XXX Mark the DMAP as writable for now. We rely
6775 * on this in ddb & dtrace to insert breakpoint
6778 prot |= VM_PROT_WRITE;
6781 if ((prot & VM_PROT_WRITE) == 0) {
6782 bits |= ATTR_S1_AP(ATTR_S1_AP_RO);
6784 if ((prot & VM_PROT_EXECUTE) == 0) {
6785 bits |= ATTR_S1_PXN;
6787 bits |= ATTR_S1_UXN;
6788 mask |= ATTR_S1_AP_MASK | ATTR_S1_XN;
6791 for (tmpva = base; tmpva < base + size; ) {
6792 ptep = pmap_pte(kernel_pmap, tmpva, &lvl);
6793 if (ptep == NULL && !skip_unmapped) {
6795 } else if ((ptep == NULL && skip_unmapped) ||
6796 (pmap_load(ptep) & mask) == bits) {
6798 * We already have the correct attribute or there
6799 * is no memory mapped at this address and we are
6800 * skipping unmapped memory.
6804 panic("Invalid DMAP table level: %d\n", lvl);
6806 tmpva = (tmpva & ~L1_OFFSET) + L1_SIZE;
6809 tmpva = (tmpva & ~L2_OFFSET) + L2_SIZE;
6816 /* We can't demote/promote this entry */
6817 MPASS((pmap_load(ptep) & ATTR_SW_NO_PROMOTE) == 0);
6820 * Split the entry to an level 3 table, then
6821 * set the new attribute.
6825 panic("Invalid DMAP table level: %d\n", lvl);
6827 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
6828 if ((tmpva & L1_OFFSET) == 0 &&
6829 (base + size - tmpva) >= L1_SIZE) {
6833 newpte = pmap_demote_l1(kernel_pmap, ptep,
6834 tmpva & ~L1_OFFSET);
6837 ptep = pmap_l1_to_l2(ptep, tmpva);
6840 if ((tmpva & L2_OFFSET) == 0 &&
6841 (base + size - tmpva) >= L2_SIZE) {
6845 newpte = pmap_demote_l2(kernel_pmap, ptep,
6849 ptep = pmap_l2_to_l3(ptep, tmpva);
6852 pte_size = PAGE_SIZE;
6856 /* Update the entry */
6857 pte = pmap_load(ptep);
6861 pmap_update_entry(kernel_pmap, ptep, pte, tmpva,
6864 pa = PTE_TO_PHYS(pte);
6865 if (!VIRT_IN_DMAP(tmpva) && PHYS_IN_DMAP(pa)) {
6867 * Keep the DMAP memory in sync.
6869 rv = pmap_change_props_locked(
6870 PHYS_TO_DMAP(pa), pte_size,
6877 * If moving to a non-cacheable entry flush
6880 if (mode == VM_MEMATTR_UNCACHEABLE)
6881 cpu_dcache_wbinv_range(tmpva, pte_size);
6890 * Create an L2 table to map all addresses within an L1 mapping.
6893 pmap_demote_l1(pmap_t pmap, pt_entry_t *l1, vm_offset_t va)
6895 pt_entry_t *l2, newl2, oldl1;
6897 vm_paddr_t l2phys, phys;
6901 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6902 oldl1 = pmap_load(l1);
6903 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
6904 KASSERT((oldl1 & ATTR_DESCR_MASK) == L1_BLOCK,
6905 ("pmap_demote_l1: Demoting a non-block entry"));
6906 KASSERT((va & L1_OFFSET) == 0,
6907 ("pmap_demote_l1: Invalid virtual address %#lx", va));
6908 KASSERT((oldl1 & ATTR_SW_MANAGED) == 0,
6909 ("pmap_demote_l1: Level 1 table shouldn't be managed"));
6910 KASSERT((oldl1 & ATTR_SW_NO_PROMOTE) == 0,
6911 ("pmap_demote_l1: Demoting entry with no-demote flag set"));
6914 if (va <= (vm_offset_t)l1 && va + L1_SIZE > (vm_offset_t)l1) {
6915 tmpl1 = kva_alloc(PAGE_SIZE);
6920 if ((ml2 = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED)) ==
6922 CTR2(KTR_PMAP, "pmap_demote_l1: failure for va %#lx"
6923 " in pmap %p", va, pmap);
6928 l2phys = VM_PAGE_TO_PHYS(ml2);
6929 l2 = (pt_entry_t *)PHYS_TO_DMAP(l2phys);
6931 /* Address the range points at */
6932 phys = PTE_TO_PHYS(oldl1);
6933 /* The attributed from the old l1 table to be copied */
6934 newl2 = oldl1 & ATTR_MASK;
6936 /* Create the new entries */
6937 for (i = 0; i < Ln_ENTRIES; i++) {
6938 l2[i] = newl2 | phys;
6941 KASSERT(l2[0] == ((oldl1 & ~ATTR_DESCR_MASK) | L2_BLOCK),
6942 ("Invalid l2 page (%lx != %lx)", l2[0],
6943 (oldl1 & ~ATTR_DESCR_MASK) | L2_BLOCK));
6946 pmap_kenter(tmpl1, PAGE_SIZE,
6947 DMAP_TO_PHYS((vm_offset_t)l1) & ~L3_OFFSET,
6948 VM_MEMATTR_WRITE_BACK);
6949 l1 = (pt_entry_t *)(tmpl1 + ((vm_offset_t)l1 & PAGE_MASK));
6952 pmap_update_entry(pmap, l1, l2phys | L1_TABLE, va, PAGE_SIZE);
6956 pmap_kremove(tmpl1);
6957 kva_free(tmpl1, PAGE_SIZE);
6964 pmap_fill_l3(pt_entry_t *firstl3, pt_entry_t newl3)
6968 for (l3 = firstl3; l3 - firstl3 < Ln_ENTRIES; l3++) {
6975 pmap_demote_l2_check(pt_entry_t *firstl3p __unused, pt_entry_t newl3e __unused)
6979 pt_entry_t *xl3p, *yl3p;
6981 for (xl3p = firstl3p; xl3p < firstl3p + Ln_ENTRIES;
6982 xl3p++, newl3e += PAGE_SIZE) {
6983 if (PTE_TO_PHYS(pmap_load(xl3p)) != PTE_TO_PHYS(newl3e)) {
6984 printf("pmap_demote_l2: xl3e %zd and newl3e map "
6985 "different pages: found %#lx, expected %#lx\n",
6986 xl3p - firstl3p, pmap_load(xl3p), newl3e);
6987 printf("page table dump\n");
6988 for (yl3p = firstl3p; yl3p < firstl3p + Ln_ENTRIES;
6990 printf("%zd %#lx\n", yl3p - firstl3p,
6997 KASSERT(PTE_TO_PHYS(pmap_load(firstl3p)) == PTE_TO_PHYS(newl3e),
6998 ("pmap_demote_l2: firstl3 and newl3e map different physical"
7005 pmap_demote_l2_abort(pmap_t pmap, vm_offset_t va, pt_entry_t *l2,
7006 struct rwlock **lockp)
7008 struct spglist free;
7011 (void)pmap_remove_l2(pmap, l2, va, pmap_load(pmap_l1(pmap, va)), &free,
7013 vm_page_free_pages_toq(&free, true);
7017 * Create an L3 table to map all addresses within an L2 mapping.
7020 pmap_demote_l2_locked(pmap_t pmap, pt_entry_t *l2, vm_offset_t va,
7021 struct rwlock **lockp)
7023 pt_entry_t *l3, newl3, oldl2;
7028 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7029 PMAP_ASSERT_STAGE1(pmap);
7030 KASSERT(ADDR_IS_CANONICAL(va),
7031 ("%s: Address not in canonical form: %lx", __func__, va));
7034 oldl2 = pmap_load(l2);
7035 KASSERT((oldl2 & ATTR_DESCR_MASK) == L2_BLOCK,
7036 ("pmap_demote_l2: Demoting a non-block entry"));
7037 KASSERT((oldl2 & ATTR_SW_NO_PROMOTE) == 0,
7038 ("pmap_demote_l2: Demoting entry with no-demote flag set"));
7042 if (va <= (vm_offset_t)l2 && va + L2_SIZE > (vm_offset_t)l2) {
7043 tmpl2 = kva_alloc(PAGE_SIZE);
7049 * Invalidate the 2MB page mapping and return "failure" if the
7050 * mapping was never accessed.
7052 if ((oldl2 & ATTR_AF) == 0) {
7053 KASSERT((oldl2 & ATTR_SW_WIRED) == 0,
7054 ("pmap_demote_l2: a wired mapping is missing ATTR_AF"));
7055 pmap_demote_l2_abort(pmap, va, l2, lockp);
7056 CTR2(KTR_PMAP, "pmap_demote_l2: failure for va %#lx in pmap %p",
7061 if ((ml3 = pmap_remove_pt_page(pmap, va)) == NULL) {
7062 KASSERT((oldl2 & ATTR_SW_WIRED) == 0,
7063 ("pmap_demote_l2: page table page for a wired mapping"
7067 * If the page table page is missing and the mapping
7068 * is for a kernel address, the mapping must belong to
7069 * either the direct map or the early kernel memory.
7070 * Page table pages are preallocated for every other
7071 * part of the kernel address space, so the direct map
7072 * region and early kernel memory are the only parts of the
7073 * kernel address space that must be handled here.
7075 KASSERT(!ADDR_IS_KERNEL(va) || VIRT_IN_DMAP(va) ||
7076 (va >= VM_MIN_KERNEL_ADDRESS && va < kernel_vm_end),
7077 ("pmap_demote_l2: No saved mpte for va %#lx", va));
7080 * If the 2MB page mapping belongs to the direct map
7081 * region of the kernel's address space, then the page
7082 * allocation request specifies the highest possible
7083 * priority (VM_ALLOC_INTERRUPT). Otherwise, the
7084 * priority is normal.
7086 ml3 = vm_page_alloc_noobj(
7087 (VIRT_IN_DMAP(va) ? VM_ALLOC_INTERRUPT : 0) |
7091 * If the allocation of the new page table page fails,
7092 * invalidate the 2MB page mapping and return "failure".
7095 pmap_demote_l2_abort(pmap, va, l2, lockp);
7096 CTR2(KTR_PMAP, "pmap_demote_l2: failure for va %#lx"
7097 " in pmap %p", va, pmap);
7100 ml3->pindex = pmap_l2_pindex(va);
7102 if (!ADDR_IS_KERNEL(va)) {
7103 ml3->ref_count = NL3PG;
7104 pmap_resident_count_inc(pmap, 1);
7107 l3phys = VM_PAGE_TO_PHYS(ml3);
7108 l3 = (pt_entry_t *)PHYS_TO_DMAP(l3phys);
7109 newl3 = (oldl2 & ~ATTR_DESCR_MASK) | L3_PAGE;
7110 KASSERT((oldl2 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) !=
7111 (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM),
7112 ("pmap_demote_l2: L2 entry is writeable but not dirty"));
7115 * If the PTP is not leftover from an earlier promotion or it does not
7116 * have ATTR_AF set in every L3E, then fill it. The new L3Es will all
7119 * When pmap_update_entry() clears the old L2 mapping, it (indirectly)
7120 * performs a dsb(). That dsb() ensures that the stores for filling
7121 * "l3" are visible before "l3" is added to the page table.
7123 if (!vm_page_all_valid(ml3))
7124 pmap_fill_l3(l3, newl3);
7126 pmap_demote_l2_check(l3, newl3);
7129 * If the mapping has changed attributes, update the L3Es.
7131 if ((pmap_load(l3) & (ATTR_MASK & ~ATTR_AF)) != (newl3 & (ATTR_MASK &
7133 pmap_fill_l3(l3, newl3);
7136 * Map the temporary page so we don't lose access to the l2 table.
7139 pmap_kenter(tmpl2, PAGE_SIZE,
7140 DMAP_TO_PHYS((vm_offset_t)l2) & ~L3_OFFSET,
7141 VM_MEMATTR_WRITE_BACK);
7142 l2 = (pt_entry_t *)(tmpl2 + ((vm_offset_t)l2 & PAGE_MASK));
7146 * The spare PV entries must be reserved prior to demoting the
7147 * mapping, that is, prior to changing the PDE. Otherwise, the state
7148 * of the L2 and the PV lists will be inconsistent, which can result
7149 * in reclaim_pv_chunk() attempting to remove a PV entry from the
7150 * wrong PV list and pmap_pv_demote_l2() failing to find the expected
7151 * PV entry for the 2MB page mapping that is being demoted.
7153 if ((oldl2 & ATTR_SW_MANAGED) != 0)
7154 reserve_pv_entries(pmap, Ln_ENTRIES - 1, lockp);
7157 * Pass PAGE_SIZE so that a single TLB invalidation is performed on
7158 * the 2MB page mapping.
7160 pmap_update_entry(pmap, l2, l3phys | L2_TABLE, va, PAGE_SIZE);
7163 * Demote the PV entry.
7165 if ((oldl2 & ATTR_SW_MANAGED) != 0)
7166 pmap_pv_demote_l2(pmap, va, PTE_TO_PHYS(oldl2), lockp);
7168 atomic_add_long(&pmap_l2_demotions, 1);
7169 CTR3(KTR_PMAP, "pmap_demote_l2: success for va %#lx"
7170 " in pmap %p %lx", va, pmap, l3[0]);
7174 pmap_kremove(tmpl2);
7175 kva_free(tmpl2, PAGE_SIZE);
7183 pmap_demote_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va)
7185 struct rwlock *lock;
7189 l3 = pmap_demote_l2_locked(pmap, l2, va, &lock);
7196 * Perform the pmap work for mincore(2). If the page is not both referenced and
7197 * modified by this pmap, returns its physical address so that the caller can
7198 * find other mappings.
7201 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
7203 pt_entry_t *pte, tpte;
7204 vm_paddr_t mask, pa;
7208 PMAP_ASSERT_STAGE1(pmap);
7210 pte = pmap_pte(pmap, addr, &lvl);
7212 tpte = pmap_load(pte);
7225 panic("pmap_mincore: invalid level %d", lvl);
7228 managed = (tpte & ATTR_SW_MANAGED) != 0;
7229 val = MINCORE_INCORE;
7231 val |= MINCORE_PSIND(3 - lvl);
7232 if ((managed && pmap_pte_dirty(pmap, tpte)) || (!managed &&
7233 (tpte & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP(ATTR_S1_AP_RW)))
7234 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
7235 if ((tpte & ATTR_AF) == ATTR_AF)
7236 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
7238 pa = PTE_TO_PHYS(tpte) | (addr & mask);
7244 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
7245 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) && managed) {
7253 * Garbage collect every ASID that is neither active on a processor nor
7257 pmap_reset_asid_set(pmap_t pmap)
7260 int asid, cpuid, epoch;
7261 struct asid_set *set;
7262 enum pmap_stage stage;
7264 set = pmap->pm_asid_set;
7265 stage = pmap->pm_stage;
7267 set = pmap->pm_asid_set;
7268 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
7269 mtx_assert(&set->asid_set_mutex, MA_OWNED);
7272 * Ensure that the store to asid_epoch is globally visible before the
7273 * loads from pc_curpmap are performed.
7275 epoch = set->asid_epoch + 1;
7276 if (epoch == INT_MAX)
7278 set->asid_epoch = epoch;
7280 if (stage == PM_STAGE1) {
7281 __asm __volatile("tlbi vmalle1is");
7283 KASSERT(pmap_clean_stage2_tlbi != NULL,
7284 ("%s: Unset stage 2 tlb invalidation callback\n",
7286 pmap_clean_stage2_tlbi();
7289 bit_nclear(set->asid_set, ASID_FIRST_AVAILABLE,
7290 set->asid_set_size - 1);
7291 CPU_FOREACH(cpuid) {
7292 if (cpuid == curcpu)
7294 if (stage == PM_STAGE1) {
7295 curpmap = pcpu_find(cpuid)->pc_curpmap;
7296 PMAP_ASSERT_STAGE1(pmap);
7298 curpmap = pcpu_find(cpuid)->pc_curvmpmap;
7299 if (curpmap == NULL)
7301 PMAP_ASSERT_STAGE2(pmap);
7303 KASSERT(curpmap->pm_asid_set == set, ("Incorrect set"));
7304 asid = COOKIE_TO_ASID(curpmap->pm_cookie);
7307 bit_set(set->asid_set, asid);
7308 curpmap->pm_cookie = COOKIE_FROM(asid, epoch);
7313 * Allocate a new ASID for the specified pmap.
7316 pmap_alloc_asid(pmap_t pmap)
7318 struct asid_set *set;
7321 set = pmap->pm_asid_set;
7322 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
7324 mtx_lock_spin(&set->asid_set_mutex);
7327 * While this processor was waiting to acquire the asid set mutex,
7328 * pmap_reset_asid_set() running on another processor might have
7329 * updated this pmap's cookie to the current epoch. In which case, we
7330 * don't need to allocate a new ASID.
7332 if (COOKIE_TO_EPOCH(pmap->pm_cookie) == set->asid_epoch)
7335 bit_ffc_at(set->asid_set, set->asid_next, set->asid_set_size,
7337 if (new_asid == -1) {
7338 bit_ffc_at(set->asid_set, ASID_FIRST_AVAILABLE,
7339 set->asid_next, &new_asid);
7340 if (new_asid == -1) {
7341 pmap_reset_asid_set(pmap);
7342 bit_ffc_at(set->asid_set, ASID_FIRST_AVAILABLE,
7343 set->asid_set_size, &new_asid);
7344 KASSERT(new_asid != -1, ("ASID allocation failure"));
7347 bit_set(set->asid_set, new_asid);
7348 set->asid_next = new_asid + 1;
7349 pmap->pm_cookie = COOKIE_FROM(new_asid, set->asid_epoch);
7351 mtx_unlock_spin(&set->asid_set_mutex);
7354 static uint64_t __read_mostly ttbr_flags;
7357 * Compute the value that should be stored in ttbr0 to activate the specified
7358 * pmap. This value may change from time to time.
7361 pmap_to_ttbr0(pmap_t pmap)
7365 ttbr = pmap->pm_ttbr;
7366 ttbr |= ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
7373 pmap_set_cnp(void *arg)
7375 uint64_t ttbr0, ttbr1;
7378 cpuid = *(u_int *)arg;
7379 if (cpuid == curcpu) {
7381 * Set the flags while all CPUs are handling the
7382 * smp_rendezvous so will not call pmap_to_ttbr0. Any calls
7383 * to pmap_to_ttbr0 after this will have the CnP flag set.
7384 * The dsb after invalidating the TLB will act as a barrier
7385 * to ensure all CPUs can observe this change.
7387 ttbr_flags |= TTBR_CnP;
7390 ttbr0 = READ_SPECIALREG(ttbr0_el1);
7393 ttbr1 = READ_SPECIALREG(ttbr1_el1);
7396 /* Update ttbr{0,1}_el1 with the CnP flag */
7397 WRITE_SPECIALREG(ttbr0_el1, ttbr0);
7398 WRITE_SPECIALREG(ttbr1_el1, ttbr1);
7400 __asm __volatile("tlbi vmalle1is");
7406 * Defer enabling CnP until we have read the ID registers to know if it's
7407 * supported on all CPUs.
7410 pmap_init_cnp(void *dummy __unused)
7415 if (!get_kernel_reg(ID_AA64MMFR2_EL1, ®))
7418 if (ID_AA64MMFR2_CnP_VAL(reg) != ID_AA64MMFR2_CnP_NONE) {
7420 printf("Enabling CnP\n");
7422 smp_rendezvous(NULL, pmap_set_cnp, NULL, &cpuid);
7426 SYSINIT(pmap_init_cnp, SI_SUB_SMP, SI_ORDER_ANY, pmap_init_cnp, NULL);
7429 pmap_activate_int(pmap_t pmap)
7431 struct asid_set *set;
7434 KASSERT(PCPU_GET(curpmap) != NULL, ("no active pmap"));
7435 KASSERT(pmap != kernel_pmap, ("kernel pmap activation"));
7437 if ((pmap->pm_stage == PM_STAGE1 && pmap == PCPU_GET(curpmap)) ||
7438 (pmap->pm_stage == PM_STAGE2 && pmap == PCPU_GET(curvmpmap))) {
7440 * Handle the possibility that the old thread was preempted
7441 * after an "ic" or "tlbi" instruction but before it performed
7442 * a "dsb" instruction. If the old thread migrates to a new
7443 * processor, its completion of a "dsb" instruction on that
7444 * new processor does not guarantee that the "ic" or "tlbi"
7445 * instructions performed on the old processor have completed.
7451 set = pmap->pm_asid_set;
7452 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
7455 * Ensure that the store to curpmap is globally visible before the
7456 * load from asid_epoch is performed.
7458 if (pmap->pm_stage == PM_STAGE1)
7459 PCPU_SET(curpmap, pmap);
7461 PCPU_SET(curvmpmap, pmap);
7463 epoch = COOKIE_TO_EPOCH(pmap->pm_cookie);
7464 if (epoch >= 0 && epoch != set->asid_epoch)
7465 pmap_alloc_asid(pmap);
7467 if (pmap->pm_stage == PM_STAGE1) {
7468 set_ttbr0(pmap_to_ttbr0(pmap));
7469 if (PCPU_GET(bcast_tlbi_workaround) != 0)
7470 invalidate_local_icache();
7476 pmap_activate_vm(pmap_t pmap)
7479 PMAP_ASSERT_STAGE2(pmap);
7481 (void)pmap_activate_int(pmap);
7485 pmap_activate(struct thread *td)
7489 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7490 PMAP_ASSERT_STAGE1(pmap);
7492 (void)pmap_activate_int(pmap);
7497 * Activate the thread we are switching to.
7498 * To simplify the assembly in cpu_throw return the new threads pcb.
7501 pmap_switch(struct thread *new)
7503 pcpu_bp_harden bp_harden;
7506 /* Store the new curthread */
7507 PCPU_SET(curthread, new);
7509 /* And the new pcb */
7511 PCPU_SET(curpcb, pcb);
7514 * TODO: We may need to flush the cache here if switching
7515 * to a user process.
7518 if (pmap_activate_int(vmspace_pmap(new->td_proc->p_vmspace))) {
7520 * Stop userspace from training the branch predictor against
7521 * other processes. This will call into a CPU specific
7522 * function that clears the branch predictor state.
7524 bp_harden = PCPU_GET(bp_harden);
7525 if (bp_harden != NULL)
7533 pmap_sync_icache(pmap_t pmap, vm_offset_t va, vm_size_t sz)
7536 PMAP_ASSERT_STAGE1(pmap);
7537 KASSERT(ADDR_IS_CANONICAL(va),
7538 ("%s: Address not in canonical form: %lx", __func__, va));
7540 if (ADDR_IS_KERNEL(va)) {
7541 cpu_icache_sync_range(va, sz);
7546 /* Find the length of data in this page to flush */
7547 offset = va & PAGE_MASK;
7548 len = imin(PAGE_SIZE - offset, sz);
7551 /* Extract the physical address & find it in the DMAP */
7552 pa = pmap_extract(pmap, va);
7554 cpu_icache_sync_range(PHYS_TO_DMAP(pa), len);
7556 /* Move to the next page */
7559 /* Set the length for the next iteration */
7560 len = imin(PAGE_SIZE, sz);
7566 pmap_stage2_fault(pmap_t pmap, uint64_t esr, uint64_t far)
7569 pt_entry_t *ptep, pte;
7572 PMAP_ASSERT_STAGE2(pmap);
7575 /* Data and insn aborts use same encoding for FSC field. */
7576 dfsc = esr & ISS_DATA_DFSC_MASK;
7578 case ISS_DATA_DFSC_TF_L0:
7579 case ISS_DATA_DFSC_TF_L1:
7580 case ISS_DATA_DFSC_TF_L2:
7581 case ISS_DATA_DFSC_TF_L3:
7583 pdep = pmap_pde(pmap, far, &lvl);
7584 if (pdep == NULL || lvl != (dfsc - ISS_DATA_DFSC_TF_L1)) {
7591 ptep = pmap_l0_to_l1(pdep, far);
7594 ptep = pmap_l1_to_l2(pdep, far);
7597 ptep = pmap_l2_to_l3(pdep, far);
7600 panic("%s: Invalid pde level %d", __func__,lvl);
7604 case ISS_DATA_DFSC_AFF_L1:
7605 case ISS_DATA_DFSC_AFF_L2:
7606 case ISS_DATA_DFSC_AFF_L3:
7608 ptep = pmap_pte(pmap, far, &lvl);
7610 if (ptep != NULL && (pte = pmap_load(ptep)) != 0) {
7612 pmap_invalidate_vpipt_icache();
7615 * If accessing an executable page invalidate
7616 * the I-cache so it will be valid when we
7617 * continue execution in the guest. The D-cache
7618 * is assumed to already be clean to the Point
7621 if ((pte & ATTR_S2_XN_MASK) !=
7622 ATTR_S2_XN(ATTR_S2_XN_NONE)) {
7623 invalidate_icache();
7626 pmap_set_bits(ptep, ATTR_AF | ATTR_DESCR_VALID);
7637 pmap_fault(pmap_t pmap, uint64_t esr, uint64_t far)
7639 pt_entry_t pte, *ptep;
7646 ec = ESR_ELx_EXCEPTION(esr);
7648 case EXCP_INSN_ABORT_L:
7649 case EXCP_INSN_ABORT:
7650 case EXCP_DATA_ABORT_L:
7651 case EXCP_DATA_ABORT:
7657 if (pmap->pm_stage == PM_STAGE2)
7658 return (pmap_stage2_fault(pmap, esr, far));
7660 /* Data and insn aborts use same encoding for FSC field. */
7661 switch (esr & ISS_DATA_DFSC_MASK) {
7662 case ISS_DATA_DFSC_AFF_L1:
7663 case ISS_DATA_DFSC_AFF_L2:
7664 case ISS_DATA_DFSC_AFF_L3:
7666 ptep = pmap_pte(pmap, far, &lvl);
7668 pmap_set_bits(ptep, ATTR_AF);
7671 * XXXMJ as an optimization we could mark the entry
7672 * dirty if this is a write fault.
7677 case ISS_DATA_DFSC_PF_L1:
7678 case ISS_DATA_DFSC_PF_L2:
7679 case ISS_DATA_DFSC_PF_L3:
7680 if ((ec != EXCP_DATA_ABORT_L && ec != EXCP_DATA_ABORT) ||
7681 (esr & ISS_DATA_WnR) == 0)
7684 ptep = pmap_pte(pmap, far, &lvl);
7686 ((pte = pmap_load(ptep)) & ATTR_SW_DBM) != 0) {
7687 if ((pte & ATTR_S1_AP_RW_BIT) ==
7688 ATTR_S1_AP(ATTR_S1_AP_RO)) {
7689 pmap_clear_bits(ptep, ATTR_S1_AP_RW_BIT);
7690 pmap_s1_invalidate_page(pmap, far, true);
7696 case ISS_DATA_DFSC_TF_L0:
7697 case ISS_DATA_DFSC_TF_L1:
7698 case ISS_DATA_DFSC_TF_L2:
7699 case ISS_DATA_DFSC_TF_L3:
7701 * Retry the translation. A break-before-make sequence can
7702 * produce a transient fault.
7704 if (pmap == kernel_pmap) {
7706 * The translation fault may have occurred within a
7707 * critical section. Therefore, we must check the
7708 * address without acquiring the kernel pmap's lock.
7710 if (pmap_klookup(far, NULL))
7714 /* Ask the MMU to check the address. */
7715 intr = intr_disable();
7716 par = arm64_address_translate_s1e0r(far);
7721 * If the translation was successful, then we can
7722 * return success to the trap handler.
7724 if (PAR_SUCCESS(par))
7734 * Increase the starting virtual address of the given mapping if a
7735 * different alignment might result in more superpage mappings.
7738 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7739 vm_offset_t *addr, vm_size_t size)
7741 vm_offset_t superpage_offset;
7745 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7746 offset += ptoa(object->pg_color);
7747 superpage_offset = offset & L2_OFFSET;
7748 if (size - ((L2_SIZE - superpage_offset) & L2_OFFSET) < L2_SIZE ||
7749 (*addr & L2_OFFSET) == superpage_offset)
7751 if ((*addr & L2_OFFSET) < superpage_offset)
7752 *addr = (*addr & ~L2_OFFSET) + superpage_offset;
7754 *addr = ((*addr + L2_OFFSET) & ~L2_OFFSET) + superpage_offset;
7758 * Get the kernel virtual address of a set of physical pages. If there are
7759 * physical addresses not covered by the DMAP perform a transient mapping
7760 * that will be removed when calling pmap_unmap_io_transient.
7762 * \param page The pages the caller wishes to obtain the virtual
7763 * address on the kernel memory map.
7764 * \param vaddr On return contains the kernel virtual memory address
7765 * of the pages passed in the page parameter.
7766 * \param count Number of pages passed in.
7767 * \param can_fault true if the thread using the mapped pages can take
7768 * page faults, false otherwise.
7770 * \returns true if the caller must call pmap_unmap_io_transient when
7771 * finished or false otherwise.
7775 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7780 int error __diagused, i;
7783 * Allocate any KVA space that we need, this is done in a separate
7784 * loop to prevent calling vmem_alloc while pinned.
7786 needs_mapping = false;
7787 for (i = 0; i < count; i++) {
7788 paddr = VM_PAGE_TO_PHYS(page[i]);
7789 if (__predict_false(!PHYS_IN_DMAP(paddr))) {
7790 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7791 M_BESTFIT | M_WAITOK, &vaddr[i]);
7792 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7793 needs_mapping = true;
7795 vaddr[i] = PHYS_TO_DMAP(paddr);
7799 /* Exit early if everything is covered by the DMAP */
7805 for (i = 0; i < count; i++) {
7806 paddr = VM_PAGE_TO_PHYS(page[i]);
7807 if (!PHYS_IN_DMAP(paddr)) {
7809 "pmap_map_io_transient: TODO: Map out of DMAP data");
7813 return (needs_mapping);
7817 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7825 for (i = 0; i < count; i++) {
7826 paddr = VM_PAGE_TO_PHYS(page[i]);
7827 if (!PHYS_IN_DMAP(paddr)) {
7828 panic("ARM64TODO: pmap_unmap_io_transient: Unmap data");
7834 pmap_is_valid_memattr(pmap_t pmap __unused, vm_memattr_t mode)
7837 return (mode >= VM_MEMATTR_DEVICE && mode <= VM_MEMATTR_WRITE_THROUGH);
7841 static vm_paddr_t pmap_san_early_kernstart;
7842 static pd_entry_t *pmap_san_early_l2;
7844 void __nosanitizeaddress
7845 pmap_san_bootstrap(struct arm64_bootparams *abp)
7848 pmap_san_early_kernstart = KERNBASE - abp->kern_delta;
7849 kasan_init_early(abp->kern_stack, KSTACK_PAGES * PAGE_SIZE);
7852 #define SAN_BOOTSTRAP_L2_SIZE (1 * L2_SIZE)
7853 #define SAN_BOOTSTRAP_SIZE (2 * PAGE_SIZE)
7854 static vm_offset_t __nosanitizeaddress
7855 pmap_san_enter_bootstrap_alloc_l2(void)
7857 static uint8_t bootstrap_data[SAN_BOOTSTRAP_L2_SIZE] __aligned(L2_SIZE);
7858 static size_t offset = 0;
7861 if (offset + L2_SIZE > sizeof(bootstrap_data)) {
7862 panic("%s: out of memory for the bootstrap shadow map L2 entries",
7866 addr = (uintptr_t)&bootstrap_data[offset];
7872 * SAN L1 + L2 pages, maybe L3 entries later?
7874 static vm_offset_t __nosanitizeaddress
7875 pmap_san_enter_bootstrap_alloc_pages(int npages)
7877 static uint8_t bootstrap_data[SAN_BOOTSTRAP_SIZE] __aligned(PAGE_SIZE);
7878 static size_t offset = 0;
7881 if (offset + (npages * PAGE_SIZE) > sizeof(bootstrap_data)) {
7882 panic("%s: out of memory for the bootstrap shadow map",
7886 addr = (uintptr_t)&bootstrap_data[offset];
7887 offset += (npages * PAGE_SIZE);
7891 static void __nosanitizeaddress
7892 pmap_san_enter_bootstrap(void)
7894 vm_offset_t freemempos;
7897 freemempos = pmap_san_enter_bootstrap_alloc_pages(2);
7898 bs_state.freemempos = freemempos;
7899 bs_state.va = KASAN_MIN_ADDRESS;
7900 pmap_bootstrap_l1_table(&bs_state);
7901 pmap_san_early_l2 = bs_state.l2;
7905 pmap_san_enter_alloc_l3(void)
7909 m = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED |
7912 panic("%s: no memory to grow shadow map", __func__);
7917 pmap_san_enter_alloc_l2(void)
7919 return (vm_page_alloc_noobj_contig(VM_ALLOC_WIRED | VM_ALLOC_ZERO,
7920 Ln_ENTRIES, 0, ~0ul, L2_SIZE, 0, VM_MEMATTR_DEFAULT));
7923 void __nosanitizeaddress
7924 pmap_san_enter(vm_offset_t va)
7926 pd_entry_t *l1, *l2;
7930 if (virtual_avail == 0) {
7935 /* Temporary shadow map prior to pmap_bootstrap(). */
7936 first = pmap_san_early_l2 == NULL;
7938 pmap_san_enter_bootstrap();
7940 l2 = pmap_san_early_l2;
7941 slot = pmap_l2_index(va);
7943 if ((pmap_load(&l2[slot]) & ATTR_DESCR_VALID) == 0) {
7945 block = pmap_san_enter_bootstrap_alloc_l2();
7946 pmap_store(&l2[slot],
7947 PHYS_TO_PTE(pmap_early_vtophys(block)) |
7948 PMAP_SAN_PTE_BITS | L2_BLOCK);
7955 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
7956 l1 = pmap_l1(kernel_pmap, va);
7958 if ((pmap_load(l1) & ATTR_DESCR_VALID) == 0) {
7959 m = pmap_san_enter_alloc_l3();
7960 pmap_store(l1, PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) | L1_TABLE);
7962 l2 = pmap_l1_to_l2(l1, va);
7963 if ((pmap_load(l2) & ATTR_DESCR_VALID) == 0) {
7964 m = pmap_san_enter_alloc_l2();
7966 pmap_store(l2, PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) |
7967 PMAP_SAN_PTE_BITS | L2_BLOCK);
7969 m = pmap_san_enter_alloc_l3();
7970 pmap_store(l2, PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) |
7975 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK)
7977 l3 = pmap_l2_to_l3(l2, va);
7978 if ((pmap_load(l3) & ATTR_DESCR_VALID) != 0)
7980 m = pmap_san_enter_alloc_l3();
7981 pmap_store(l3, PHYS_TO_PTE(VM_PAGE_TO_PHYS(m)) |
7982 PMAP_SAN_PTE_BITS | L3_PAGE);
7988 * Track a range of the kernel's virtual address space that is contiguous
7989 * in various mapping attributes.
7991 struct pmap_kernel_map_range {
8001 sysctl_kmaps_dump(struct sbuf *sb, struct pmap_kernel_map_range *range,
8007 if (eva <= range->sva)
8010 index = range->attrs & ATTR_S1_IDX_MASK;
8012 case ATTR_S1_IDX(VM_MEMATTR_DEVICE_NP):
8015 case ATTR_S1_IDX(VM_MEMATTR_DEVICE):
8018 case ATTR_S1_IDX(VM_MEMATTR_UNCACHEABLE):
8021 case ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK):
8024 case ATTR_S1_IDX(VM_MEMATTR_WRITE_THROUGH):
8029 "%s: unknown memory type %x for range 0x%016lx-0x%016lx\n",
8030 __func__, index, range->sva, eva);
8035 sbuf_printf(sb, "0x%016lx-0x%016lx r%c%c%c%c %6s %d %d %d %d\n",
8037 (range->attrs & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP_RW ? 'w' : '-',
8038 (range->attrs & ATTR_S1_PXN) != 0 ? '-' : 'x',
8039 (range->attrs & ATTR_S1_UXN) != 0 ? '-' : 'X',
8040 (range->attrs & ATTR_S1_AP(ATTR_S1_AP_USER)) != 0 ? 'u' : 's',
8041 mode, range->l1blocks, range->l2blocks, range->l3contig,
8044 /* Reset to sentinel value. */
8045 range->sva = 0xfffffffffffffffful;
8049 * Determine whether the attributes specified by a page table entry match those
8050 * being tracked by the current range.
8053 sysctl_kmaps_match(struct pmap_kernel_map_range *range, pt_entry_t attrs)
8056 return (range->attrs == attrs);
8060 sysctl_kmaps_reinit(struct pmap_kernel_map_range *range, vm_offset_t va,
8064 memset(range, 0, sizeof(*range));
8066 range->attrs = attrs;
8069 /* Get the block/page attributes that correspond to the table attributes */
8071 sysctl_kmaps_table_attrs(pd_entry_t table)
8076 if ((table & TATTR_UXN_TABLE) != 0)
8077 attrs |= ATTR_S1_UXN;
8078 if ((table & TATTR_PXN_TABLE) != 0)
8079 attrs |= ATTR_S1_PXN;
8080 if ((table & TATTR_AP_TABLE_RO) != 0)
8081 attrs |= ATTR_S1_AP(ATTR_S1_AP_RO);
8086 /* Read the block/page attributes we care about */
8088 sysctl_kmaps_block_attrs(pt_entry_t block)
8090 return (block & (ATTR_S1_AP_MASK | ATTR_S1_XN | ATTR_S1_IDX_MASK));
8094 * Given a leaf PTE, derive the mapping's attributes. If they do not match
8095 * those of the current run, dump the address range and its attributes, and
8099 sysctl_kmaps_check(struct sbuf *sb, struct pmap_kernel_map_range *range,
8100 vm_offset_t va, pd_entry_t l0e, pd_entry_t l1e, pd_entry_t l2e,
8105 attrs = sysctl_kmaps_table_attrs(l0e);
8107 if ((l1e & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
8108 attrs |= sysctl_kmaps_block_attrs(l1e);
8111 attrs |= sysctl_kmaps_table_attrs(l1e);
8113 if ((l2e & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
8114 attrs |= sysctl_kmaps_block_attrs(l2e);
8117 attrs |= sysctl_kmaps_table_attrs(l2e);
8118 attrs |= sysctl_kmaps_block_attrs(l3e);
8121 if (range->sva > va || !sysctl_kmaps_match(range, attrs)) {
8122 sysctl_kmaps_dump(sb, range, va);
8123 sysctl_kmaps_reinit(range, va, attrs);
8128 sysctl_kmaps(SYSCTL_HANDLER_ARGS)
8130 struct pmap_kernel_map_range range;
8131 struct sbuf sbuf, *sb;
8132 pd_entry_t l0e, *l1, l1e, *l2, l2e;
8133 pt_entry_t *l3, l3e;
8136 int error, i, j, k, l;
8138 error = sysctl_wire_old_buffer(req, 0);
8142 sbuf_new_for_sysctl(sb, NULL, PAGE_SIZE, req);
8144 /* Sentinel value. */
8145 range.sva = 0xfffffffffffffffful;
8148 * Iterate over the kernel page tables without holding the kernel pmap
8149 * lock. Kernel page table pages are never freed, so at worst we will
8150 * observe inconsistencies in the output.
8152 for (sva = 0xffff000000000000ul, i = pmap_l0_index(sva); i < Ln_ENTRIES;
8154 if (i == pmap_l0_index(DMAP_MIN_ADDRESS))
8155 sbuf_printf(sb, "\nDirect map:\n");
8156 else if (i == pmap_l0_index(VM_MIN_KERNEL_ADDRESS))
8157 sbuf_printf(sb, "\nKernel map:\n");
8159 else if (i == pmap_l0_index(KASAN_MIN_ADDRESS))
8160 sbuf_printf(sb, "\nKASAN shadow map:\n");
8163 l0e = kernel_pmap->pm_l0[i];
8164 if ((l0e & ATTR_DESCR_VALID) == 0) {
8165 sysctl_kmaps_dump(sb, &range, sva);
8169 pa = PTE_TO_PHYS(l0e);
8170 l1 = (pd_entry_t *)PHYS_TO_DMAP(pa);
8172 for (j = pmap_l1_index(sva); j < Ln_ENTRIES; j++) {
8174 if ((l1e & ATTR_DESCR_VALID) == 0) {
8175 sysctl_kmaps_dump(sb, &range, sva);
8179 if ((l1e & ATTR_DESCR_MASK) == L1_BLOCK) {
8180 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
8181 sysctl_kmaps_check(sb, &range, sva, l0e, l1e,
8187 pa = PTE_TO_PHYS(l1e);
8188 l2 = (pd_entry_t *)PHYS_TO_DMAP(pa);
8190 for (k = pmap_l2_index(sva); k < Ln_ENTRIES; k++) {
8192 if ((l2e & ATTR_DESCR_VALID) == 0) {
8193 sysctl_kmaps_dump(sb, &range, sva);
8197 if ((l2e & ATTR_DESCR_MASK) == L2_BLOCK) {
8198 sysctl_kmaps_check(sb, &range, sva,
8204 pa = PTE_TO_PHYS(l2e);
8205 l3 = (pt_entry_t *)PHYS_TO_DMAP(pa);
8207 for (l = pmap_l3_index(sva); l < Ln_ENTRIES;
8208 l++, sva += L3_SIZE) {
8210 if ((l3e & ATTR_DESCR_VALID) == 0) {
8211 sysctl_kmaps_dump(sb, &range,
8215 sysctl_kmaps_check(sb, &range, sva,
8216 l0e, l1e, l2e, l3e);
8217 if ((l3e & ATTR_CONTIGUOUS) != 0)
8218 range.l3contig += l % 16 == 0 ?
8227 error = sbuf_finish(sb);
8231 SYSCTL_OID(_vm_pmap, OID_AUTO, kernel_maps,
8232 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
8233 NULL, 0, sysctl_kmaps, "A",
8234 "Dump kernel address layout");