2 * Copyright (c) 1991 Regents of the University of California.
4 * Copyright (c) 1994 John S. Dyson
6 * Copyright (c) 1994 David Greenman
8 * Copyright (c) 2003 Peter Wemm
10 * Copyright (c) 2005-2010 Alan L. Cox <alc@cs.rice.edu>
11 * All rights reserved.
12 * Copyright (c) 2014 Andrew Turner
13 * All rights reserved.
14 * Copyright (c) 2014-2016 The FreeBSD Foundation
15 * All rights reserved.
17 * This code is derived from software contributed to Berkeley by
18 * the Systems Programming Group of the University of Utah Computer
19 * Science Department and William Jolitz of UUNET Technologies Inc.
21 * This software was developed by Andrew Turner under sponsorship from
22 * the FreeBSD Foundation.
24 * Redistribution and use in source and binary forms, with or without
25 * modification, are permitted provided that the following conditions
27 * 1. Redistributions of source code must retain the above copyright
28 * notice, this list of conditions and the following disclaimer.
29 * 2. Redistributions in binary form must reproduce the above copyright
30 * notice, this list of conditions and the following disclaimer in the
31 * documentation and/or other materials provided with the distribution.
32 * 3. All advertising materials mentioning features or use of this software
33 * must display the following acknowledgement:
34 * This product includes software developed by the University of
35 * California, Berkeley and its contributors.
36 * 4. Neither the name of the University nor the names of its contributors
37 * may be used to endorse or promote products derived from this software
38 * without specific prior written permission.
40 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * from: @(#)pmap.c 7.7 (Berkeley) 5/12/91
55 * Copyright (c) 2003 Networks Associates Technology, Inc.
56 * All rights reserved.
58 * This software was developed for the FreeBSD Project by Jake Burkholder,
59 * Safeport Network Services, and Network Associates Laboratories, the
60 * Security Research Division of Network Associates, Inc. under
61 * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
62 * CHATS research program.
64 * Redistribution and use in source and binary forms, with or without
65 * modification, are permitted provided that the following conditions
67 * 1. Redistributions of source code must retain the above copyright
68 * notice, this list of conditions and the following disclaimer.
69 * 2. Redistributions in binary form must reproduce the above copyright
70 * notice, this list of conditions and the following disclaimer in the
71 * documentation and/or other materials provided with the distribution.
73 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
74 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
75 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
76 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
77 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
78 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
79 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
80 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
81 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
82 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
86 #include <sys/cdefs.h>
87 __FBSDID("$FreeBSD$");
90 * Manages physical address maps.
92 * Since the information managed by this module is
93 * also stored by the logical address mapping module,
94 * this module may throw away valid virtual-to-physical
95 * mappings at almost any time. However, invalidations
96 * of virtual-to-physical mappings must be done as
99 * In order to cope with hardware architectures which
100 * make virtual-to-physical map invalidates expensive,
101 * this module may delay invalidate or reduced protection
102 * operations until such time as they are actually
103 * necessary. This module is given full information as
104 * to which processors are currently using which maps,
105 * and to when physical maps must be made correct.
110 #include <sys/param.h>
111 #include <sys/bitstring.h>
113 #include <sys/systm.h>
114 #include <sys/kernel.h>
116 #include <sys/limits.h>
117 #include <sys/lock.h>
118 #include <sys/malloc.h>
119 #include <sys/mman.h>
120 #include <sys/msgbuf.h>
121 #include <sys/mutex.h>
122 #include <sys/physmem.h>
123 #include <sys/proc.h>
124 #include <sys/rwlock.h>
125 #include <sys/sbuf.h>
127 #include <sys/vmem.h>
128 #include <sys/vmmeter.h>
129 #include <sys/sched.h>
130 #include <sys/sysctl.h>
131 #include <sys/_unrhdr.h>
135 #include <vm/vm_param.h>
136 #include <vm/vm_kern.h>
137 #include <vm/vm_page.h>
138 #include <vm/vm_map.h>
139 #include <vm/vm_object.h>
140 #include <vm/vm_extern.h>
141 #include <vm/vm_pageout.h>
142 #include <vm/vm_pager.h>
143 #include <vm/vm_phys.h>
144 #include <vm/vm_radix.h>
145 #include <vm/vm_reserv.h>
146 #include <vm/vm_dumpset.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)
171 #if !defined(DIAGNOSTIC)
172 #ifdef __GNUC_GNU_INLINE__
173 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
175 #define PMAP_INLINE extern inline
182 #define PV_STAT(x) do { x ; } while (0)
185 #define PV_STAT(x) do { } while (0)
186 #define __pvused __unused
189 #define pmap_l0_pindex(v) (NUL2E + NUL1E + ((v) >> L0_SHIFT))
190 #define pmap_l1_pindex(v) (NUL2E + ((v) >> L1_SHIFT))
191 #define pmap_l2_pindex(v) ((v) >> L2_SHIFT)
193 struct pmap_large_md_page {
194 struct rwlock pv_lock;
195 struct md_page pv_page;
196 /* Pad to a power of 2, see pmap_init_pv_table(). */
200 static struct pmap_large_md_page *
201 _pa_to_pmdp(vm_paddr_t pa)
203 struct vm_phys_seg *seg;
206 for (segind = 0; segind < vm_phys_nsegs; segind++) {
207 seg = &vm_phys_segs[segind];
208 if (pa >= seg->start && pa < seg->end)
209 return ((struct pmap_large_md_page *)seg->md_first +
210 pmap_l2_pindex(pa) - pmap_l2_pindex(seg->start));
215 static struct pmap_large_md_page *
216 pa_to_pmdp(vm_paddr_t pa)
218 struct pmap_large_md_page *pvd;
220 pvd = _pa_to_pmdp(pa);
222 panic("pa 0x%jx not within vm_phys_segs", (uintmax_t)pa);
226 static struct pmap_large_md_page *
227 page_to_pmdp(vm_page_t m)
229 struct vm_phys_seg *seg;
231 seg = &vm_phys_segs[m->segind];
232 return ((struct pmap_large_md_page *)seg->md_first +
233 pmap_l2_pindex(VM_PAGE_TO_PHYS(m)) - pmap_l2_pindex(seg->start));
236 #define pa_to_pvh(pa) (&(pa_to_pmdp(pa)->pv_page))
237 #define page_to_pvh(m) (&(page_to_pmdp(m)->pv_page))
239 #define PHYS_TO_PV_LIST_LOCK(pa) ({ \
240 struct pmap_large_md_page *_pvd; \
241 struct rwlock *_lock; \
242 _pvd = _pa_to_pmdp(pa); \
243 if (__predict_false(_pvd == NULL)) \
244 _lock = &pv_dummy_large.pv_lock; \
246 _lock = &(_pvd->pv_lock); \
250 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
251 struct rwlock **_lockp = (lockp); \
252 struct rwlock *_new_lock; \
254 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
255 if (_new_lock != *_lockp) { \
256 if (*_lockp != NULL) \
257 rw_wunlock(*_lockp); \
258 *_lockp = _new_lock; \
263 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
264 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
266 #define RELEASE_PV_LIST_LOCK(lockp) do { \
267 struct rwlock **_lockp = (lockp); \
269 if (*_lockp != NULL) { \
270 rw_wunlock(*_lockp); \
275 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
276 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
279 * The presence of this flag indicates that the mapping is writeable.
280 * If the ATTR_S1_AP_RO bit is also set, then the mapping is clean, otherwise
281 * it is dirty. This flag may only be set on managed mappings.
283 * The DBM bit is reserved on ARMv8.0 but it seems we can safely treat it
284 * as a software managed bit.
286 #define ATTR_SW_DBM ATTR_DBM
288 struct pmap kernel_pmap_store;
290 /* Used for mapping ACPI memory before VM is initialized */
291 #define PMAP_PREINIT_MAPPING_COUNT 32
292 #define PMAP_PREINIT_MAPPING_SIZE (PMAP_PREINIT_MAPPING_COUNT * L2_SIZE)
293 static vm_offset_t preinit_map_va; /* Start VA of pre-init mapping space */
294 static int vm_initialized = 0; /* No need to use pre-init maps when set */
297 * Reserve a few L2 blocks starting from 'preinit_map_va' pointer.
298 * Always map entire L2 block for simplicity.
299 * VA of L2 block = preinit_map_va + i * L2_SIZE
301 static struct pmap_preinit_mapping {
305 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
307 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
308 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
309 vm_offset_t kernel_vm_end = 0;
312 * Data for the pv entry allocation mechanism.
316 pc_to_domain(struct pv_chunk *pc)
318 return (vm_phys_domain(DMAP_TO_PHYS((vm_offset_t)pc)));
322 pc_to_domain(struct pv_chunk *pc __unused)
328 struct pv_chunks_list {
330 TAILQ_HEAD(pch, pv_chunk) pvc_list;
332 } __aligned(CACHE_LINE_SIZE);
334 struct pv_chunks_list __exclusive_cache_line pv_chunks[PMAP_MEMDOM];
336 __exclusive_cache_line static struct pmap_large_md_page pv_dummy_large;
337 #define pv_dummy pv_dummy_large.pv_page
338 __read_mostly static struct pmap_large_md_page *pv_table;
339 __read_mostly vm_paddr_t pmap_last_pa;
341 vm_paddr_t dmap_phys_base; /* The start of the dmap region */
342 vm_paddr_t dmap_phys_max; /* The limit of the dmap region */
343 vm_offset_t dmap_max_addr; /* The virtual address limit of the dmap */
345 extern pt_entry_t pagetable_l0_ttbr1[];
347 #define PHYSMAP_SIZE (2 * (VM_PHYSSEG_MAX - 1))
348 static vm_paddr_t physmap[PHYSMAP_SIZE];
349 static u_int physmap_idx;
351 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
352 "VM/pmap parameters");
354 #if PAGE_SIZE == PAGE_SIZE_4K
355 #define L1_BLOCKS_SUPPORTED 1
357 /* TODO: Make this dynamic when we support FEAT_LPA2 (TCR_EL1.DS == 1) */
358 #define L1_BLOCKS_SUPPORTED 0
361 #define PMAP_ASSERT_L1_BLOCKS_SUPPORTED MPASS(L1_BLOCKS_SUPPORTED)
364 * This ASID allocator uses a bit vector ("asid_set") to remember which ASIDs
365 * that it has currently allocated to a pmap, a cursor ("asid_next") to
366 * optimize its search for a free ASID in the bit vector, and an epoch number
367 * ("asid_epoch") to indicate when it has reclaimed all previously allocated
368 * ASIDs that are not currently active on a processor.
370 * The current epoch number is always in the range [0, INT_MAX). Negative
371 * numbers and INT_MAX are reserved for special cases that are described
380 struct mtx asid_set_mutex;
383 static struct asid_set asids;
384 static struct asid_set vmids;
386 static SYSCTL_NODE(_vm_pmap, OID_AUTO, asid, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
388 SYSCTL_INT(_vm_pmap_asid, OID_AUTO, bits, CTLFLAG_RD, &asids.asid_bits, 0,
389 "The number of bits in an ASID");
390 SYSCTL_INT(_vm_pmap_asid, OID_AUTO, next, CTLFLAG_RD, &asids.asid_next, 0,
391 "The last allocated ASID plus one");
392 SYSCTL_INT(_vm_pmap_asid, OID_AUTO, epoch, CTLFLAG_RD, &asids.asid_epoch, 0,
393 "The current epoch number");
395 static SYSCTL_NODE(_vm_pmap, OID_AUTO, vmid, CTLFLAG_RD, 0, "VMID allocator");
396 SYSCTL_INT(_vm_pmap_vmid, OID_AUTO, bits, CTLFLAG_RD, &vmids.asid_bits, 0,
397 "The number of bits in an VMID");
398 SYSCTL_INT(_vm_pmap_vmid, OID_AUTO, next, CTLFLAG_RD, &vmids.asid_next, 0,
399 "The last allocated VMID plus one");
400 SYSCTL_INT(_vm_pmap_vmid, OID_AUTO, epoch, CTLFLAG_RD, &vmids.asid_epoch, 0,
401 "The current epoch number");
403 void (*pmap_clean_stage2_tlbi)(void);
404 void (*pmap_invalidate_vpipt_icache)(void);
405 void (*pmap_stage2_invalidate_range)(uint64_t, vm_offset_t, vm_offset_t, bool);
406 void (*pmap_stage2_invalidate_all)(uint64_t);
409 * A pmap's cookie encodes an ASID and epoch number. Cookies for reserved
410 * ASIDs have a negative epoch number, specifically, INT_MIN. Cookies for
411 * dynamically allocated ASIDs have a non-negative epoch number.
413 * An invalid ASID is represented by -1.
415 * There are two special-case cookie values: (1) COOKIE_FROM(-1, INT_MIN),
416 * which indicates that an ASID should never be allocated to the pmap, and
417 * (2) COOKIE_FROM(-1, INT_MAX), which indicates that an ASID should be
418 * allocated when the pmap is next activated.
420 #define COOKIE_FROM(asid, epoch) ((long)((u_int)(asid) | \
421 ((u_long)(epoch) << 32)))
422 #define COOKIE_TO_ASID(cookie) ((int)(cookie))
423 #define COOKIE_TO_EPOCH(cookie) ((int)((u_long)(cookie) >> 32))
425 #define TLBI_VA_SHIFT 12
426 #define TLBI_VA_MASK ((1ul << 44) - 1)
427 #define TLBI_VA(addr) (((addr) >> TLBI_VA_SHIFT) & TLBI_VA_MASK)
428 #define TLBI_VA_L3_INCR (L3_SIZE >> TLBI_VA_SHIFT)
430 static int superpages_enabled = 1;
431 SYSCTL_INT(_vm_pmap, OID_AUTO, superpages_enabled,
432 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &superpages_enabled, 0,
433 "Are large page mappings enabled?");
436 * Internal flags for pmap_enter()'s helper functions.
438 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
439 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
441 TAILQ_HEAD(pv_chunklist, pv_chunk);
443 static void free_pv_chunk(struct pv_chunk *pc);
444 static void free_pv_chunk_batch(struct pv_chunklist *batch);
445 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
446 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
447 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
448 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
449 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
452 static void pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte);
453 static bool pmap_activate_int(pmap_t pmap);
454 static void pmap_alloc_asid(pmap_t pmap);
455 static int pmap_change_props_locked(vm_offset_t va, vm_size_t size,
456 vm_prot_t prot, int mode, bool skip_unmapped);
457 static pt_entry_t *pmap_demote_l1(pmap_t pmap, pt_entry_t *l1, vm_offset_t va);
458 static pt_entry_t *pmap_demote_l2_locked(pmap_t pmap, pt_entry_t *l2,
459 vm_offset_t va, struct rwlock **lockp);
460 static pt_entry_t *pmap_demote_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va);
461 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
462 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
463 static int pmap_enter_l2(pmap_t pmap, vm_offset_t va, pd_entry_t new_l2,
464 u_int flags, vm_page_t m, struct rwlock **lockp);
465 static int pmap_remove_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva,
466 pd_entry_t l1e, struct spglist *free, struct rwlock **lockp);
467 static int pmap_remove_l3(pmap_t pmap, pt_entry_t *l3, vm_offset_t sva,
468 pd_entry_t l2e, struct spglist *free, struct rwlock **lockp);
469 static void pmap_reset_asid_set(pmap_t pmap);
470 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
471 vm_page_t m, struct rwlock **lockp);
473 static vm_page_t _pmap_alloc_l3(pmap_t pmap, vm_pindex_t ptepindex,
474 struct rwlock **lockp);
476 static void _pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m,
477 struct spglist *free);
478 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
479 static __inline vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
482 * These load the old table data and store the new value.
483 * They need to be atomic as the System MMU may write to the table at
484 * the same time as the CPU.
486 #define pmap_clear(table) atomic_store_64(table, 0)
487 #define pmap_clear_bits(table, bits) atomic_clear_64(table, bits)
488 #define pmap_load(table) (*table)
489 #define pmap_load_clear(table) atomic_swap_64(table, 0)
490 #define pmap_load_store(table, entry) atomic_swap_64(table, entry)
491 #define pmap_set_bits(table, bits) atomic_set_64(table, bits)
492 #define pmap_store(table, entry) atomic_store_64(table, entry)
494 /********************/
495 /* Inline functions */
496 /********************/
499 pagecopy(void *s, void *d)
502 memcpy(d, s, PAGE_SIZE);
505 static __inline pd_entry_t *
506 pmap_l0(pmap_t pmap, vm_offset_t va)
509 return (&pmap->pm_l0[pmap_l0_index(va)]);
512 static __inline pd_entry_t *
513 pmap_l0_to_l1(pd_entry_t *l0, vm_offset_t va)
517 l1 = (pd_entry_t *)PHYS_TO_DMAP(pmap_load(l0) & ~ATTR_MASK);
518 return (&l1[pmap_l1_index(va)]);
521 static __inline pd_entry_t *
522 pmap_l1(pmap_t pmap, vm_offset_t va)
526 l0 = pmap_l0(pmap, va);
527 if ((pmap_load(l0) & ATTR_DESCR_MASK) != L0_TABLE)
530 return (pmap_l0_to_l1(l0, va));
533 static __inline pd_entry_t *
534 pmap_l1_to_l2(pd_entry_t *l1p, vm_offset_t va)
540 KASSERT(ADDR_IS_CANONICAL(va),
541 ("%s: Address not in canonical form: %lx", __func__, va));
543 * The valid bit may be clear if pmap_update_entry() is concurrently
544 * modifying the entry, so for KVA only the entry type may be checked.
546 KASSERT(ADDR_IS_KERNEL(va) || (l1 & ATTR_DESCR_VALID) != 0,
547 ("%s: L1 entry %#lx for %#lx is invalid", __func__, l1, va));
548 KASSERT((l1 & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_TABLE,
549 ("%s: L1 entry %#lx for %#lx is a leaf", __func__, l1, va));
550 l2p = (pd_entry_t *)PHYS_TO_DMAP(l1 & ~ATTR_MASK);
551 return (&l2p[pmap_l2_index(va)]);
554 static __inline pd_entry_t *
555 pmap_l2(pmap_t pmap, vm_offset_t va)
559 l1 = pmap_l1(pmap, va);
560 if ((pmap_load(l1) & ATTR_DESCR_MASK) != L1_TABLE)
563 return (pmap_l1_to_l2(l1, va));
566 static __inline pt_entry_t *
567 pmap_l2_to_l3(pd_entry_t *l2p, vm_offset_t va)
574 KASSERT(ADDR_IS_CANONICAL(va),
575 ("%s: Address not in canonical form: %lx", __func__, va));
577 * The valid bit may be clear if pmap_update_entry() is concurrently
578 * modifying the entry, so for KVA only the entry type may be checked.
580 KASSERT(ADDR_IS_KERNEL(va) || (l2 & ATTR_DESCR_VALID) != 0,
581 ("%s: L2 entry %#lx for %#lx is invalid", __func__, l2, va));
582 KASSERT((l2 & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_TABLE,
583 ("%s: L2 entry %#lx for %#lx is a leaf", __func__, l2, va));
584 l3p = (pt_entry_t *)PHYS_TO_DMAP(l2 & ~ATTR_MASK);
585 return (&l3p[pmap_l3_index(va)]);
589 * Returns the lowest valid pde for a given virtual address.
590 * The next level may or may not point to a valid page or block.
592 static __inline pd_entry_t *
593 pmap_pde(pmap_t pmap, vm_offset_t va, int *level)
595 pd_entry_t *l0, *l1, *l2, desc;
597 l0 = pmap_l0(pmap, va);
598 desc = pmap_load(l0) & ATTR_DESCR_MASK;
599 if (desc != L0_TABLE) {
604 l1 = pmap_l0_to_l1(l0, va);
605 desc = pmap_load(l1) & ATTR_DESCR_MASK;
606 if (desc != L1_TABLE) {
611 l2 = pmap_l1_to_l2(l1, va);
612 desc = pmap_load(l2) & ATTR_DESCR_MASK;
613 if (desc != L2_TABLE) {
623 * Returns the lowest valid pte block or table entry for a given virtual
624 * address. If there are no valid entries return NULL and set the level to
625 * the first invalid level.
627 static __inline pt_entry_t *
628 pmap_pte(pmap_t pmap, vm_offset_t va, int *level)
630 pd_entry_t *l1, *l2, desc;
633 l1 = pmap_l1(pmap, va);
638 desc = pmap_load(l1) & ATTR_DESCR_MASK;
639 if (desc == L1_BLOCK) {
640 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
645 if (desc != L1_TABLE) {
650 l2 = pmap_l1_to_l2(l1, va);
651 desc = pmap_load(l2) & ATTR_DESCR_MASK;
652 if (desc == L2_BLOCK) {
657 if (desc != L2_TABLE) {
663 l3 = pmap_l2_to_l3(l2, va);
664 if ((pmap_load(l3) & ATTR_DESCR_MASK) != L3_PAGE)
671 * If the given pmap has an L{1,2}_BLOCK or L3_PAGE entry at the specified
672 * level that maps the specified virtual address, then a pointer to that entry
673 * is returned. Otherwise, NULL is returned, unless INVARIANTS are enabled
674 * and a diagnostic message is provided, in which case this function panics.
676 static __always_inline pt_entry_t *
677 pmap_pte_exists(pmap_t pmap, vm_offset_t va, int level, const char *diag)
679 pd_entry_t *l0p, *l1p, *l2p;
680 pt_entry_t desc, *l3p;
681 int walk_level __diagused;
683 KASSERT(level >= 0 && level < 4,
684 ("%s: %s passed an out-of-range level (%d)", __func__, diag,
686 l0p = pmap_l0(pmap, va);
687 desc = pmap_load(l0p) & ATTR_DESCR_MASK;
688 if (desc == L0_TABLE && level > 0) {
689 l1p = pmap_l0_to_l1(l0p, va);
690 desc = pmap_load(l1p) & ATTR_DESCR_MASK;
691 if (desc == L1_BLOCK && level == 1) {
692 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
695 if (desc == L1_TABLE && level > 1) {
696 l2p = pmap_l1_to_l2(l1p, va);
697 desc = pmap_load(l2p) & ATTR_DESCR_MASK;
698 if (desc == L2_BLOCK && level == 2)
700 else if (desc == L2_TABLE && level > 2) {
701 l3p = pmap_l2_to_l3(l2p, va);
702 desc = pmap_load(l3p) & ATTR_DESCR_MASK;
703 if (desc == L3_PAGE && level == 3)
713 KASSERT(diag == NULL,
714 ("%s: va %#lx not mapped at level %d, desc %ld at level %d",
715 diag, va, level, desc, walk_level));
720 pmap_ps_enabled(pmap_t pmap)
723 * Promotion requires a hypervisor call when the kernel is running
724 * in EL1. To stop this disable superpage support on non-stage 1
727 if (pmap->pm_stage != PM_STAGE1)
730 return (superpages_enabled != 0);
734 pmap_get_tables(pmap_t pmap, vm_offset_t va, pd_entry_t **l0, pd_entry_t **l1,
735 pd_entry_t **l2, pt_entry_t **l3)
737 pd_entry_t *l0p, *l1p, *l2p;
739 if (pmap->pm_l0 == NULL)
742 l0p = pmap_l0(pmap, va);
745 if ((pmap_load(l0p) & ATTR_DESCR_MASK) != L0_TABLE)
748 l1p = pmap_l0_to_l1(l0p, va);
751 if ((pmap_load(l1p) & ATTR_DESCR_MASK) == L1_BLOCK) {
752 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
758 if ((pmap_load(l1p) & ATTR_DESCR_MASK) != L1_TABLE)
761 l2p = pmap_l1_to_l2(l1p, va);
764 if ((pmap_load(l2p) & ATTR_DESCR_MASK) == L2_BLOCK) {
769 if ((pmap_load(l2p) & ATTR_DESCR_MASK) != L2_TABLE)
772 *l3 = pmap_l2_to_l3(l2p, va);
778 pmap_l3_valid(pt_entry_t l3)
781 return ((l3 & ATTR_DESCR_MASK) == L3_PAGE);
784 CTASSERT(L1_BLOCK == L2_BLOCK);
787 pmap_pte_memattr(pmap_t pmap, vm_memattr_t memattr)
791 if (pmap->pm_stage == PM_STAGE1) {
792 val = ATTR_S1_IDX(memattr);
793 if (memattr == VM_MEMATTR_DEVICE)
801 case VM_MEMATTR_DEVICE:
802 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_DEVICE_nGnRnE) |
803 ATTR_S2_XN(ATTR_S2_XN_ALL));
804 case VM_MEMATTR_UNCACHEABLE:
805 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_NC));
806 case VM_MEMATTR_WRITE_BACK:
807 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_WB));
808 case VM_MEMATTR_WRITE_THROUGH:
809 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_WT));
811 panic("%s: invalid memory attribute %x", __func__, memattr);
816 pmap_pte_prot(pmap_t pmap, vm_prot_t prot)
821 if (pmap->pm_stage == PM_STAGE1) {
822 if ((prot & VM_PROT_EXECUTE) == 0)
824 if ((prot & VM_PROT_WRITE) == 0)
825 val |= ATTR_S1_AP(ATTR_S1_AP_RO);
827 if ((prot & VM_PROT_WRITE) != 0)
828 val |= ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
829 if ((prot & VM_PROT_READ) != 0)
830 val |= ATTR_S2_S2AP(ATTR_S2_S2AP_READ);
831 if ((prot & VM_PROT_EXECUTE) == 0)
832 val |= ATTR_S2_XN(ATTR_S2_XN_ALL);
839 * Checks if the PTE is dirty.
842 pmap_pte_dirty(pmap_t pmap, pt_entry_t pte)
845 KASSERT((pte & ATTR_SW_MANAGED) != 0, ("pte %#lx is unmanaged", pte));
847 if (pmap->pm_stage == PM_STAGE1) {
848 KASSERT((pte & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) != 0,
849 ("pte %#lx is writeable and missing ATTR_SW_DBM", pte));
851 return ((pte & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
852 (ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_SW_DBM));
855 return ((pte & ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE)) ==
856 ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE));
860 pmap_resident_count_inc(pmap_t pmap, int count)
863 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
864 pmap->pm_stats.resident_count += count;
868 pmap_resident_count_dec(pmap_t pmap, int count)
871 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
872 KASSERT(pmap->pm_stats.resident_count >= count,
873 ("pmap %p resident count underflow %ld %d", pmap,
874 pmap->pm_stats.resident_count, count));
875 pmap->pm_stats.resident_count -= count;
879 pmap_early_vtophys(vm_offset_t va)
883 pa_page = arm64_address_translate_s1e1r(va) & PAR_PA_MASK;
884 return (pa_page | (va & PAR_LOW_MASK));
887 /* State of the bootstrapped DMAP page tables */
888 struct pmap_bootstrap_state {
892 vm_offset_t freemempos;
895 pt_entry_t table_attrs;
902 /* The bootstrap state */
903 static struct pmap_bootstrap_state bs_state = {
907 .table_attrs = TATTR_PXN_TABLE,
908 .l0_slot = L0_ENTRIES,
909 .l1_slot = Ln_ENTRIES,
910 .l2_slot = Ln_ENTRIES,
915 pmap_bootstrap_l0_table(struct pmap_bootstrap_state *state)
921 /* Link the level 0 table to a level 1 table */
922 l0_slot = pmap_l0_index(state->va);
923 if (l0_slot != state->l0_slot) {
925 * Make sure we move from a low address to high address
926 * before the DMAP region is ready. This ensures we never
927 * modify an existing mapping until we can map from a
928 * physical address to a virtual address.
930 MPASS(state->l0_slot < l0_slot ||
931 state->l0_slot == L0_ENTRIES ||
934 /* Reset lower levels */
937 state->l1_slot = Ln_ENTRIES;
938 state->l2_slot = Ln_ENTRIES;
940 /* Check the existing L0 entry */
941 state->l0_slot = l0_slot;
942 if (state->dmap_valid) {
943 l0e = pagetable_l0_ttbr1[l0_slot];
944 if ((l0e & ATTR_DESCR_VALID) != 0) {
945 MPASS((l0e & ATTR_DESCR_MASK) == L0_TABLE);
946 l1_pa = l0e & ~ATTR_MASK;
947 state->l1 = (pt_entry_t *)PHYS_TO_DMAP(l1_pa);
952 /* Create a new L0 table entry */
953 state->l1 = (pt_entry_t *)state->freemempos;
954 memset(state->l1, 0, PAGE_SIZE);
955 state->freemempos += PAGE_SIZE;
957 l1_pa = pmap_early_vtophys((vm_offset_t)state->l1);
958 MPASS((l1_pa & Ln_TABLE_MASK) == 0);
959 MPASS(pagetable_l0_ttbr1[l0_slot] == 0);
960 pmap_store(&pagetable_l0_ttbr1[l0_slot], l1_pa |
961 TATTR_UXN_TABLE | TATTR_AP_TABLE_NO_EL0 | L0_TABLE);
963 KASSERT(state->l1 != NULL, ("%s: NULL l1", __func__));
967 pmap_bootstrap_l1_table(struct pmap_bootstrap_state *state)
973 /* Make sure there is a valid L0 -> L1 table */
974 pmap_bootstrap_l0_table(state);
976 /* Link the level 1 table to a level 2 table */
977 l1_slot = pmap_l1_index(state->va);
978 if (l1_slot != state->l1_slot) {
979 /* See pmap_bootstrap_l0_table for a description */
980 MPASS(state->l1_slot < l1_slot ||
981 state->l1_slot == Ln_ENTRIES ||
984 /* Reset lower levels */
986 state->l2_slot = Ln_ENTRIES;
988 /* Check the existing L1 entry */
989 state->l1_slot = l1_slot;
990 if (state->dmap_valid) {
991 l1e = state->l1[l1_slot];
992 if ((l1e & ATTR_DESCR_VALID) != 0) {
993 MPASS((l1e & ATTR_DESCR_MASK) == L1_TABLE);
994 l2_pa = l1e & ~ATTR_MASK;
995 state->l2 = (pt_entry_t *)PHYS_TO_DMAP(l2_pa);
1000 /* Create a new L1 table entry */
1001 state->l2 = (pt_entry_t *)state->freemempos;
1002 memset(state->l2, 0, PAGE_SIZE);
1003 state->freemempos += PAGE_SIZE;
1005 l2_pa = pmap_early_vtophys((vm_offset_t)state->l2);
1006 MPASS((l2_pa & Ln_TABLE_MASK) == 0);
1007 MPASS(state->l1[l1_slot] == 0);
1008 pmap_store(&state->l1[l1_slot], l2_pa | state->table_attrs |
1011 KASSERT(state->l2 != NULL, ("%s: NULL l2", __func__));
1015 pmap_bootstrap_l2_table(struct pmap_bootstrap_state *state)
1021 /* Make sure there is a valid L1 -> L2 table */
1022 pmap_bootstrap_l1_table(state);
1024 /* Link the level 2 table to a level 3 table */
1025 l2_slot = pmap_l2_index(state->va);
1026 if (l2_slot != state->l2_slot) {
1027 /* See pmap_bootstrap_l0_table for a description */
1028 MPASS(state->l2_slot < l2_slot ||
1029 state->l2_slot == Ln_ENTRIES ||
1032 /* Check the existing L2 entry */
1033 state->l2_slot = l2_slot;
1034 if (state->dmap_valid) {
1035 l2e = state->l2[l2_slot];
1036 if ((l2e & ATTR_DESCR_VALID) != 0) {
1037 MPASS((l2e & ATTR_DESCR_MASK) == L2_TABLE);
1038 l3_pa = l2e & ~ATTR_MASK;
1039 state->l3 = (pt_entry_t *)PHYS_TO_DMAP(l3_pa);
1044 /* Create a new L2 table entry */
1045 state->l3 = (pt_entry_t *)state->freemempos;
1046 memset(state->l3, 0, PAGE_SIZE);
1047 state->freemempos += PAGE_SIZE;
1049 l3_pa = pmap_early_vtophys((vm_offset_t)state->l3);
1050 MPASS((l3_pa & Ln_TABLE_MASK) == 0);
1051 MPASS(state->l2[l2_slot] == 0);
1052 pmap_store(&state->l2[l2_slot], l3_pa | state->table_attrs |
1055 KASSERT(state->l3 != NULL, ("%s: NULL l3", __func__));
1059 pmap_bootstrap_l2_block(struct pmap_bootstrap_state *state, int i)
1064 if ((physmap[i + 1] - state->pa) < L2_SIZE)
1067 /* Make sure there is a valid L1 table */
1068 pmap_bootstrap_l1_table(state);
1070 MPASS((state->va & L2_OFFSET) == 0);
1072 state->va < DMAP_MAX_ADDRESS &&
1073 (physmap[i + 1] - state->pa) >= L2_SIZE;
1074 state->va += L2_SIZE, state->pa += L2_SIZE) {
1076 * Stop if we are about to walk off the end of what the
1077 * current L1 slot can address.
1079 if (!first && (state->pa & L1_OFFSET) == 0)
1083 l2_slot = pmap_l2_index(state->va);
1084 MPASS((state->pa & L2_OFFSET) == 0);
1085 MPASS(state->l2[l2_slot] == 0);
1086 pmap_store(&state->l2[l2_slot], state->pa | ATTR_DEFAULT |
1087 ATTR_S1_XN | ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) |
1090 MPASS(state->va == (state->pa - dmap_phys_base + DMAP_MIN_ADDRESS));
1094 pmap_bootstrap_l3_page(struct pmap_bootstrap_state *state, int i)
1099 if ((physmap[i + 1] - state->pa) < L3_SIZE)
1102 /* Make sure there is a valid L2 table */
1103 pmap_bootstrap_l2_table(state);
1105 MPASS((state->va & L3_OFFSET) == 0);
1107 state->va < DMAP_MAX_ADDRESS &&
1108 (physmap[i + 1] - state->pa) >= L3_SIZE;
1109 state->va += L3_SIZE, state->pa += L3_SIZE) {
1111 * Stop if we are about to walk off the end of what the
1112 * current L2 slot can address.
1114 if (!first && (state->pa & L2_OFFSET) == 0)
1118 l3_slot = pmap_l3_index(state->va);
1119 MPASS((state->pa & L3_OFFSET) == 0);
1120 MPASS(state->l3[l3_slot] == 0);
1121 pmap_store(&state->l3[l3_slot], state->pa | ATTR_DEFAULT |
1122 ATTR_S1_XN | ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) |
1125 MPASS(state->va == (state->pa - dmap_phys_base + DMAP_MIN_ADDRESS));
1129 pmap_bootstrap_dmap(vm_paddr_t min_pa)
1133 dmap_phys_base = min_pa & ~L1_OFFSET;
1137 for (i = 0; i < (physmap_idx * 2); i += 2) {
1138 bs_state.pa = physmap[i] & ~L3_OFFSET;
1139 bs_state.va = bs_state.pa - dmap_phys_base + DMAP_MIN_ADDRESS;
1141 /* Create L3 mappings at the start of the region */
1142 if ((bs_state.pa & L2_OFFSET) != 0)
1143 pmap_bootstrap_l3_page(&bs_state, i);
1144 MPASS(bs_state.pa <= physmap[i + 1]);
1146 if (L1_BLOCKS_SUPPORTED) {
1147 /* Create L2 mappings at the start of the region */
1148 if ((bs_state.pa & L1_OFFSET) != 0)
1149 pmap_bootstrap_l2_block(&bs_state, i);
1150 MPASS(bs_state.pa <= physmap[i + 1]);
1152 /* Create the main L1 block mappings */
1153 for (; bs_state.va < DMAP_MAX_ADDRESS &&
1154 (physmap[i + 1] - bs_state.pa) >= L1_SIZE;
1155 bs_state.va += L1_SIZE, bs_state.pa += L1_SIZE) {
1156 /* Make sure there is a valid L1 table */
1157 pmap_bootstrap_l0_table(&bs_state);
1158 MPASS((bs_state.pa & L1_OFFSET) == 0);
1160 &bs_state.l1[pmap_l1_index(bs_state.va)],
1161 bs_state.pa | ATTR_DEFAULT | ATTR_S1_XN |
1162 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) |
1165 MPASS(bs_state.pa <= physmap[i + 1]);
1167 /* Create L2 mappings at the end of the region */
1168 pmap_bootstrap_l2_block(&bs_state, i);
1170 while (bs_state.va < DMAP_MAX_ADDRESS &&
1171 (physmap[i + 1] - bs_state.pa) >= L2_SIZE) {
1172 pmap_bootstrap_l2_block(&bs_state, i);
1175 MPASS(bs_state.pa <= physmap[i + 1]);
1177 /* Create L3 mappings at the end of the region */
1178 pmap_bootstrap_l3_page(&bs_state, i);
1179 MPASS(bs_state.pa == physmap[i + 1]);
1181 if (bs_state.pa > dmap_phys_max) {
1182 dmap_phys_max = bs_state.pa;
1183 dmap_max_addr = bs_state.va;
1191 pmap_bootstrap_l2(vm_offset_t va)
1193 KASSERT((va & L1_OFFSET) == 0, ("Invalid virtual address"));
1195 /* Leave bs_state.pa as it's only needed to bootstrap blocks and pages*/
1198 for (; bs_state.va < VM_MAX_KERNEL_ADDRESS; bs_state.va += L1_SIZE)
1199 pmap_bootstrap_l1_table(&bs_state);
1203 pmap_bootstrap_l3(vm_offset_t va)
1205 KASSERT((va & L2_OFFSET) == 0, ("Invalid virtual address"));
1207 /* Leave bs_state.pa as it's only needed to bootstrap blocks and pages*/
1210 for (; bs_state.va < VM_MAX_KERNEL_ADDRESS; bs_state.va += L2_SIZE)
1211 pmap_bootstrap_l2_table(&bs_state);
1215 * Bootstrap the system enough to run with virtual memory.
1218 pmap_bootstrap(vm_paddr_t kernstart, vm_size_t kernlen)
1220 vm_offset_t dpcpu, msgbufpv;
1221 vm_paddr_t start_pa, pa, min_pa;
1222 uint64_t kern_delta;
1225 /* Verify that the ASID is set through TTBR0. */
1226 KASSERT((READ_SPECIALREG(tcr_el1) & TCR_A1) == 0,
1227 ("pmap_bootstrap: TCR_EL1.A1 != 0"));
1229 kern_delta = KERNBASE - kernstart;
1231 printf("pmap_bootstrap %lx %lx\n", kernstart, kernlen);
1232 printf("%lx\n", (KERNBASE >> L1_SHIFT) & Ln_ADDR_MASK);
1234 /* Set this early so we can use the pagetable walking functions */
1235 kernel_pmap_store.pm_l0 = pagetable_l0_ttbr1;
1236 PMAP_LOCK_INIT(kernel_pmap);
1237 kernel_pmap->pm_l0_paddr =
1238 pmap_early_vtophys((vm_offset_t)kernel_pmap_store.pm_l0);
1239 kernel_pmap->pm_cookie = COOKIE_FROM(-1, INT_MIN);
1240 kernel_pmap->pm_stage = PM_STAGE1;
1241 kernel_pmap->pm_levels = 4;
1242 kernel_pmap->pm_ttbr = kernel_pmap->pm_l0_paddr;
1243 kernel_pmap->pm_asid_set = &asids;
1245 /* Assume the address we were loaded to is a valid physical address */
1246 min_pa = KERNBASE - kern_delta;
1248 physmap_idx = physmem_avail(physmap, nitems(physmap));
1252 * Find the minimum physical address. physmap is sorted,
1253 * but may contain empty ranges.
1255 for (i = 0; i < physmap_idx * 2; i += 2) {
1256 if (physmap[i] == physmap[i + 1])
1258 if (physmap[i] <= min_pa)
1259 min_pa = physmap[i];
1262 bs_state.freemempos = KERNBASE + kernlen;
1263 bs_state.freemempos = roundup2(bs_state.freemempos, PAGE_SIZE);
1265 /* Create a direct map region early so we can use it for pa -> va */
1266 pmap_bootstrap_dmap(min_pa);
1267 bs_state.dmap_valid = true;
1269 * We only use PXN when we know nothing will be executed from it, e.g.
1272 bs_state.table_attrs &= ~TATTR_PXN_TABLE;
1274 start_pa = pa = KERNBASE - kern_delta;
1277 * Create the l2 tables up to VM_MAX_KERNEL_ADDRESS. We assume that the
1278 * loader allocated the first and only l2 page table page used to map
1279 * the kernel, preloaded files and module metadata.
1281 pmap_bootstrap_l2(KERNBASE + L1_SIZE);
1282 /* And the l3 tables for the early devmap */
1283 pmap_bootstrap_l3(VM_MAX_KERNEL_ADDRESS - (PMAP_MAPDEV_EARLY_SIZE));
1287 #define alloc_pages(var, np) \
1288 (var) = bs_state.freemempos; \
1289 bs_state.freemempos += (np * PAGE_SIZE); \
1290 memset((char *)(var), 0, ((np) * PAGE_SIZE));
1292 /* Allocate dynamic per-cpu area. */
1293 alloc_pages(dpcpu, DPCPU_SIZE / PAGE_SIZE);
1294 dpcpu_init((void *)dpcpu, 0);
1296 /* Allocate memory for the msgbuf, e.g. for /sbin/dmesg */
1297 alloc_pages(msgbufpv, round_page(msgbufsize) / PAGE_SIZE);
1298 msgbufp = (void *)msgbufpv;
1300 /* Reserve some VA space for early BIOS/ACPI mapping */
1301 preinit_map_va = roundup2(bs_state.freemempos, L2_SIZE);
1303 virtual_avail = preinit_map_va + PMAP_PREINIT_MAPPING_SIZE;
1304 virtual_avail = roundup2(virtual_avail, L1_SIZE);
1305 virtual_end = VM_MAX_KERNEL_ADDRESS - (PMAP_MAPDEV_EARLY_SIZE);
1306 kernel_vm_end = virtual_avail;
1308 pa = pmap_early_vtophys(bs_state.freemempos);
1310 physmem_exclude_region(start_pa, pa - start_pa, EXFLAG_NOALLOC);
1316 * Initialize a vm_page's machine-dependent fields.
1319 pmap_page_init(vm_page_t m)
1322 TAILQ_INIT(&m->md.pv_list);
1323 m->md.pv_memattr = VM_MEMATTR_WRITE_BACK;
1327 pmap_init_asids(struct asid_set *set, int bits)
1331 set->asid_bits = bits;
1334 * We may be too early in the overall initialization process to use
1337 set->asid_set_size = 1 << set->asid_bits;
1338 set->asid_set = kmem_malloc(bitstr_size(set->asid_set_size),
1340 for (i = 0; i < ASID_FIRST_AVAILABLE; i++)
1341 bit_set(set->asid_set, i);
1342 set->asid_next = ASID_FIRST_AVAILABLE;
1343 mtx_init(&set->asid_set_mutex, "asid set", NULL, MTX_SPIN);
1347 pmap_init_pv_table(void)
1349 struct vm_phys_seg *seg, *next_seg;
1350 struct pmap_large_md_page *pvd;
1352 int domain, i, j, pages;
1355 * We strongly depend on the size being a power of two, so the assert
1356 * is overzealous. However, should the struct be resized to a
1357 * different power of two, the code below needs to be revisited.
1359 CTASSERT((sizeof(*pvd) == 64));
1362 * Calculate the size of the array.
1365 for (i = 0; i < vm_phys_nsegs; i++) {
1366 seg = &vm_phys_segs[i];
1367 pages = pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) -
1368 pmap_l2_pindex(seg->start);
1369 s += round_page(pages * sizeof(*pvd));
1371 pv_table = (struct pmap_large_md_page *)kva_alloc(s);
1372 if (pv_table == NULL)
1373 panic("%s: kva_alloc failed\n", __func__);
1376 * Iterate physical segments to allocate domain-local memory for PV
1380 for (i = 0; i < vm_phys_nsegs; i++) {
1381 seg = &vm_phys_segs[i];
1382 pages = pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) -
1383 pmap_l2_pindex(seg->start);
1384 domain = seg->domain;
1386 s = round_page(pages * sizeof(*pvd));
1388 for (j = 0; j < s; j += PAGE_SIZE) {
1389 vm_page_t m = vm_page_alloc_noobj_domain(domain,
1392 panic("failed to allocate PV table page");
1393 pmap_qenter((vm_offset_t)pvd + j, &m, 1);
1396 for (j = 0; j < s / sizeof(*pvd); j++) {
1397 rw_init_flags(&pvd->pv_lock, "pmap pv list", RW_NEW);
1398 TAILQ_INIT(&pvd->pv_page.pv_list);
1402 pvd = &pv_dummy_large;
1403 memset(pvd, 0, sizeof(*pvd));
1404 rw_init_flags(&pvd->pv_lock, "pmap pv list dummy", RW_NEW);
1405 TAILQ_INIT(&pvd->pv_page.pv_list);
1408 * Set pointers from vm_phys_segs to pv_table.
1410 for (i = 0, pvd = pv_table; i < vm_phys_nsegs; i++) {
1411 seg = &vm_phys_segs[i];
1412 seg->md_first = pvd;
1413 pvd += pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) -
1414 pmap_l2_pindex(seg->start);
1417 * If there is a following segment, and the final
1418 * superpage of this segment and the initial superpage
1419 * of the next segment are the same then adjust the
1420 * pv_table entry for that next segment down by one so
1421 * that the pv_table entries will be shared.
1423 if (i + 1 < vm_phys_nsegs) {
1424 next_seg = &vm_phys_segs[i + 1];
1425 if (pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) - 1 ==
1426 pmap_l2_pindex(next_seg->start)) {
1434 * Initialize the pmap module.
1435 * Called by vm_init, to initialize any structures that the pmap
1436 * system needs to map virtual memory.
1445 * Are large page mappings enabled?
1447 TUNABLE_INT_FETCH("vm.pmap.superpages_enabled", &superpages_enabled);
1448 if (superpages_enabled) {
1449 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1450 ("pmap_init: can't assign to pagesizes[1]"));
1451 pagesizes[1] = L2_SIZE;
1452 if (L1_BLOCKS_SUPPORTED) {
1453 KASSERT(MAXPAGESIZES > 2 && pagesizes[2] == 0,
1454 ("pmap_init: can't assign to pagesizes[2]"));
1455 pagesizes[2] = L1_SIZE;
1460 * Initialize the ASID allocator.
1462 pmap_init_asids(&asids,
1463 (READ_SPECIALREG(tcr_el1) & TCR_ASID_16) != 0 ? 16 : 8);
1466 mmfr1 = READ_SPECIALREG(id_aa64mmfr1_el1);
1469 if (ID_AA64MMFR1_VMIDBits_VAL(mmfr1) ==
1470 ID_AA64MMFR1_VMIDBits_16)
1472 pmap_init_asids(&vmids, vmid_bits);
1476 * Initialize pv chunk lists.
1478 for (i = 0; i < PMAP_MEMDOM; i++) {
1479 mtx_init(&pv_chunks[i].pvc_lock, "pmap pv chunk list", NULL,
1481 TAILQ_INIT(&pv_chunks[i].pvc_list);
1483 pmap_init_pv_table();
1488 static SYSCTL_NODE(_vm_pmap, OID_AUTO, l2, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
1489 "2MB page mapping counters");
1491 static u_long pmap_l2_demotions;
1492 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, demotions, CTLFLAG_RD,
1493 &pmap_l2_demotions, 0, "2MB page demotions");
1495 static u_long pmap_l2_mappings;
1496 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, mappings, CTLFLAG_RD,
1497 &pmap_l2_mappings, 0, "2MB page mappings");
1499 static u_long pmap_l2_p_failures;
1500 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, p_failures, CTLFLAG_RD,
1501 &pmap_l2_p_failures, 0, "2MB page promotion failures");
1503 static u_long pmap_l2_promotions;
1504 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, promotions, CTLFLAG_RD,
1505 &pmap_l2_promotions, 0, "2MB page promotions");
1508 * If the given value for "final_only" is false, then any cached intermediate-
1509 * level entries, i.e., L{0,1,2}_TABLE entries, are invalidated in addition to
1510 * any cached final-level entry, i.e., either an L{1,2}_BLOCK or L3_PAGE entry.
1511 * Otherwise, just the cached final-level entry is invalidated.
1513 static __inline void
1514 pmap_s1_invalidate_kernel(uint64_t r, bool final_only)
1517 __asm __volatile("tlbi vaale1is, %0" : : "r" (r));
1519 __asm __volatile("tlbi vaae1is, %0" : : "r" (r));
1522 static __inline void
1523 pmap_s1_invalidate_user(uint64_t r, bool final_only)
1526 __asm __volatile("tlbi vale1is, %0" : : "r" (r));
1528 __asm __volatile("tlbi vae1is, %0" : : "r" (r));
1532 * Invalidates any cached final- and optionally intermediate-level TLB entries
1533 * for the specified virtual address in the given virtual address space.
1535 static __inline void
1536 pmap_s1_invalidate_page(pmap_t pmap, vm_offset_t va, bool final_only)
1540 PMAP_ASSERT_STAGE1(pmap);
1544 if (pmap == kernel_pmap) {
1545 pmap_s1_invalidate_kernel(r, final_only);
1547 r |= ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
1548 pmap_s1_invalidate_user(r, final_only);
1554 static __inline void
1555 pmap_s2_invalidate_page(pmap_t pmap, vm_offset_t va, bool final_only)
1557 PMAP_ASSERT_STAGE2(pmap);
1558 MPASS(pmap_stage2_invalidate_range != NULL);
1559 pmap_stage2_invalidate_range(pmap_to_ttbr0(pmap), va, va + PAGE_SIZE,
1563 static __inline void
1564 pmap_invalidate_page(pmap_t pmap, vm_offset_t va, bool final_only)
1566 if (pmap->pm_stage == PM_STAGE1)
1567 pmap_s1_invalidate_page(pmap, va, final_only);
1569 pmap_s2_invalidate_page(pmap, va, final_only);
1573 * Invalidates any cached final- and optionally intermediate-level TLB entries
1574 * for the specified virtual address range in the given virtual address space.
1576 static __inline void
1577 pmap_s1_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1580 uint64_t end, r, start;
1582 PMAP_ASSERT_STAGE1(pmap);
1585 if (pmap == kernel_pmap) {
1586 start = TLBI_VA(sva);
1588 for (r = start; r < end; r += TLBI_VA_L3_INCR)
1589 pmap_s1_invalidate_kernel(r, final_only);
1591 start = end = ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
1592 start |= TLBI_VA(sva);
1593 end |= TLBI_VA(eva);
1594 for (r = start; r < end; r += TLBI_VA_L3_INCR)
1595 pmap_s1_invalidate_user(r, final_only);
1601 static __inline void
1602 pmap_s2_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1605 PMAP_ASSERT_STAGE2(pmap);
1606 MPASS(pmap_stage2_invalidate_range != NULL);
1607 pmap_stage2_invalidate_range(pmap_to_ttbr0(pmap), sva, eva, final_only);
1610 static __inline void
1611 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1614 if (pmap->pm_stage == PM_STAGE1)
1615 pmap_s1_invalidate_range(pmap, sva, eva, final_only);
1617 pmap_s2_invalidate_range(pmap, sva, eva, final_only);
1621 * Invalidates all cached intermediate- and final-level TLB entries for the
1622 * given virtual address space.
1624 static __inline void
1625 pmap_s1_invalidate_all(pmap_t pmap)
1629 PMAP_ASSERT_STAGE1(pmap);
1632 if (pmap == kernel_pmap) {
1633 __asm __volatile("tlbi vmalle1is");
1635 r = ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
1636 __asm __volatile("tlbi aside1is, %0" : : "r" (r));
1642 static __inline void
1643 pmap_s2_invalidate_all(pmap_t pmap)
1645 PMAP_ASSERT_STAGE2(pmap);
1646 MPASS(pmap_stage2_invalidate_all != NULL);
1647 pmap_stage2_invalidate_all(pmap_to_ttbr0(pmap));
1650 static __inline void
1651 pmap_invalidate_all(pmap_t pmap)
1653 if (pmap->pm_stage == PM_STAGE1)
1654 pmap_s1_invalidate_all(pmap);
1656 pmap_s2_invalidate_all(pmap);
1660 * Routine: pmap_extract
1662 * Extract the physical page address associated
1663 * with the given map/virtual_address pair.
1666 pmap_extract(pmap_t pmap, vm_offset_t va)
1668 pt_entry_t *pte, tpte;
1675 * Find the block or page map for this virtual address. pmap_pte
1676 * will return either a valid block/page entry, or NULL.
1678 pte = pmap_pte(pmap, va, &lvl);
1680 tpte = pmap_load(pte);
1681 pa = tpte & ~ATTR_MASK;
1684 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
1685 KASSERT((tpte & ATTR_DESCR_MASK) == L1_BLOCK,
1686 ("pmap_extract: Invalid L1 pte found: %lx",
1687 tpte & ATTR_DESCR_MASK));
1688 pa |= (va & L1_OFFSET);
1691 KASSERT((tpte & ATTR_DESCR_MASK) == L2_BLOCK,
1692 ("pmap_extract: Invalid L2 pte found: %lx",
1693 tpte & ATTR_DESCR_MASK));
1694 pa |= (va & L2_OFFSET);
1697 KASSERT((tpte & ATTR_DESCR_MASK) == L3_PAGE,
1698 ("pmap_extract: Invalid L3 pte found: %lx",
1699 tpte & ATTR_DESCR_MASK));
1700 pa |= (va & L3_OFFSET);
1709 * Routine: pmap_extract_and_hold
1711 * Atomically extract and hold the physical page
1712 * with the given pmap and virtual address pair
1713 * if that mapping permits the given protection.
1716 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1718 pt_entry_t *pte, tpte;
1726 pte = pmap_pte(pmap, va, &lvl);
1728 tpte = pmap_load(pte);
1730 KASSERT(lvl > 0 && lvl <= 3,
1731 ("pmap_extract_and_hold: Invalid level %d", lvl));
1733 * Check that the pte is either a L3 page, or a L1 or L2 block
1734 * entry. We can assume L1_BLOCK == L2_BLOCK.
1736 KASSERT((lvl == 3 && (tpte & ATTR_DESCR_MASK) == L3_PAGE) ||
1737 (lvl < 3 && (tpte & ATTR_DESCR_MASK) == L1_BLOCK),
1738 ("pmap_extract_and_hold: Invalid pte at L%d: %lx", lvl,
1739 tpte & ATTR_DESCR_MASK));
1742 if ((prot & VM_PROT_WRITE) == 0)
1744 else if (pmap->pm_stage == PM_STAGE1 &&
1745 (tpte & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP(ATTR_S1_AP_RW))
1747 else if (pmap->pm_stage == PM_STAGE2 &&
1748 ((tpte & ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE)) ==
1749 ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE)))
1755 off = va & L1_OFFSET;
1758 off = va & L2_OFFSET;
1764 m = PHYS_TO_VM_PAGE((tpte & ~ATTR_MASK) | off);
1765 if (m != NULL && !vm_page_wire_mapped(m))
1774 * Walks the page tables to translate a kernel virtual address to a
1775 * physical address. Returns true if the kva is valid and stores the
1776 * physical address in pa if it is not NULL.
1778 * See the comment above data_abort() for the rationale for specifying
1779 * NO_PERTHREAD_SSP here.
1781 bool NO_PERTHREAD_SSP
1782 pmap_klookup(vm_offset_t va, vm_paddr_t *pa)
1784 pt_entry_t *pte, tpte;
1789 * Disable interrupts so we don't get interrupted between asking
1790 * for address translation, and getting the result back.
1792 intr = intr_disable();
1793 par = arm64_address_translate_s1e1r(va);
1796 if (PAR_SUCCESS(par)) {
1798 *pa = (par & PAR_PA_MASK) | (va & PAR_LOW_MASK);
1803 * Fall back to walking the page table. The address translation
1804 * instruction may fail when the page is in a break-before-make
1805 * sequence. As we only clear the valid bit in said sequence we
1806 * can walk the page table to find the physical address.
1809 pte = pmap_l1(kernel_pmap, va);
1814 * A concurrent pmap_update_entry() will clear the entry's valid bit
1815 * but leave the rest of the entry unchanged. Therefore, we treat a
1816 * non-zero entry as being valid, and we ignore the valid bit when
1817 * determining whether the entry maps a block, page, or table.
1819 tpte = pmap_load(pte);
1822 if ((tpte & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
1824 *pa = (tpte & ~ATTR_MASK) | (va & L1_OFFSET);
1827 pte = pmap_l1_to_l2(&tpte, va);
1828 tpte = pmap_load(pte);
1831 if ((tpte & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
1833 *pa = (tpte & ~ATTR_MASK) | (va & L2_OFFSET);
1836 pte = pmap_l2_to_l3(&tpte, va);
1837 tpte = pmap_load(pte);
1841 *pa = (tpte & ~ATTR_MASK) | (va & L3_OFFSET);
1846 pmap_kextract(vm_offset_t va)
1850 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
1851 return (DMAP_TO_PHYS(va));
1853 if (pmap_klookup(va, &pa) == false)
1858 /***************************************************
1859 * Low level mapping routines.....
1860 ***************************************************/
1863 pmap_kenter(vm_offset_t sva, vm_size_t size, vm_paddr_t pa, int mode)
1866 pt_entry_t *pte, attr;
1870 KASSERT((pa & L3_OFFSET) == 0,
1871 ("pmap_kenter: Invalid physical address"));
1872 KASSERT((sva & L3_OFFSET) == 0,
1873 ("pmap_kenter: Invalid virtual address"));
1874 KASSERT((size & PAGE_MASK) == 0,
1875 ("pmap_kenter: Mapping is not page-sized"));
1877 attr = ATTR_DEFAULT | ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_S1_XN |
1878 ATTR_S1_IDX(mode) | L3_PAGE;
1881 pde = pmap_pde(kernel_pmap, va, &lvl);
1882 KASSERT(pde != NULL,
1883 ("pmap_kenter: Invalid page entry, va: 0x%lx", va));
1884 KASSERT(lvl == 2, ("pmap_kenter: Invalid level %d", lvl));
1886 pte = pmap_l2_to_l3(pde, va);
1887 pmap_load_store(pte, (pa & ~L3_OFFSET) | attr);
1893 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
1897 pmap_kenter_device(vm_offset_t sva, vm_size_t size, vm_paddr_t pa)
1900 pmap_kenter(sva, size, pa, VM_MEMATTR_DEVICE);
1904 * Remove a page from the kernel pagetables.
1907 pmap_kremove(vm_offset_t va)
1911 pte = pmap_pte_exists(kernel_pmap, va, 3, __func__);
1913 pmap_s1_invalidate_page(kernel_pmap, va, true);
1917 pmap_kremove_device(vm_offset_t sva, vm_size_t size)
1922 KASSERT((sva & L3_OFFSET) == 0,
1923 ("pmap_kremove_device: Invalid virtual address"));
1924 KASSERT((size & PAGE_MASK) == 0,
1925 ("pmap_kremove_device: Mapping is not page-sized"));
1929 pte = pmap_pte_exists(kernel_pmap, va, 3, __func__);
1935 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
1939 * Used to map a range of physical addresses into kernel
1940 * virtual address space.
1942 * The value passed in '*virt' is a suggested virtual address for
1943 * the mapping. Architectures which can support a direct-mapped
1944 * physical to virtual region can return the appropriate address
1945 * within that region, leaving '*virt' unchanged. Other
1946 * architectures should map the pages starting at '*virt' and
1947 * update '*virt' with the first usable address after the mapped
1951 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
1953 return PHYS_TO_DMAP(start);
1957 * Add a list of wired pages to the kva
1958 * this routine is only used for temporary
1959 * kernel mappings that do not need to have
1960 * page modification or references recorded.
1961 * Note that old mappings are simply written
1962 * over. The page *must* be wired.
1963 * Note: SMP coherent. Uses a ranged shootdown IPI.
1966 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
1969 pt_entry_t *pte, pa;
1975 for (i = 0; i < count; i++) {
1976 pde = pmap_pde(kernel_pmap, va, &lvl);
1977 KASSERT(pde != NULL,
1978 ("pmap_qenter: Invalid page entry, va: 0x%lx", va));
1980 ("pmap_qenter: Invalid level %d", lvl));
1983 pa = VM_PAGE_TO_PHYS(m) | ATTR_DEFAULT |
1984 ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_S1_XN |
1985 ATTR_S1_IDX(m->md.pv_memattr) | L3_PAGE;
1986 pte = pmap_l2_to_l3(pde, va);
1987 pmap_load_store(pte, pa);
1991 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
1995 * This routine tears out page mappings from the
1996 * kernel -- it is meant only for temporary mappings.
1999 pmap_qremove(vm_offset_t sva, int count)
2004 KASSERT(ADDR_IS_CANONICAL(sva),
2005 ("%s: Address not in canonical form: %lx", __func__, sva));
2006 KASSERT(ADDR_IS_KERNEL(sva), ("usermode va %lx", sva));
2009 while (count-- > 0) {
2010 pte = pmap_pte_exists(kernel_pmap, va, 3, NULL);
2017 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
2020 /***************************************************
2021 * Page table page management routines.....
2022 ***************************************************/
2024 * Schedule the specified unused page table page to be freed. Specifically,
2025 * add the page to the specified list of pages that will be released to the
2026 * physical memory manager after the TLB has been updated.
2028 static __inline void
2029 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2030 boolean_t set_PG_ZERO)
2034 m->flags |= PG_ZERO;
2036 m->flags &= ~PG_ZERO;
2037 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2041 * Decrements a page table page's reference count, which is used to record the
2042 * number of valid page table entries within the page. If the reference count
2043 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2044 * page table page was unmapped and FALSE otherwise.
2046 static inline boolean_t
2047 pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2051 if (m->ref_count == 0) {
2052 _pmap_unwire_l3(pmap, va, m, free);
2059 _pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2062 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2064 * unmap the page table page
2066 if (m->pindex >= (NUL2E + NUL1E)) {
2070 l0 = pmap_l0(pmap, va);
2072 } else if (m->pindex >= NUL2E) {
2076 l1 = pmap_l1(pmap, va);
2082 l2 = pmap_l2(pmap, va);
2085 pmap_resident_count_dec(pmap, 1);
2086 if (m->pindex < NUL2E) {
2087 /* We just released an l3, unhold the matching l2 */
2088 pd_entry_t *l1, tl1;
2091 l1 = pmap_l1(pmap, va);
2092 tl1 = pmap_load(l1);
2093 l2pg = PHYS_TO_VM_PAGE(tl1 & ~ATTR_MASK);
2094 pmap_unwire_l3(pmap, va, l2pg, free);
2095 } else if (m->pindex < (NUL2E + NUL1E)) {
2096 /* We just released an l2, unhold the matching l1 */
2097 pd_entry_t *l0, tl0;
2100 l0 = pmap_l0(pmap, va);
2101 tl0 = pmap_load(l0);
2102 l1pg = PHYS_TO_VM_PAGE(tl0 & ~ATTR_MASK);
2103 pmap_unwire_l3(pmap, va, l1pg, free);
2105 pmap_invalidate_page(pmap, va, false);
2108 * Put page on a list so that it is released after
2109 * *ALL* TLB shootdown is done
2111 pmap_add_delayed_free_list(m, free, TRUE);
2115 * After removing a page table entry, this routine is used to
2116 * conditionally free the page, and manage the reference count.
2119 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2120 struct spglist *free)
2124 KASSERT(ADDR_IS_CANONICAL(va),
2125 ("%s: Address not in canonical form: %lx", __func__, va));
2126 if (ADDR_IS_KERNEL(va))
2128 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2129 mpte = PHYS_TO_VM_PAGE(ptepde & ~ATTR_MASK);
2130 return (pmap_unwire_l3(pmap, va, mpte, free));
2134 * Release a page table page reference after a failed attempt to create a
2138 pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
2140 struct spglist free;
2143 if (pmap_unwire_l3(pmap, va, mpte, &free))
2144 vm_page_free_pages_toq(&free, true);
2148 pmap_pinit0(pmap_t pmap)
2151 PMAP_LOCK_INIT(pmap);
2152 bzero(&pmap->pm_stats, sizeof(pmap->pm_stats));
2153 pmap->pm_l0_paddr = READ_SPECIALREG(ttbr0_el1);
2154 pmap->pm_l0 = (pd_entry_t *)PHYS_TO_DMAP(pmap->pm_l0_paddr);
2155 vm_radix_init(&pmap->pm_root);
2156 pmap->pm_cookie = COOKIE_FROM(ASID_RESERVED_FOR_PID_0, INT_MIN);
2157 pmap->pm_stage = PM_STAGE1;
2158 pmap->pm_levels = 4;
2159 pmap->pm_ttbr = pmap->pm_l0_paddr;
2160 pmap->pm_asid_set = &asids;
2162 PCPU_SET(curpmap, pmap);
2166 pmap_pinit_stage(pmap_t pmap, enum pmap_stage stage, int levels)
2171 * allocate the l0 page
2173 m = vm_page_alloc_noobj(VM_ALLOC_WAITOK | VM_ALLOC_WIRED |
2175 pmap->pm_l0_paddr = VM_PAGE_TO_PHYS(m);
2176 pmap->pm_l0 = (pd_entry_t *)PHYS_TO_DMAP(pmap->pm_l0_paddr);
2178 vm_radix_init(&pmap->pm_root);
2179 bzero(&pmap->pm_stats, sizeof(pmap->pm_stats));
2180 pmap->pm_cookie = COOKIE_FROM(-1, INT_MAX);
2182 MPASS(levels == 3 || levels == 4);
2183 pmap->pm_levels = levels;
2184 pmap->pm_stage = stage;
2187 pmap->pm_asid_set = &asids;
2190 pmap->pm_asid_set = &vmids;
2193 panic("%s: Invalid pmap type %d", __func__, stage);
2197 /* XXX Temporarily disable deferred ASID allocation. */
2198 pmap_alloc_asid(pmap);
2201 * Allocate the level 1 entry to use as the root. This will increase
2202 * the refcount on the level 1 page so it won't be removed until
2203 * pmap_release() is called.
2205 if (pmap->pm_levels == 3) {
2207 m = _pmap_alloc_l3(pmap, NUL2E + NUL1E, NULL);
2210 pmap->pm_ttbr = VM_PAGE_TO_PHYS(m);
2216 pmap_pinit(pmap_t pmap)
2219 return (pmap_pinit_stage(pmap, PM_STAGE1, 4));
2223 * This routine is called if the desired page table page does not exist.
2225 * If page table page allocation fails, this routine may sleep before
2226 * returning NULL. It sleeps only if a lock pointer was given.
2228 * Note: If a page allocation fails at page table level two or three,
2229 * one or two pages may be held during the wait, only to be released
2230 * afterwards. This conservative approach is easily argued to avoid
2234 _pmap_alloc_l3(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2236 vm_page_t m, l1pg, l2pg;
2238 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2241 * Allocate a page table page.
2243 if ((m = vm_page_alloc_noobj(VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2244 if (lockp != NULL) {
2245 RELEASE_PV_LIST_LOCK(lockp);
2252 * Indicate the need to retry. While waiting, the page table
2253 * page may have been allocated.
2257 m->pindex = ptepindex;
2260 * Because of AArch64's weak memory consistency model, we must have a
2261 * barrier here to ensure that the stores for zeroing "m", whether by
2262 * pmap_zero_page() or an earlier function, are visible before adding
2263 * "m" to the page table. Otherwise, a page table walk by another
2264 * processor's MMU could see the mapping to "m" and a stale, non-zero
2270 * Map the pagetable page into the process address space, if
2271 * it isn't already there.
2274 if (ptepindex >= (NUL2E + NUL1E)) {
2275 pd_entry_t *l0p, l0e;
2276 vm_pindex_t l0index;
2278 l0index = ptepindex - (NUL2E + NUL1E);
2279 l0p = &pmap->pm_l0[l0index];
2280 KASSERT((pmap_load(l0p) & ATTR_DESCR_VALID) == 0,
2281 ("%s: L0 entry %#lx is valid", __func__, pmap_load(l0p)));
2282 l0e = VM_PAGE_TO_PHYS(m) | L0_TABLE;
2285 * Mark all kernel memory as not accessible from userspace
2286 * and userspace memory as not executable from the kernel.
2287 * This has been done for the bootstrap L0 entries in
2290 if (pmap == kernel_pmap)
2291 l0e |= TATTR_UXN_TABLE | TATTR_AP_TABLE_NO_EL0;
2293 l0e |= TATTR_PXN_TABLE;
2294 pmap_store(l0p, l0e);
2295 } else if (ptepindex >= NUL2E) {
2296 vm_pindex_t l0index, l1index;
2297 pd_entry_t *l0, *l1;
2300 l1index = ptepindex - NUL2E;
2301 l0index = l1index >> Ln_ENTRIES_SHIFT;
2303 l0 = &pmap->pm_l0[l0index];
2304 tl0 = pmap_load(l0);
2306 /* recurse for allocating page dir */
2307 if (_pmap_alloc_l3(pmap, NUL2E + NUL1E + l0index,
2309 vm_page_unwire_noq(m);
2310 vm_page_free_zero(m);
2314 l1pg = PHYS_TO_VM_PAGE(tl0 & ~ATTR_MASK);
2318 l1 = (pd_entry_t *)PHYS_TO_DMAP(pmap_load(l0) & ~ATTR_MASK);
2319 l1 = &l1[ptepindex & Ln_ADDR_MASK];
2320 KASSERT((pmap_load(l1) & ATTR_DESCR_VALID) == 0,
2321 ("%s: L1 entry %#lx is valid", __func__, pmap_load(l1)));
2322 pmap_store(l1, VM_PAGE_TO_PHYS(m) | L1_TABLE);
2324 vm_pindex_t l0index, l1index;
2325 pd_entry_t *l0, *l1, *l2;
2326 pd_entry_t tl0, tl1;
2328 l1index = ptepindex >> Ln_ENTRIES_SHIFT;
2329 l0index = l1index >> Ln_ENTRIES_SHIFT;
2331 l0 = &pmap->pm_l0[l0index];
2332 tl0 = pmap_load(l0);
2334 /* recurse for allocating page dir */
2335 if (_pmap_alloc_l3(pmap, NUL2E + l1index,
2337 vm_page_unwire_noq(m);
2338 vm_page_free_zero(m);
2341 tl0 = pmap_load(l0);
2342 l1 = (pd_entry_t *)PHYS_TO_DMAP(tl0 & ~ATTR_MASK);
2343 l1 = &l1[l1index & Ln_ADDR_MASK];
2345 l1 = (pd_entry_t *)PHYS_TO_DMAP(tl0 & ~ATTR_MASK);
2346 l1 = &l1[l1index & Ln_ADDR_MASK];
2347 tl1 = pmap_load(l1);
2349 /* recurse for allocating page dir */
2350 if (_pmap_alloc_l3(pmap, NUL2E + l1index,
2352 vm_page_unwire_noq(m);
2353 vm_page_free_zero(m);
2357 l2pg = PHYS_TO_VM_PAGE(tl1 & ~ATTR_MASK);
2362 l2 = (pd_entry_t *)PHYS_TO_DMAP(pmap_load(l1) & ~ATTR_MASK);
2363 l2 = &l2[ptepindex & Ln_ADDR_MASK];
2364 KASSERT((pmap_load(l2) & ATTR_DESCR_VALID) == 0,
2365 ("%s: L2 entry %#lx is valid", __func__, pmap_load(l2)));
2366 pmap_store(l2, VM_PAGE_TO_PHYS(m) | L2_TABLE);
2369 pmap_resident_count_inc(pmap, 1);
2375 pmap_alloc_l2(pmap_t pmap, vm_offset_t va, vm_page_t *l2pgp,
2376 struct rwlock **lockp)
2378 pd_entry_t *l1, *l2;
2380 vm_pindex_t l2pindex;
2382 KASSERT(ADDR_IS_CANONICAL(va),
2383 ("%s: Address not in canonical form: %lx", __func__, va));
2386 l1 = pmap_l1(pmap, va);
2387 if (l1 != NULL && (pmap_load(l1) & ATTR_DESCR_MASK) == L1_TABLE) {
2388 l2 = pmap_l1_to_l2(l1, va);
2389 if (!ADDR_IS_KERNEL(va)) {
2390 /* Add a reference to the L2 page. */
2391 l2pg = PHYS_TO_VM_PAGE(pmap_load(l1) & ~ATTR_MASK);
2395 } else if (!ADDR_IS_KERNEL(va)) {
2396 /* Allocate a L2 page. */
2397 l2pindex = pmap_l2_pindex(va) >> Ln_ENTRIES_SHIFT;
2398 l2pg = _pmap_alloc_l3(pmap, NUL2E + l2pindex, lockp);
2405 l2 = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(l2pg));
2406 l2 = &l2[pmap_l2_index(va)];
2408 panic("pmap_alloc_l2: missing page table page for va %#lx",
2415 pmap_alloc_l3(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2417 vm_pindex_t ptepindex;
2418 pd_entry_t *pde, tpde;
2426 * Calculate pagetable page index
2428 ptepindex = pmap_l2_pindex(va);
2431 * Get the page directory entry
2433 pde = pmap_pde(pmap, va, &lvl);
2436 * If the page table page is mapped, we just increment the hold count,
2437 * and activate it. If we get a level 2 pde it will point to a level 3
2445 pte = pmap_l0_to_l1(pde, va);
2446 KASSERT(pmap_load(pte) == 0,
2447 ("pmap_alloc_l3: TODO: l0 superpages"));
2452 pte = pmap_l1_to_l2(pde, va);
2453 KASSERT(pmap_load(pte) == 0,
2454 ("pmap_alloc_l3: TODO: l1 superpages"));
2458 tpde = pmap_load(pde);
2460 m = PHYS_TO_VM_PAGE(tpde & ~ATTR_MASK);
2466 panic("pmap_alloc_l3: Invalid level %d", lvl);
2470 * Here if the pte page isn't mapped, or if it has been deallocated.
2472 m = _pmap_alloc_l3(pmap, ptepindex, lockp);
2473 if (m == NULL && lockp != NULL)
2479 /***************************************************
2480 * Pmap allocation/deallocation routines.
2481 ***************************************************/
2484 * Release any resources held by the given physical map.
2485 * Called when a pmap initialized by pmap_pinit is being released.
2486 * Should only be called if the map contains no valid mappings.
2489 pmap_release(pmap_t pmap)
2491 boolean_t rv __diagused;
2492 struct spglist free;
2493 struct asid_set *set;
2497 if (pmap->pm_levels != 4) {
2498 PMAP_ASSERT_STAGE2(pmap);
2499 KASSERT(pmap->pm_stats.resident_count == 1,
2500 ("pmap_release: pmap resident count %ld != 0",
2501 pmap->pm_stats.resident_count));
2502 KASSERT((pmap->pm_l0[0] & ATTR_DESCR_VALID) == ATTR_DESCR_VALID,
2503 ("pmap_release: Invalid l0 entry: %lx", pmap->pm_l0[0]));
2506 m = PHYS_TO_VM_PAGE(pmap->pm_ttbr);
2508 rv = pmap_unwire_l3(pmap, 0, m, &free);
2511 vm_page_free_pages_toq(&free, true);
2514 KASSERT(pmap->pm_stats.resident_count == 0,
2515 ("pmap_release: pmap resident count %ld != 0",
2516 pmap->pm_stats.resident_count));
2517 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2518 ("pmap_release: pmap has reserved page table page(s)"));
2520 set = pmap->pm_asid_set;
2521 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
2524 * Allow the ASID to be reused. In stage 2 VMIDs we don't invalidate
2525 * the entries when removing them so rely on a later tlb invalidation.
2526 * this will happen when updating the VMID generation. Because of this
2527 * we don't reuse VMIDs within a generation.
2529 if (pmap->pm_stage == PM_STAGE1) {
2530 mtx_lock_spin(&set->asid_set_mutex);
2531 if (COOKIE_TO_EPOCH(pmap->pm_cookie) == set->asid_epoch) {
2532 asid = COOKIE_TO_ASID(pmap->pm_cookie);
2533 KASSERT(asid >= ASID_FIRST_AVAILABLE &&
2534 asid < set->asid_set_size,
2535 ("pmap_release: pmap cookie has out-of-range asid"));
2536 bit_clear(set->asid_set, asid);
2538 mtx_unlock_spin(&set->asid_set_mutex);
2541 m = PHYS_TO_VM_PAGE(pmap->pm_l0_paddr);
2542 vm_page_unwire_noq(m);
2543 vm_page_free_zero(m);
2547 kvm_size(SYSCTL_HANDLER_ARGS)
2549 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2551 return sysctl_handle_long(oidp, &ksize, 0, req);
2553 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
2554 0, 0, kvm_size, "LU",
2558 kvm_free(SYSCTL_HANDLER_ARGS)
2560 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2562 return sysctl_handle_long(oidp, &kfree, 0, req);
2564 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
2565 0, 0, kvm_free, "LU",
2566 "Amount of KVM free");
2569 * grow the number of kernel page table entries, if needed
2572 pmap_growkernel(vm_offset_t addr)
2576 pd_entry_t *l0, *l1, *l2;
2578 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2580 addr = roundup2(addr, L2_SIZE);
2581 if (addr - 1 >= vm_map_max(kernel_map))
2582 addr = vm_map_max(kernel_map);
2583 while (kernel_vm_end < addr) {
2584 l0 = pmap_l0(kernel_pmap, kernel_vm_end);
2585 KASSERT(pmap_load(l0) != 0,
2586 ("pmap_growkernel: No level 0 kernel entry"));
2588 l1 = pmap_l0_to_l1(l0, kernel_vm_end);
2589 if (pmap_load(l1) == 0) {
2590 /* We need a new PDP entry */
2591 nkpg = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT |
2592 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2594 panic("pmap_growkernel: no memory to grow kernel");
2595 nkpg->pindex = kernel_vm_end >> L1_SHIFT;
2596 /* See the dmb() in _pmap_alloc_l3(). */
2598 paddr = VM_PAGE_TO_PHYS(nkpg);
2599 pmap_store(l1, paddr | L1_TABLE);
2600 continue; /* try again */
2602 l2 = pmap_l1_to_l2(l1, kernel_vm_end);
2603 if (pmap_load(l2) != 0) {
2604 kernel_vm_end = (kernel_vm_end + L2_SIZE) & ~L2_OFFSET;
2605 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
2606 kernel_vm_end = vm_map_max(kernel_map);
2612 nkpg = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED |
2615 panic("pmap_growkernel: no memory to grow kernel");
2616 nkpg->pindex = kernel_vm_end >> L2_SHIFT;
2617 /* See the dmb() in _pmap_alloc_l3(). */
2619 paddr = VM_PAGE_TO_PHYS(nkpg);
2620 pmap_store(l2, paddr | L2_TABLE);
2622 kernel_vm_end = (kernel_vm_end + L2_SIZE) & ~L2_OFFSET;
2623 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
2624 kernel_vm_end = vm_map_max(kernel_map);
2630 /***************************************************
2631 * page management routines.
2632 ***************************************************/
2634 static const uint64_t pc_freemask[_NPCM] = {
2635 [0 ... _NPCM - 2] = PC_FREEN,
2636 [_NPCM - 1] = PC_FREEL
2640 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2642 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2643 "Current number of pv entry chunks");
2644 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2645 "Current number of pv entry chunks allocated");
2646 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2647 "Current number of pv entry chunks frees");
2648 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
2649 "Number of times tried to get a chunk page but failed.");
2651 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
2652 static int pv_entry_spare;
2654 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2655 "Current number of pv entry frees");
2656 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
2657 "Current number of pv entry allocs");
2658 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2659 "Current number of pv entries");
2660 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2661 "Current number of spare pv entries");
2665 * We are in a serious low memory condition. Resort to
2666 * drastic measures to free some pages so we can allocate
2667 * another pv entry chunk.
2669 * Returns NULL if PV entries were reclaimed from the specified pmap.
2671 * We do not, however, unmap 2mpages because subsequent accesses will
2672 * allocate per-page pv entries until repromotion occurs, thereby
2673 * exacerbating the shortage of free pv entries.
2676 reclaim_pv_chunk_domain(pmap_t locked_pmap, struct rwlock **lockp, int domain)
2678 struct pv_chunks_list *pvc;
2679 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
2680 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
2681 struct md_page *pvh;
2683 pmap_t next_pmap, pmap;
2684 pt_entry_t *pte, tpte;
2688 struct spglist free;
2690 int bit, field, freed, lvl;
2692 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2693 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
2698 bzero(&pc_marker_b, sizeof(pc_marker_b));
2699 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
2700 pc_marker = (struct pv_chunk *)&pc_marker_b;
2701 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
2703 pvc = &pv_chunks[domain];
2704 mtx_lock(&pvc->pvc_lock);
2705 pvc->active_reclaims++;
2706 TAILQ_INSERT_HEAD(&pvc->pvc_list, pc_marker, pc_lru);
2707 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc_marker_end, pc_lru);
2708 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
2709 SLIST_EMPTY(&free)) {
2710 next_pmap = pc->pc_pmap;
2711 if (next_pmap == NULL) {
2713 * The next chunk is a marker. However, it is
2714 * not our marker, so active_reclaims must be
2715 * > 1. Consequently, the next_chunk code
2716 * will not rotate the pv_chunks list.
2720 mtx_unlock(&pvc->pvc_lock);
2723 * A pv_chunk can only be removed from the pc_lru list
2724 * when both pvc->pvc_lock is owned and the
2725 * corresponding pmap is locked.
2727 if (pmap != next_pmap) {
2728 if (pmap != NULL && pmap != locked_pmap)
2731 /* Avoid deadlock and lock recursion. */
2732 if (pmap > locked_pmap) {
2733 RELEASE_PV_LIST_LOCK(lockp);
2735 mtx_lock(&pvc->pvc_lock);
2737 } else if (pmap != locked_pmap) {
2738 if (PMAP_TRYLOCK(pmap)) {
2739 mtx_lock(&pvc->pvc_lock);
2742 pmap = NULL; /* pmap is not locked */
2743 mtx_lock(&pvc->pvc_lock);
2744 pc = TAILQ_NEXT(pc_marker, pc_lru);
2746 pc->pc_pmap != next_pmap)
2754 * Destroy every non-wired, 4 KB page mapping in the chunk.
2757 for (field = 0; field < _NPCM; field++) {
2758 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2759 inuse != 0; inuse &= ~(1UL << bit)) {
2760 bit = ffsl(inuse) - 1;
2761 pv = &pc->pc_pventry[field * 64 + bit];
2763 pde = pmap_pde(pmap, va, &lvl);
2766 pte = pmap_l2_to_l3(pde, va);
2767 tpte = pmap_load(pte);
2768 if ((tpte & ATTR_SW_WIRED) != 0)
2770 tpte = pmap_load_clear(pte);
2771 m = PHYS_TO_VM_PAGE(tpte & ~ATTR_MASK);
2772 if (pmap_pte_dirty(pmap, tpte))
2774 if ((tpte & ATTR_AF) != 0) {
2775 pmap_s1_invalidate_page(pmap, va, true);
2776 vm_page_aflag_set(m, PGA_REFERENCED);
2778 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
2779 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
2781 if (TAILQ_EMPTY(&m->md.pv_list) &&
2782 (m->flags & PG_FICTITIOUS) == 0) {
2783 pvh = page_to_pvh(m);
2784 if (TAILQ_EMPTY(&pvh->pv_list)) {
2785 vm_page_aflag_clear(m,
2789 pc->pc_map[field] |= 1UL << bit;
2790 pmap_unuse_pt(pmap, va, pmap_load(pde), &free);
2795 mtx_lock(&pvc->pvc_lock);
2798 /* Every freed mapping is for a 4 KB page. */
2799 pmap_resident_count_dec(pmap, freed);
2800 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
2801 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
2802 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
2803 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2804 if (pc_is_free(pc)) {
2805 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
2806 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
2807 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
2808 /* Entire chunk is free; return it. */
2809 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
2810 dump_drop_page(m_pc->phys_addr);
2811 mtx_lock(&pvc->pvc_lock);
2812 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
2815 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2816 mtx_lock(&pvc->pvc_lock);
2817 /* One freed pv entry in locked_pmap is sufficient. */
2818 if (pmap == locked_pmap)
2822 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
2823 TAILQ_INSERT_AFTER(&pvc->pvc_list, pc, pc_marker, pc_lru);
2824 if (pvc->active_reclaims == 1 && pmap != NULL) {
2826 * Rotate the pv chunks list so that we do not
2827 * scan the same pv chunks that could not be
2828 * freed (because they contained a wired
2829 * and/or superpage mapping) on every
2830 * invocation of reclaim_pv_chunk().
2832 while ((pc = TAILQ_FIRST(&pvc->pvc_list)) != pc_marker){
2833 MPASS(pc->pc_pmap != NULL);
2834 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
2835 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
2839 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
2840 TAILQ_REMOVE(&pvc->pvc_list, pc_marker_end, pc_lru);
2841 pvc->active_reclaims--;
2842 mtx_unlock(&pvc->pvc_lock);
2843 if (pmap != NULL && pmap != locked_pmap)
2845 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
2846 m_pc = SLIST_FIRST(&free);
2847 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2848 /* Recycle a freed page table page. */
2849 m_pc->ref_count = 1;
2851 vm_page_free_pages_toq(&free, true);
2856 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
2861 domain = PCPU_GET(domain);
2862 for (i = 0; i < vm_ndomains; i++) {
2863 m = reclaim_pv_chunk_domain(locked_pmap, lockp, domain);
2866 domain = (domain + 1) % vm_ndomains;
2873 * free the pv_entry back to the free list
2876 free_pv_entry(pmap_t pmap, pv_entry_t pv)
2878 struct pv_chunk *pc;
2879 int idx, field, bit;
2881 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2882 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
2883 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
2884 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
2885 pc = pv_to_chunk(pv);
2886 idx = pv - &pc->pc_pventry[0];
2889 pc->pc_map[field] |= 1ul << bit;
2890 if (!pc_is_free(pc)) {
2891 /* 98% of the time, pc is already at the head of the list. */
2892 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
2893 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2894 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2898 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2903 free_pv_chunk_dequeued(struct pv_chunk *pc)
2907 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
2908 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
2909 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
2910 /* entire chunk is free, return it */
2911 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
2912 dump_drop_page(m->phys_addr);
2913 vm_page_unwire_noq(m);
2918 free_pv_chunk(struct pv_chunk *pc)
2920 struct pv_chunks_list *pvc;
2922 pvc = &pv_chunks[pc_to_domain(pc)];
2923 mtx_lock(&pvc->pvc_lock);
2924 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
2925 mtx_unlock(&pvc->pvc_lock);
2926 free_pv_chunk_dequeued(pc);
2930 free_pv_chunk_batch(struct pv_chunklist *batch)
2932 struct pv_chunks_list *pvc;
2933 struct pv_chunk *pc, *npc;
2936 for (i = 0; i < vm_ndomains; i++) {
2937 if (TAILQ_EMPTY(&batch[i]))
2939 pvc = &pv_chunks[i];
2940 mtx_lock(&pvc->pvc_lock);
2941 TAILQ_FOREACH(pc, &batch[i], pc_list) {
2942 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
2944 mtx_unlock(&pvc->pvc_lock);
2947 for (i = 0; i < vm_ndomains; i++) {
2948 TAILQ_FOREACH_SAFE(pc, &batch[i], pc_list, npc) {
2949 free_pv_chunk_dequeued(pc);
2955 * Returns a new PV entry, allocating a new PV chunk from the system when
2956 * needed. If this PV chunk allocation fails and a PV list lock pointer was
2957 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
2960 * The given PV list lock may be released.
2963 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
2965 struct pv_chunks_list *pvc;
2968 struct pv_chunk *pc;
2971 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2972 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
2974 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
2976 for (field = 0; field < _NPCM; field++) {
2977 if (pc->pc_map[field]) {
2978 bit = ffsl(pc->pc_map[field]) - 1;
2982 if (field < _NPCM) {
2983 pv = &pc->pc_pventry[field * 64 + bit];
2984 pc->pc_map[field] &= ~(1ul << bit);
2985 /* If this was the last item, move it to tail */
2986 if (pc_is_full(pc)) {
2987 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2988 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
2991 PV_STAT(atomic_add_long(&pv_entry_count, 1));
2992 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
2996 /* No free items, allocate another chunk */
2997 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
2999 if (lockp == NULL) {
3000 PV_STAT(pc_chunk_tryfail++);
3003 m = reclaim_pv_chunk(pmap, lockp);
3007 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3008 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3009 dump_add_page(m->phys_addr);
3010 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3012 memcpy(pc->pc_map, pc_freemask, sizeof(pc_freemask));
3013 pc->pc_map[0] &= ~1ul; /* preallocated bit 0 */
3014 pvc = &pv_chunks[vm_page_domain(m)];
3015 mtx_lock(&pvc->pvc_lock);
3016 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
3017 mtx_unlock(&pvc->pvc_lock);
3018 pv = &pc->pc_pventry[0];
3019 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3020 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3021 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3026 * Ensure that the number of spare PV entries in the specified pmap meets or
3027 * exceeds the given count, "needed".
3029 * The given PV list lock may be released.
3032 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3034 struct pv_chunks_list *pvc;
3035 struct pch new_tail[PMAP_MEMDOM];
3036 struct pv_chunk *pc;
3041 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3042 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3045 * Newly allocated PV chunks must be stored in a private list until
3046 * the required number of PV chunks have been allocated. Otherwise,
3047 * reclaim_pv_chunk() could recycle one of these chunks. In
3048 * contrast, these chunks must be added to the pmap upon allocation.
3050 for (i = 0; i < PMAP_MEMDOM; i++)
3051 TAILQ_INIT(&new_tail[i]);
3054 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3055 bit_count((bitstr_t *)pc->pc_map, 0,
3056 sizeof(pc->pc_map) * NBBY, &free);
3060 if (avail >= needed)
3063 for (reclaimed = false; avail < needed; avail += _NPCPV) {
3064 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
3066 m = reclaim_pv_chunk(pmap, lockp);
3071 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3072 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3073 dump_add_page(m->phys_addr);
3074 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3076 memcpy(pc->pc_map, pc_freemask, sizeof(pc_freemask));
3077 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3078 TAILQ_INSERT_TAIL(&new_tail[vm_page_domain(m)], pc, pc_lru);
3079 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3082 * The reclaim might have freed a chunk from the current pmap.
3083 * If that chunk contained available entries, we need to
3084 * re-count the number of available entries.
3089 for (i = 0; i < vm_ndomains; i++) {
3090 if (TAILQ_EMPTY(&new_tail[i]))
3092 pvc = &pv_chunks[i];
3093 mtx_lock(&pvc->pvc_lock);
3094 TAILQ_CONCAT(&pvc->pvc_list, &new_tail[i], pc_lru);
3095 mtx_unlock(&pvc->pvc_lock);
3100 * First find and then remove the pv entry for the specified pmap and virtual
3101 * address from the specified pv list. Returns the pv entry if found and NULL
3102 * otherwise. This operation can be performed on pv lists for either 4KB or
3103 * 2MB page mappings.
3105 static __inline pv_entry_t
3106 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3110 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3111 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3112 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3121 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3122 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3123 * entries for each of the 4KB page mappings.
3126 pmap_pv_demote_l2(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3127 struct rwlock **lockp)
3129 struct md_page *pvh;
3130 struct pv_chunk *pc;
3132 vm_offset_t va_last;
3136 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3137 KASSERT((va & L2_OFFSET) == 0,
3138 ("pmap_pv_demote_l2: va is not 2mpage aligned"));
3139 KASSERT((pa & L2_OFFSET) == 0,
3140 ("pmap_pv_demote_l2: pa is not 2mpage aligned"));
3141 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3144 * Transfer the 2mpage's pv entry for this mapping to the first
3145 * page's pv list. Once this transfer begins, the pv list lock
3146 * must not be released until the last pv entry is reinstantiated.
3148 pvh = pa_to_pvh(pa);
3149 pv = pmap_pvh_remove(pvh, pmap, va);
3150 KASSERT(pv != NULL, ("pmap_pv_demote_l2: pv not found"));
3151 m = PHYS_TO_VM_PAGE(pa);
3152 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3154 /* Instantiate the remaining Ln_ENTRIES - 1 pv entries. */
3155 PV_STAT(atomic_add_long(&pv_entry_allocs, Ln_ENTRIES - 1));
3156 va_last = va + L2_SIZE - PAGE_SIZE;
3158 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3159 KASSERT(!pc_is_full(pc), ("pmap_pv_demote_l2: missing spare"));
3160 for (field = 0; field < _NPCM; field++) {
3161 while (pc->pc_map[field]) {
3162 bit = ffsl(pc->pc_map[field]) - 1;
3163 pc->pc_map[field] &= ~(1ul << bit);
3164 pv = &pc->pc_pventry[field * 64 + bit];
3168 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3169 ("pmap_pv_demote_l2: page %p is not managed", m));
3170 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3176 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3177 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3180 if (pc_is_full(pc)) {
3181 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3182 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3184 PV_STAT(atomic_add_long(&pv_entry_count, Ln_ENTRIES - 1));
3185 PV_STAT(atomic_subtract_int(&pv_entry_spare, Ln_ENTRIES - 1));
3189 * First find and then destroy the pv entry for the specified pmap and virtual
3190 * address. This operation can be performed on pv lists for either 4KB or 2MB
3194 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3198 pv = pmap_pvh_remove(pvh, pmap, va);
3199 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3200 free_pv_entry(pmap, pv);
3204 * Conditionally create the PV entry for a 4KB page mapping if the required
3205 * memory can be allocated without resorting to reclamation.
3208 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3209 struct rwlock **lockp)
3213 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3214 /* Pass NULL instead of the lock pointer to disable reclamation. */
3215 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3217 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3218 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3226 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3227 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3228 * false if the PV entry cannot be allocated without resorting to reclamation.
3231 pmap_pv_insert_l2(pmap_t pmap, vm_offset_t va, pd_entry_t l2e, u_int flags,
3232 struct rwlock **lockp)
3234 struct md_page *pvh;
3238 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3239 /* Pass NULL instead of the lock pointer to disable reclamation. */
3240 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3241 NULL : lockp)) == NULL)
3244 pa = l2e & ~ATTR_MASK;
3245 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3246 pvh = pa_to_pvh(pa);
3247 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3253 pmap_remove_kernel_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va)
3255 pt_entry_t newl2, oldl2 __diagused;
3259 KASSERT(!VIRT_IN_DMAP(va), ("removing direct mapping of %#lx", va));
3260 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3261 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3263 ml3 = pmap_remove_pt_page(pmap, va);
3265 panic("pmap_remove_kernel_l2: Missing pt page");
3267 ml3pa = VM_PAGE_TO_PHYS(ml3);
3268 newl2 = ml3pa | L2_TABLE;
3271 * If this page table page was unmapped by a promotion, then it
3272 * contains valid mappings. Zero it to invalidate those mappings.
3274 if (ml3->valid != 0)
3275 pagezero((void *)PHYS_TO_DMAP(ml3pa));
3278 * Demote the mapping. The caller must have already invalidated the
3279 * mapping (i.e., the "break" in break-before-make).
3281 oldl2 = pmap_load_store(l2, newl2);
3282 KASSERT(oldl2 == 0, ("%s: found existing mapping at %p: %#lx",
3283 __func__, l2, oldl2));
3287 * pmap_remove_l2: Do the things to unmap a level 2 superpage.
3290 pmap_remove_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva,
3291 pd_entry_t l1e, struct spglist *free, struct rwlock **lockp)
3293 struct md_page *pvh;
3295 vm_page_t m, ml3, mt;
3297 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3298 KASSERT((sva & L2_OFFSET) == 0, ("pmap_remove_l2: sva is not aligned"));
3299 old_l2 = pmap_load_clear(l2);
3300 KASSERT((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK,
3301 ("pmap_remove_l2: L2e %lx is not a block mapping", old_l2));
3304 * Since a promotion must break the 4KB page mappings before making
3305 * the 2MB page mapping, a pmap_s1_invalidate_page() suffices.
3307 pmap_s1_invalidate_page(pmap, sva, true);
3309 if (old_l2 & ATTR_SW_WIRED)
3310 pmap->pm_stats.wired_count -= L2_SIZE / PAGE_SIZE;
3311 pmap_resident_count_dec(pmap, L2_SIZE / PAGE_SIZE);
3312 if (old_l2 & ATTR_SW_MANAGED) {
3313 m = PHYS_TO_VM_PAGE(old_l2 & ~ATTR_MASK);
3314 pvh = page_to_pvh(m);
3315 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, old_l2 & ~ATTR_MASK);
3316 pmap_pvh_free(pvh, pmap, sva);
3317 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++) {
3318 if (pmap_pte_dirty(pmap, old_l2))
3320 if (old_l2 & ATTR_AF)
3321 vm_page_aflag_set(mt, PGA_REFERENCED);
3322 if (TAILQ_EMPTY(&mt->md.pv_list) &&
3323 TAILQ_EMPTY(&pvh->pv_list))
3324 vm_page_aflag_clear(mt, PGA_WRITEABLE);
3327 if (pmap == kernel_pmap) {
3328 pmap_remove_kernel_l2(pmap, l2, sva);
3330 ml3 = pmap_remove_pt_page(pmap, sva);
3332 KASSERT(ml3->valid == VM_PAGE_BITS_ALL,
3333 ("pmap_remove_l2: l3 page not promoted"));
3334 pmap_resident_count_dec(pmap, 1);
3335 KASSERT(ml3->ref_count == NL3PG,
3336 ("pmap_remove_l2: l3 page ref count error"));
3338 pmap_add_delayed_free_list(ml3, free, FALSE);
3341 return (pmap_unuse_pt(pmap, sva, l1e, free));
3345 * pmap_remove_l3: do the things to unmap a page in a process
3348 pmap_remove_l3(pmap_t pmap, pt_entry_t *l3, vm_offset_t va,
3349 pd_entry_t l2e, struct spglist *free, struct rwlock **lockp)
3351 struct md_page *pvh;
3355 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3356 old_l3 = pmap_load_clear(l3);
3357 pmap_s1_invalidate_page(pmap, va, true);
3358 if (old_l3 & ATTR_SW_WIRED)
3359 pmap->pm_stats.wired_count -= 1;
3360 pmap_resident_count_dec(pmap, 1);
3361 if (old_l3 & ATTR_SW_MANAGED) {
3362 m = PHYS_TO_VM_PAGE(old_l3 & ~ATTR_MASK);
3363 if (pmap_pte_dirty(pmap, old_l3))
3365 if (old_l3 & ATTR_AF)
3366 vm_page_aflag_set(m, PGA_REFERENCED);
3367 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3368 pmap_pvh_free(&m->md, pmap, va);
3369 if (TAILQ_EMPTY(&m->md.pv_list) &&
3370 (m->flags & PG_FICTITIOUS) == 0) {
3371 pvh = page_to_pvh(m);
3372 if (TAILQ_EMPTY(&pvh->pv_list))
3373 vm_page_aflag_clear(m, PGA_WRITEABLE);
3376 return (pmap_unuse_pt(pmap, va, l2e, free));
3380 * Remove the specified range of addresses from the L3 page table that is
3381 * identified by the given L2 entry.
3384 pmap_remove_l3_range(pmap_t pmap, pd_entry_t l2e, vm_offset_t sva,
3385 vm_offset_t eva, struct spglist *free, struct rwlock **lockp)
3387 struct md_page *pvh;
3388 struct rwlock *new_lock;
3389 pt_entry_t *l3, old_l3;
3393 KASSERT(ADDR_IS_CANONICAL(sva),
3394 ("%s: Start address not in canonical form: %lx", __func__, sva));
3395 KASSERT(ADDR_IS_CANONICAL(eva) || eva == VM_MAX_USER_ADDRESS,
3396 ("%s: End address not in canonical form: %lx", __func__, eva));
3398 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3399 KASSERT(rounddown2(sva, L2_SIZE) + L2_SIZE == roundup2(eva, L2_SIZE),
3400 ("pmap_remove_l3_range: range crosses an L3 page table boundary"));
3401 l3pg = !ADDR_IS_KERNEL(sva) ? PHYS_TO_VM_PAGE(l2e & ~ATTR_MASK) : NULL;
3403 for (l3 = pmap_l2_to_l3(&l2e, sva); sva != eva; l3++, sva += L3_SIZE) {
3404 if (!pmap_l3_valid(pmap_load(l3))) {
3406 pmap_invalidate_range(pmap, va, sva, true);
3411 old_l3 = pmap_load_clear(l3);
3412 if ((old_l3 & ATTR_SW_WIRED) != 0)
3413 pmap->pm_stats.wired_count--;
3414 pmap_resident_count_dec(pmap, 1);
3415 if ((old_l3 & ATTR_SW_MANAGED) != 0) {
3416 m = PHYS_TO_VM_PAGE(old_l3 & ~ATTR_MASK);
3417 if (pmap_pte_dirty(pmap, old_l3))
3419 if ((old_l3 & ATTR_AF) != 0)
3420 vm_page_aflag_set(m, PGA_REFERENCED);
3421 new_lock = PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m));
3422 if (new_lock != *lockp) {
3423 if (*lockp != NULL) {
3425 * Pending TLB invalidations must be
3426 * performed before the PV list lock is
3427 * released. Otherwise, a concurrent
3428 * pmap_remove_all() on a physical page
3429 * could return while a stale TLB entry
3430 * still provides access to that page.
3433 pmap_invalidate_range(pmap, va,
3442 pmap_pvh_free(&m->md, pmap, sva);
3443 if (TAILQ_EMPTY(&m->md.pv_list) &&
3444 (m->flags & PG_FICTITIOUS) == 0) {
3445 pvh = page_to_pvh(m);
3446 if (TAILQ_EMPTY(&pvh->pv_list))
3447 vm_page_aflag_clear(m, PGA_WRITEABLE);
3450 if (l3pg != NULL && pmap_unwire_l3(pmap, sva, l3pg, free)) {
3452 * _pmap_unwire_l3() has already invalidated the TLB
3453 * entries at all levels for "sva". So, we need not
3454 * perform "sva += L3_SIZE;" here. Moreover, we need
3455 * not perform "va = sva;" if "sva" is at the start
3456 * of a new valid range consisting of a single page.
3464 pmap_invalidate_range(pmap, va, sva, true);
3468 * Remove the given range of addresses from the specified map.
3470 * It is assumed that the start and end are properly
3471 * rounded to the page size.
3474 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3476 struct rwlock *lock;
3477 vm_offset_t va_next;
3478 pd_entry_t *l0, *l1, *l2;
3479 pt_entry_t l3_paddr;
3480 struct spglist free;
3483 * Perform an unsynchronized read. This is, however, safe.
3485 if (pmap->pm_stats.resident_count == 0)
3493 for (; sva < eva; sva = va_next) {
3494 if (pmap->pm_stats.resident_count == 0)
3497 l0 = pmap_l0(pmap, sva);
3498 if (pmap_load(l0) == 0) {
3499 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
3505 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
3508 l1 = pmap_l0_to_l1(l0, sva);
3509 if (pmap_load(l1) == 0)
3511 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
3512 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
3513 KASSERT(va_next <= eva,
3514 ("partial update of non-transparent 1G page "
3515 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
3516 pmap_load(l1), sva, eva, va_next));
3517 MPASS(pmap != kernel_pmap);
3518 MPASS((pmap_load(l1) & ATTR_SW_MANAGED) == 0);
3520 pmap_s1_invalidate_page(pmap, sva, true);
3521 pmap_resident_count_dec(pmap, L1_SIZE / PAGE_SIZE);
3522 pmap_unuse_pt(pmap, sva, pmap_load(l0), &free);
3527 * Calculate index for next page table.
3529 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
3533 l2 = pmap_l1_to_l2(l1, sva);
3537 l3_paddr = pmap_load(l2);
3539 if ((l3_paddr & ATTR_DESCR_MASK) == L2_BLOCK) {
3540 if (sva + L2_SIZE == va_next && eva >= va_next) {
3541 pmap_remove_l2(pmap, l2, sva, pmap_load(l1),
3544 } else if (pmap_demote_l2_locked(pmap, l2, sva,
3547 l3_paddr = pmap_load(l2);
3551 * Weed out invalid mappings.
3553 if ((l3_paddr & ATTR_DESCR_MASK) != L2_TABLE)
3557 * Limit our scan to either the end of the va represented
3558 * by the current page table page, or to the end of the
3559 * range being removed.
3564 pmap_remove_l3_range(pmap, l3_paddr, sva, va_next, &free,
3570 vm_page_free_pages_toq(&free, true);
3574 * Routine: pmap_remove_all
3576 * Removes this physical page from
3577 * all physical maps in which it resides.
3578 * Reflects back modify bits to the pager.
3581 * Original versions of this routine were very
3582 * inefficient because they iteratively called
3583 * pmap_remove (slow...)
3587 pmap_remove_all(vm_page_t m)
3589 struct md_page *pvh;
3592 struct rwlock *lock;
3593 pd_entry_t *pde, tpde;
3594 pt_entry_t *pte, tpte;
3596 struct spglist free;
3597 int lvl, pvh_gen, md_gen;
3599 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3600 ("pmap_remove_all: page %p is not managed", m));
3602 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3603 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
3606 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
3608 if (!PMAP_TRYLOCK(pmap)) {
3609 pvh_gen = pvh->pv_gen;
3613 if (pvh_gen != pvh->pv_gen) {
3619 pte = pmap_pte_exists(pmap, va, 2, __func__);
3620 pmap_demote_l2_locked(pmap, pte, va, &lock);
3623 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3625 if (!PMAP_TRYLOCK(pmap)) {
3626 pvh_gen = pvh->pv_gen;
3627 md_gen = m->md.pv_gen;
3631 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
3636 pmap_resident_count_dec(pmap, 1);
3638 pde = pmap_pde(pmap, pv->pv_va, &lvl);
3639 KASSERT(pde != NULL,
3640 ("pmap_remove_all: no page directory entry found"));
3642 ("pmap_remove_all: invalid pde level %d", lvl));
3643 tpde = pmap_load(pde);
3645 pte = pmap_l2_to_l3(pde, pv->pv_va);
3646 tpte = pmap_load_clear(pte);
3647 if (tpte & ATTR_SW_WIRED)
3648 pmap->pm_stats.wired_count--;
3649 if ((tpte & ATTR_AF) != 0) {
3650 pmap_invalidate_page(pmap, pv->pv_va, true);
3651 vm_page_aflag_set(m, PGA_REFERENCED);
3655 * Update the vm_page_t clean and reference bits.
3657 if (pmap_pte_dirty(pmap, tpte))
3659 pmap_unuse_pt(pmap, pv->pv_va, tpde, &free);
3660 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3662 free_pv_entry(pmap, pv);
3665 vm_page_aflag_clear(m, PGA_WRITEABLE);
3667 vm_page_free_pages_toq(&free, true);
3671 * Masks and sets bits in a level 2 page table entries in the specified pmap
3674 pmap_protect_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva, pt_entry_t mask,
3680 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3681 PMAP_ASSERT_STAGE1(pmap);
3682 KASSERT((sva & L2_OFFSET) == 0,
3683 ("pmap_protect_l2: sva is not 2mpage aligned"));
3684 old_l2 = pmap_load(l2);
3685 KASSERT((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK,
3686 ("pmap_protect_l2: L2e %lx is not a block mapping", old_l2));
3689 * Return if the L2 entry already has the desired access restrictions
3692 if ((old_l2 & mask) == nbits)
3695 while (!atomic_fcmpset_64(l2, &old_l2, (old_l2 & ~mask) | nbits))
3699 * When a dirty read/write superpage mapping is write protected,
3700 * update the dirty field of each of the superpage's constituent 4KB
3703 if ((old_l2 & ATTR_SW_MANAGED) != 0 &&
3704 (nbits & ATTR_S1_AP(ATTR_S1_AP_RO)) != 0 &&
3705 pmap_pte_dirty(pmap, old_l2)) {
3706 m = PHYS_TO_VM_PAGE(old_l2 & ~ATTR_MASK);
3707 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
3712 * Since a promotion must break the 4KB page mappings before making
3713 * the 2MB page mapping, a pmap_s1_invalidate_page() suffices.
3715 pmap_s1_invalidate_page(pmap, sva, true);
3719 * Masks and sets bits in last level page table entries in the specified
3723 pmap_mask_set(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, pt_entry_t mask,
3724 pt_entry_t nbits, bool invalidate)
3726 vm_offset_t va, va_next;
3727 pd_entry_t *l0, *l1, *l2;
3728 pt_entry_t *l3p, l3;
3731 for (; sva < eva; sva = va_next) {
3732 l0 = pmap_l0(pmap, sva);
3733 if (pmap_load(l0) == 0) {
3734 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
3740 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
3743 l1 = pmap_l0_to_l1(l0, sva);
3744 if (pmap_load(l1) == 0)
3746 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
3747 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
3748 KASSERT(va_next <= eva,
3749 ("partial update of non-transparent 1G page "
3750 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
3751 pmap_load(l1), sva, eva, va_next));
3752 MPASS((pmap_load(l1) & ATTR_SW_MANAGED) == 0);
3753 if ((pmap_load(l1) & mask) != nbits) {
3754 pmap_store(l1, (pmap_load(l1) & ~mask) | nbits);
3756 pmap_s1_invalidate_page(pmap, sva, true);
3761 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
3765 l2 = pmap_l1_to_l2(l1, sva);
3766 if (pmap_load(l2) == 0)
3769 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK) {
3770 if (sva + L2_SIZE == va_next && eva >= va_next) {
3771 pmap_protect_l2(pmap, l2, sva, mask, nbits);
3773 } else if (pmap_demote_l2(pmap, l2, sva) == NULL)
3776 KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
3777 ("pmap_protect: Invalid L2 entry after demotion"));
3783 for (l3p = pmap_l2_to_l3(l2, sva); sva != va_next; l3p++,
3785 l3 = pmap_load(l3p);
3788 * Go to the next L3 entry if the current one is
3789 * invalid or already has the desired access
3790 * restrictions in place. (The latter case occurs
3791 * frequently. For example, in a "buildworld"
3792 * workload, almost 1 out of 4 L3 entries already
3793 * have the desired restrictions.)
3795 if (!pmap_l3_valid(l3) || (l3 & mask) == nbits) {
3796 if (va != va_next) {
3798 pmap_s1_invalidate_range(pmap,
3805 while (!atomic_fcmpset_64(l3p, &l3, (l3 & ~mask) |
3810 * When a dirty read/write mapping is write protected,
3811 * update the page's dirty field.
3813 if ((l3 & ATTR_SW_MANAGED) != 0 &&
3814 (nbits & ATTR_S1_AP(ATTR_S1_AP_RO)) != 0 &&
3815 pmap_pte_dirty(pmap, l3))
3816 vm_page_dirty(PHYS_TO_VM_PAGE(l3 & ~ATTR_MASK));
3821 if (va != va_next && invalidate)
3822 pmap_s1_invalidate_range(pmap, va, sva, true);
3828 * Set the physical protection on the
3829 * specified range of this map as requested.
3832 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
3834 pt_entry_t mask, nbits;
3836 PMAP_ASSERT_STAGE1(pmap);
3837 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
3838 if (prot == VM_PROT_NONE) {
3839 pmap_remove(pmap, sva, eva);
3844 if ((prot & VM_PROT_WRITE) == 0) {
3845 mask |= ATTR_S1_AP_RW_BIT | ATTR_SW_DBM;
3846 nbits |= ATTR_S1_AP(ATTR_S1_AP_RO);
3848 if ((prot & VM_PROT_EXECUTE) == 0) {
3850 nbits |= ATTR_S1_XN;
3855 pmap_mask_set(pmap, sva, eva, mask, nbits, true);
3859 pmap_disable_promotion(vm_offset_t sva, vm_size_t size)
3862 MPASS((sva & L3_OFFSET) == 0);
3863 MPASS(((sva + size) & L3_OFFSET) == 0);
3865 pmap_mask_set(kernel_pmap, sva, sva + size, ATTR_SW_NO_PROMOTE,
3866 ATTR_SW_NO_PROMOTE, false);
3870 * Inserts the specified page table page into the specified pmap's collection
3871 * of idle page table pages. Each of a pmap's page table pages is responsible
3872 * for mapping a distinct range of virtual addresses. The pmap's collection is
3873 * ordered by this virtual address range.
3875 * If "promoted" is false, then the page table page "mpte" must be zero filled.
3878 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted)
3881 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3882 mpte->valid = promoted ? VM_PAGE_BITS_ALL : 0;
3883 return (vm_radix_insert(&pmap->pm_root, mpte));
3887 * Removes the page table page mapping the specified virtual address from the
3888 * specified pmap's collection of idle page table pages, and returns it.
3889 * Otherwise, returns NULL if there is no page table page corresponding to the
3890 * specified virtual address.
3892 static __inline vm_page_t
3893 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
3896 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3897 return (vm_radix_remove(&pmap->pm_root, pmap_l2_pindex(va)));
3901 * Performs a break-before-make update of a pmap entry. This is needed when
3902 * either promoting or demoting pages to ensure the TLB doesn't get into an
3903 * inconsistent state.
3906 pmap_update_entry(pmap_t pmap, pd_entry_t *pte, pd_entry_t newpte,
3907 vm_offset_t va, vm_size_t size)
3911 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3913 if ((newpte & ATTR_SW_NO_PROMOTE) != 0)
3914 panic("%s: Updating non-promote pte", __func__);
3917 * Ensure we don't get switched out with the page table in an
3918 * inconsistent state. We also need to ensure no interrupts fire
3919 * as they may make use of an address we are about to invalidate.
3921 intr = intr_disable();
3924 * Clear the old mapping's valid bit, but leave the rest of the entry
3925 * unchanged, so that a lockless, concurrent pmap_kextract() can still
3926 * lookup the physical address.
3928 pmap_clear_bits(pte, ATTR_DESCR_VALID);
3931 * When promoting, the L{1,2}_TABLE entry that is being replaced might
3932 * be cached, so we invalidate intermediate entries as well as final
3935 pmap_s1_invalidate_range(pmap, va, va + size, false);
3937 /* Create the new mapping */
3938 pmap_store(pte, newpte);
3944 #if VM_NRESERVLEVEL > 0
3946 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3947 * replace the many pv entries for the 4KB page mappings by a single pv entry
3948 * for the 2MB page mapping.
3951 pmap_pv_promote_l2(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3952 struct rwlock **lockp)
3954 struct md_page *pvh;
3956 vm_offset_t va_last;
3959 KASSERT((pa & L2_OFFSET) == 0,
3960 ("pmap_pv_promote_l2: pa is not 2mpage aligned"));
3961 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3964 * Transfer the first page's pv entry for this mapping to the 2mpage's
3965 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3966 * a transfer avoids the possibility that get_pv_entry() calls
3967 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3968 * mappings that is being promoted.
3970 m = PHYS_TO_VM_PAGE(pa);
3971 va = va & ~L2_OFFSET;
3972 pv = pmap_pvh_remove(&m->md, pmap, va);
3973 KASSERT(pv != NULL, ("pmap_pv_promote_l2: pv not found"));
3974 pvh = page_to_pvh(m);
3975 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3977 /* Free the remaining NPTEPG - 1 pv entries. */
3978 va_last = va + L2_SIZE - PAGE_SIZE;
3982 pmap_pvh_free(&m->md, pmap, va);
3983 } while (va < va_last);
3987 * Tries to promote the 512, contiguous 4KB page mappings that are within a
3988 * single level 2 table entry to a single 2MB page mapping. For promotion
3989 * to occur, two conditions must be met: (1) the 4KB page mappings must map
3990 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
3991 * identical characteristics.
3994 pmap_promote_l2(pmap_t pmap, pd_entry_t *l2, vm_offset_t va, vm_page_t mpte,
3995 struct rwlock **lockp)
3997 pt_entry_t *firstl3, *l3, newl2, oldl3, pa;
3999 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4000 PMAP_ASSERT_STAGE1(pmap);
4003 * Examine the first L3E in the specified PTP. Abort if this L3E is
4004 * ineligible for promotion, invalid, or does not map the first 4KB
4005 * physical page within a 2MB page.
4007 firstl3 = (pt_entry_t *)PHYS_TO_DMAP(pmap_load(l2) & ~ATTR_MASK);
4008 newl2 = pmap_load(firstl3);
4009 if ((newl2 & ATTR_SW_NO_PROMOTE) != 0)
4011 if ((newl2 & ((~ATTR_MASK & L2_OFFSET) | ATTR_DESCR_MASK)) != L3_PAGE) {
4012 atomic_add_long(&pmap_l2_p_failures, 1);
4013 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
4014 " in pmap %p", va, pmap);
4019 * Both here and in the below "for" loop, to allow for repromotion
4020 * after MADV_FREE, conditionally write protect a clean L3E before
4021 * possibly aborting the promotion due to other L3E attributes. Why?
4022 * Suppose that MADV_FREE is applied to a part of a superpage, the
4023 * address range [S, E). pmap_advise() will demote the superpage
4024 * mapping, destroy the 4KB page mapping at the end of [S, E), and
4025 * set AP_RO and clear AF in the L3Es for the rest of [S, E). Later,
4026 * imagine that the memory in [S, E) is recycled, but the last 4KB
4027 * page in [S, E) is not the last to be rewritten, or simply accessed.
4028 * In other words, there is still a 4KB page in [S, E), call it P,
4029 * that is writeable but AP_RO is set and AF is clear in P's L3E.
4030 * Unless we write protect P before aborting the promotion, if and
4031 * when P is finally rewritten, there won't be a page fault to trigger
4035 if ((newl2 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
4036 (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM)) {
4038 * When the mapping is clean, i.e., ATTR_S1_AP_RO is set,
4039 * ATTR_SW_DBM can be cleared without a TLB invalidation.
4041 if (!atomic_fcmpset_64(firstl3, &newl2, newl2 & ~ATTR_SW_DBM))
4043 newl2 &= ~ATTR_SW_DBM;
4045 if ((newl2 & ATTR_AF) == 0) {
4046 atomic_add_long(&pmap_l2_p_failures, 1);
4047 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
4048 " in pmap %p", va, pmap);
4053 * Examine each of the other L3Es in the specified PTP. Abort if this
4054 * L3E maps an unexpected 4KB physical page or does not have identical
4055 * characteristics to the first L3E.
4057 pa = (newl2 & (~ATTR_MASK | ATTR_DESCR_MASK)) + L2_SIZE - PAGE_SIZE;
4058 for (l3 = firstl3 + NL3PG - 1; l3 > firstl3; l3--) {
4059 oldl3 = pmap_load(l3);
4060 if ((oldl3 & (~ATTR_MASK | ATTR_DESCR_MASK)) != pa) {
4061 atomic_add_long(&pmap_l2_p_failures, 1);
4062 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
4063 " in pmap %p", va, pmap);
4067 if ((oldl3 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
4068 (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM)) {
4070 * When the mapping is clean, i.e., ATTR_S1_AP_RO is
4071 * set, ATTR_SW_DBM can be cleared without a TLB
4074 if (!atomic_fcmpset_64(l3, &oldl3, oldl3 &
4077 oldl3 &= ~ATTR_SW_DBM;
4079 if ((oldl3 & ATTR_MASK) != (newl2 & ATTR_MASK)) {
4080 atomic_add_long(&pmap_l2_p_failures, 1);
4081 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
4082 " in pmap %p", va, pmap);
4089 * Save the page table page in its current state until the L2
4090 * mapping the superpage is demoted by pmap_demote_l2() or
4091 * destroyed by pmap_remove_l3().
4094 mpte = PHYS_TO_VM_PAGE(pmap_load(l2) & ~ATTR_MASK);
4095 KASSERT(mpte >= vm_page_array &&
4096 mpte < &vm_page_array[vm_page_array_size],
4097 ("pmap_promote_l2: page table page is out of range"));
4098 KASSERT(mpte->pindex == pmap_l2_pindex(va),
4099 ("pmap_promote_l2: page table page's pindex is wrong"));
4100 if (pmap_insert_pt_page(pmap, mpte, true)) {
4101 atomic_add_long(&pmap_l2_p_failures, 1);
4103 "pmap_promote_l2: failure for va %#lx in pmap %p", va,
4108 if ((newl2 & ATTR_SW_MANAGED) != 0)
4109 pmap_pv_promote_l2(pmap, va, newl2 & ~ATTR_MASK, lockp);
4111 newl2 &= ~ATTR_DESCR_MASK;
4114 pmap_update_entry(pmap, l2, newl2, va & ~L2_OFFSET, L2_SIZE);
4116 atomic_add_long(&pmap_l2_promotions, 1);
4117 CTR2(KTR_PMAP, "pmap_promote_l2: success for va %#lx in pmap %p", va,
4120 #endif /* VM_NRESERVLEVEL > 0 */
4123 pmap_enter_largepage(pmap_t pmap, vm_offset_t va, pt_entry_t newpte, int flags,
4126 pd_entry_t *l0p, *l1p, *l2p, origpte;
4129 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4130 KASSERT(psind > 0 && psind < MAXPAGESIZES,
4131 ("psind %d unexpected", psind));
4132 KASSERT(((newpte & ~ATTR_MASK) & (pagesizes[psind] - 1)) == 0,
4133 ("unaligned phys address %#lx newpte %#lx psind %d",
4134 (newpte & ~ATTR_MASK), newpte, psind));
4138 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
4140 l0p = pmap_l0(pmap, va);
4141 if ((pmap_load(l0p) & ATTR_DESCR_VALID) == 0) {
4142 mp = _pmap_alloc_l3(pmap, pmap_l0_pindex(va), NULL);
4144 if ((flags & PMAP_ENTER_NOSLEEP) != 0)
4145 return (KERN_RESOURCE_SHORTAGE);
4151 l1p = pmap_l0_to_l1(l0p, va);
4152 KASSERT(l1p != NULL, ("va %#lx lost l1 entry", va));
4153 origpte = pmap_load(l1p);
4155 l1p = pmap_l0_to_l1(l0p, va);
4156 KASSERT(l1p != NULL, ("va %#lx lost l1 entry", va));
4157 origpte = pmap_load(l1p);
4158 if ((origpte & ATTR_DESCR_VALID) == 0) {
4159 mp = PHYS_TO_VM_PAGE(pmap_load(l0p) &
4164 KASSERT(((origpte & ~ATTR_MASK) == (newpte & ~ATTR_MASK) &&
4165 (origpte & ATTR_DESCR_MASK) == L1_BLOCK) ||
4166 (origpte & ATTR_DESCR_VALID) == 0,
4167 ("va %#lx changing 1G phys page l1 %#lx newpte %#lx",
4168 va, origpte, newpte));
4169 pmap_store(l1p, newpte);
4170 } else /* (psind == 1) */ {
4171 l2p = pmap_l2(pmap, va);
4173 mp = _pmap_alloc_l3(pmap, pmap_l1_pindex(va), NULL);
4175 if ((flags & PMAP_ENTER_NOSLEEP) != 0)
4176 return (KERN_RESOURCE_SHORTAGE);
4182 l2p = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
4183 l2p = &l2p[pmap_l2_index(va)];
4184 origpte = pmap_load(l2p);
4186 l1p = pmap_l1(pmap, va);
4187 origpte = pmap_load(l2p);
4188 if ((origpte & ATTR_DESCR_VALID) == 0) {
4189 mp = PHYS_TO_VM_PAGE(pmap_load(l1p) &
4194 KASSERT((origpte & ATTR_DESCR_VALID) == 0 ||
4195 ((origpte & ATTR_DESCR_MASK) == L2_BLOCK &&
4196 (origpte & ~ATTR_MASK) == (newpte & ~ATTR_MASK)),
4197 ("va %#lx changing 2M phys page l2 %#lx newpte %#lx",
4198 va, origpte, newpte));
4199 pmap_store(l2p, newpte);
4203 if ((origpte & ATTR_DESCR_VALID) == 0)
4204 pmap_resident_count_inc(pmap, pagesizes[psind] / PAGE_SIZE);
4205 if ((newpte & ATTR_SW_WIRED) != 0 && (origpte & ATTR_SW_WIRED) == 0)
4206 pmap->pm_stats.wired_count += pagesizes[psind] / PAGE_SIZE;
4207 else if ((newpte & ATTR_SW_WIRED) == 0 &&
4208 (origpte & ATTR_SW_WIRED) != 0)
4209 pmap->pm_stats.wired_count -= pagesizes[psind] / PAGE_SIZE;
4211 return (KERN_SUCCESS);
4215 * Insert the given physical page (p) at
4216 * the specified virtual address (v) in the
4217 * target physical map with the protection requested.
4219 * If specified, the page will be wired down, meaning
4220 * that the related pte can not be reclaimed.
4222 * NB: This is the only routine which MAY NOT lazy-evaluate
4223 * or lose information. That is, this routine must actually
4224 * insert this page into the given map NOW.
4227 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4228 u_int flags, int8_t psind)
4230 struct rwlock *lock;
4232 pt_entry_t new_l3, orig_l3;
4233 pt_entry_t *l2, *l3;
4240 KASSERT(ADDR_IS_CANONICAL(va),
4241 ("%s: Address not in canonical form: %lx", __func__, va));
4243 va = trunc_page(va);
4244 if ((m->oflags & VPO_UNMANAGED) == 0)
4245 VM_PAGE_OBJECT_BUSY_ASSERT(m);
4246 pa = VM_PAGE_TO_PHYS(m);
4247 new_l3 = (pt_entry_t)(pa | ATTR_DEFAULT | L3_PAGE);
4248 new_l3 |= pmap_pte_memattr(pmap, m->md.pv_memattr);
4249 new_l3 |= pmap_pte_prot(pmap, prot);
4251 if ((flags & PMAP_ENTER_WIRED) != 0)
4252 new_l3 |= ATTR_SW_WIRED;
4253 if (pmap->pm_stage == PM_STAGE1) {
4254 if (!ADDR_IS_KERNEL(va))
4255 new_l3 |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
4257 new_l3 |= ATTR_S1_UXN;
4258 if (pmap != kernel_pmap)
4259 new_l3 |= ATTR_S1_nG;
4262 * Clear the access flag on executable mappings, this will be
4263 * set later when the page is accessed. The fault handler is
4264 * required to invalidate the I-cache.
4266 * TODO: Switch to the valid flag to allow hardware management
4267 * of the access flag. Much of the pmap code assumes the
4268 * valid flag is set and fails to destroy the old page tables
4269 * correctly if it is clear.
4271 if (prot & VM_PROT_EXECUTE)
4274 if ((m->oflags & VPO_UNMANAGED) == 0) {
4275 new_l3 |= ATTR_SW_MANAGED;
4276 if ((prot & VM_PROT_WRITE) != 0) {
4277 new_l3 |= ATTR_SW_DBM;
4278 if ((flags & VM_PROT_WRITE) == 0) {
4279 if (pmap->pm_stage == PM_STAGE1)
4280 new_l3 |= ATTR_S1_AP(ATTR_S1_AP_RO);
4283 ~ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
4288 CTR2(KTR_PMAP, "pmap_enter: %.16lx -> %.16lx", va, pa);
4292 if ((flags & PMAP_ENTER_LARGEPAGE) != 0) {
4293 KASSERT((m->oflags & VPO_UNMANAGED) != 0,
4294 ("managed largepage va %#lx flags %#x", va, flags));
4297 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
4299 } else /* (psind == 1) */
4301 rv = pmap_enter_largepage(pmap, va, new_l3, flags, psind);
4305 /* Assert the required virtual and physical alignment. */
4306 KASSERT((va & L2_OFFSET) == 0, ("pmap_enter: va unaligned"));
4307 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4308 rv = pmap_enter_l2(pmap, va, (new_l3 & ~L3_PAGE) | L2_BLOCK,
4315 * In the case that a page table page is not
4316 * resident, we are creating it here.
4319 pde = pmap_pde(pmap, va, &lvl);
4320 if (pde != NULL && lvl == 2) {
4321 l3 = pmap_l2_to_l3(pde, va);
4322 if (!ADDR_IS_KERNEL(va) && mpte == NULL) {
4323 mpte = PHYS_TO_VM_PAGE(pmap_load(pde) & ~ATTR_MASK);
4327 } else if (pde != NULL && lvl == 1) {
4328 l2 = pmap_l1_to_l2(pde, va);
4329 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK &&
4330 (l3 = pmap_demote_l2_locked(pmap, l2, va, &lock)) != NULL) {
4331 l3 = &l3[pmap_l3_index(va)];
4332 if (!ADDR_IS_KERNEL(va)) {
4333 mpte = PHYS_TO_VM_PAGE(
4334 pmap_load(l2) & ~ATTR_MASK);
4339 /* We need to allocate an L3 table. */
4341 if (!ADDR_IS_KERNEL(va)) {
4342 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4345 * We use _pmap_alloc_l3() instead of pmap_alloc_l3() in order
4346 * to handle the possibility that a superpage mapping for "va"
4347 * was created while we slept.
4349 mpte = _pmap_alloc_l3(pmap, pmap_l2_pindex(va),
4350 nosleep ? NULL : &lock);
4351 if (mpte == NULL && nosleep) {
4352 CTR0(KTR_PMAP, "pmap_enter: mpte == NULL");
4353 rv = KERN_RESOURCE_SHORTAGE;
4358 panic("pmap_enter: missing L3 table for kernel va %#lx", va);
4361 orig_l3 = pmap_load(l3);
4362 opa = orig_l3 & ~ATTR_MASK;
4366 * Is the specified virtual address already mapped?
4368 if (pmap_l3_valid(orig_l3)) {
4370 * Wiring change, just update stats. We don't worry about
4371 * wiring PT pages as they remain resident as long as there
4372 * are valid mappings in them. Hence, if a user page is wired,
4373 * the PT page will be also.
4375 if ((flags & PMAP_ENTER_WIRED) != 0 &&
4376 (orig_l3 & ATTR_SW_WIRED) == 0)
4377 pmap->pm_stats.wired_count++;
4378 else if ((flags & PMAP_ENTER_WIRED) == 0 &&
4379 (orig_l3 & ATTR_SW_WIRED) != 0)
4380 pmap->pm_stats.wired_count--;
4383 * Remove the extra PT page reference.
4387 KASSERT(mpte->ref_count > 0,
4388 ("pmap_enter: missing reference to page table page,"
4393 * Has the physical page changed?
4397 * No, might be a protection or wiring change.
4399 if ((orig_l3 & ATTR_SW_MANAGED) != 0 &&
4400 (new_l3 & ATTR_SW_DBM) != 0)
4401 vm_page_aflag_set(m, PGA_WRITEABLE);
4406 * The physical page has changed. Temporarily invalidate
4409 orig_l3 = pmap_load_clear(l3);
4410 KASSERT((orig_l3 & ~ATTR_MASK) == opa,
4411 ("pmap_enter: unexpected pa update for %#lx", va));
4412 if ((orig_l3 & ATTR_SW_MANAGED) != 0) {
4413 om = PHYS_TO_VM_PAGE(opa);
4416 * The pmap lock is sufficient to synchronize with
4417 * concurrent calls to pmap_page_test_mappings() and
4418 * pmap_ts_referenced().
4420 if (pmap_pte_dirty(pmap, orig_l3))
4422 if ((orig_l3 & ATTR_AF) != 0) {
4423 pmap_invalidate_page(pmap, va, true);
4424 vm_page_aflag_set(om, PGA_REFERENCED);
4426 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4427 pv = pmap_pvh_remove(&om->md, pmap, va);
4428 if ((m->oflags & VPO_UNMANAGED) != 0)
4429 free_pv_entry(pmap, pv);
4430 if ((om->a.flags & PGA_WRITEABLE) != 0 &&
4431 TAILQ_EMPTY(&om->md.pv_list) &&
4432 ((om->flags & PG_FICTITIOUS) != 0 ||
4433 TAILQ_EMPTY(&page_to_pvh(om)->pv_list)))
4434 vm_page_aflag_clear(om, PGA_WRITEABLE);
4436 KASSERT((orig_l3 & ATTR_AF) != 0,
4437 ("pmap_enter: unmanaged mapping lacks ATTR_AF"));
4438 pmap_invalidate_page(pmap, va, true);
4443 * Increment the counters.
4445 if ((new_l3 & ATTR_SW_WIRED) != 0)
4446 pmap->pm_stats.wired_count++;
4447 pmap_resident_count_inc(pmap, 1);
4450 * Enter on the PV list if part of our managed memory.
4452 if ((m->oflags & VPO_UNMANAGED) == 0) {
4454 pv = get_pv_entry(pmap, &lock);
4457 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4458 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4460 if ((new_l3 & ATTR_SW_DBM) != 0)
4461 vm_page_aflag_set(m, PGA_WRITEABLE);
4465 if (pmap->pm_stage == PM_STAGE1) {
4467 * Sync icache if exec permission and attribute
4468 * VM_MEMATTR_WRITE_BACK is set. Do it now, before the mapping
4469 * is stored and made valid for hardware table walk. If done
4470 * later, then other can access this page before caches are
4471 * properly synced. Don't do it for kernel memory which is
4472 * mapped with exec permission even if the memory isn't going
4473 * to hold executable code. The only time when icache sync is
4474 * needed is after kernel module is loaded and the relocation
4475 * info is processed. And it's done in elf_cpu_load_file().
4477 if ((prot & VM_PROT_EXECUTE) && pmap != kernel_pmap &&
4478 m->md.pv_memattr == VM_MEMATTR_WRITE_BACK &&
4479 (opa != pa || (orig_l3 & ATTR_S1_XN))) {
4480 PMAP_ASSERT_STAGE1(pmap);
4481 cpu_icache_sync_range(PHYS_TO_DMAP(pa), PAGE_SIZE);
4484 cpu_dcache_wb_range(PHYS_TO_DMAP(pa), PAGE_SIZE);
4488 * Update the L3 entry
4490 if (pmap_l3_valid(orig_l3)) {
4491 KASSERT(opa == pa, ("pmap_enter: invalid update"));
4492 if ((orig_l3 & ~ATTR_AF) != (new_l3 & ~ATTR_AF)) {
4493 /* same PA, different attributes */
4494 orig_l3 = pmap_load_store(l3, new_l3);
4495 pmap_invalidate_page(pmap, va, true);
4496 if ((orig_l3 & ATTR_SW_MANAGED) != 0 &&
4497 pmap_pte_dirty(pmap, orig_l3))
4502 * This can happens if multiple threads simultaneously
4503 * access not yet mapped page. This bad for performance
4504 * since this can cause full demotion-NOP-promotion
4506 * Another possible reasons are:
4507 * - VM and pmap memory layout are diverged
4508 * - tlb flush is missing somewhere and CPU doesn't see
4511 CTR4(KTR_PMAP, "%s: already mapped page - "
4512 "pmap %p va 0x%#lx pte 0x%lx",
4513 __func__, pmap, va, new_l3);
4517 pmap_store(l3, new_l3);
4521 #if VM_NRESERVLEVEL > 0
4523 * Try to promote from level 3 pages to a level 2 superpage. This
4524 * currently only works on stage 1 pmaps as pmap_promote_l2 looks at
4525 * stage 1 specific fields and performs a break-before-make sequence
4526 * that is incorrect a stage 2 pmap.
4528 if ((mpte == NULL || mpte->ref_count == NL3PG) &&
4529 pmap_ps_enabled(pmap) && pmap->pm_stage == PM_STAGE1 &&
4530 (m->flags & PG_FICTITIOUS) == 0 &&
4531 vm_reserv_level_iffullpop(m) == 0) {
4532 pmap_promote_l2(pmap, pde, va, mpte, &lock);
4545 * Tries to create a read- and/or execute-only 2MB page mapping. Returns
4546 * KERN_SUCCESS if the mapping was created. Otherwise, returns an error
4547 * value. See pmap_enter_l2() for the possible error values when "no sleep",
4548 * "no replace", and "no reclaim" are specified.
4551 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4552 struct rwlock **lockp)
4556 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4557 PMAP_ASSERT_STAGE1(pmap);
4558 KASSERT(ADDR_IS_CANONICAL(va),
4559 ("%s: Address not in canonical form: %lx", __func__, va));
4561 new_l2 = (pd_entry_t)(VM_PAGE_TO_PHYS(m) | ATTR_DEFAULT |
4562 ATTR_S1_IDX(m->md.pv_memattr) | ATTR_S1_AP(ATTR_S1_AP_RO) |
4564 if ((m->oflags & VPO_UNMANAGED) == 0) {
4565 new_l2 |= ATTR_SW_MANAGED;
4568 if ((prot & VM_PROT_EXECUTE) == 0 ||
4569 m->md.pv_memattr == VM_MEMATTR_DEVICE)
4570 new_l2 |= ATTR_S1_XN;
4571 if (!ADDR_IS_KERNEL(va))
4572 new_l2 |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
4574 new_l2 |= ATTR_S1_UXN;
4575 if (pmap != kernel_pmap)
4576 new_l2 |= ATTR_S1_nG;
4577 return (pmap_enter_l2(pmap, va, new_l2, PMAP_ENTER_NOSLEEP |
4578 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, m, lockp));
4582 * Returns true if every page table entry in the specified page table is
4586 pmap_every_pte_zero(vm_paddr_t pa)
4588 pt_entry_t *pt_end, *pte;
4590 KASSERT((pa & PAGE_MASK) == 0, ("pa is misaligned"));
4591 pte = (pt_entry_t *)PHYS_TO_DMAP(pa);
4592 for (pt_end = pte + Ln_ENTRIES; pte < pt_end; pte++) {
4600 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
4601 * the mapping was created, and one of KERN_FAILURE, KERN_NO_SPACE, or
4602 * KERN_RESOURCE_SHORTAGE otherwise. Returns KERN_FAILURE if
4603 * PMAP_ENTER_NOREPLACE was specified and a 4KB page mapping already exists
4604 * within the 2MB virtual address range starting at the specified virtual
4605 * address. Returns KERN_NO_SPACE if PMAP_ENTER_NOREPLACE was specified and a
4606 * 2MB page mapping already exists at the specified virtual address. Returns
4607 * KERN_RESOURCE_SHORTAGE if either (1) PMAP_ENTER_NOSLEEP was specified and a
4608 * page table page allocation failed or (2) PMAP_ENTER_NORECLAIM was specified
4609 * and a PV entry allocation failed.
4612 pmap_enter_l2(pmap_t pmap, vm_offset_t va, pd_entry_t new_l2, u_int flags,
4613 vm_page_t m, struct rwlock **lockp)
4615 struct spglist free;
4616 pd_entry_t *l2, old_l2;
4619 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4620 KASSERT(ADDR_IS_CANONICAL(va),
4621 ("%s: Address not in canonical form: %lx", __func__, va));
4623 if ((l2 = pmap_alloc_l2(pmap, va, &l2pg, (flags &
4624 PMAP_ENTER_NOSLEEP) != 0 ? NULL : lockp)) == NULL) {
4625 CTR2(KTR_PMAP, "pmap_enter_l2: failure for va %#lx in pmap %p",
4627 return (KERN_RESOURCE_SHORTAGE);
4631 * If there are existing mappings, either abort or remove them.
4633 if ((old_l2 = pmap_load(l2)) != 0) {
4634 KASSERT(l2pg == NULL || l2pg->ref_count > 1,
4635 ("pmap_enter_l2: l2pg's ref count is too low"));
4636 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
4637 if ((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK) {
4641 "pmap_enter_l2: no space for va %#lx"
4642 " in pmap %p", va, pmap);
4643 return (KERN_NO_SPACE);
4644 } else if (!ADDR_IS_KERNEL(va) ||
4645 !pmap_every_pte_zero(old_l2 & ~ATTR_MASK)) {
4649 "pmap_enter_l2: failure for va %#lx"
4650 " in pmap %p", va, pmap);
4651 return (KERN_FAILURE);
4655 if ((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK)
4656 (void)pmap_remove_l2(pmap, l2, va,
4657 pmap_load(pmap_l1(pmap, va)), &free, lockp);
4659 pmap_remove_l3_range(pmap, old_l2, va, va + L2_SIZE,
4661 if (!ADDR_IS_KERNEL(va)) {
4662 vm_page_free_pages_toq(&free, true);
4663 KASSERT(pmap_load(l2) == 0,
4664 ("pmap_enter_l2: non-zero L2 entry %p", l2));
4666 KASSERT(SLIST_EMPTY(&free),
4667 ("pmap_enter_l2: freed kernel page table page"));
4670 * Both pmap_remove_l2() and pmap_remove_l3_range()
4671 * will leave the kernel page table page zero filled.
4672 * Nonetheless, the TLB could have an intermediate
4673 * entry for the kernel page table page, so request
4674 * an invalidation at all levels after clearing
4675 * the L2_TABLE entry.
4677 mt = PHYS_TO_VM_PAGE(pmap_load(l2) & ~ATTR_MASK);
4678 if (pmap_insert_pt_page(pmap, mt, false))
4679 panic("pmap_enter_l2: trie insert failed");
4681 pmap_s1_invalidate_page(pmap, va, false);
4685 if ((new_l2 & ATTR_SW_MANAGED) != 0) {
4687 * Abort this mapping if its PV entry could not be created.
4689 if (!pmap_pv_insert_l2(pmap, va, new_l2, flags, lockp)) {
4691 pmap_abort_ptp(pmap, va, l2pg);
4693 "pmap_enter_l2: failure for va %#lx in pmap %p",
4695 return (KERN_RESOURCE_SHORTAGE);
4697 if ((new_l2 & ATTR_SW_DBM) != 0)
4698 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
4699 vm_page_aflag_set(mt, PGA_WRITEABLE);
4703 * Increment counters.
4705 if ((new_l2 & ATTR_SW_WIRED) != 0)
4706 pmap->pm_stats.wired_count += L2_SIZE / PAGE_SIZE;
4707 pmap->pm_stats.resident_count += L2_SIZE / PAGE_SIZE;
4710 * Conditionally sync the icache. See pmap_enter() for details.
4712 if ((new_l2 & ATTR_S1_XN) == 0 && ((new_l2 & ~ATTR_MASK) !=
4713 (old_l2 & ~ATTR_MASK) || (old_l2 & ATTR_S1_XN) != 0) &&
4714 pmap != kernel_pmap && m->md.pv_memattr == VM_MEMATTR_WRITE_BACK) {
4715 cpu_icache_sync_range(PHYS_TO_DMAP(new_l2 & ~ATTR_MASK),
4720 * Map the superpage.
4722 pmap_store(l2, new_l2);
4725 atomic_add_long(&pmap_l2_mappings, 1);
4726 CTR2(KTR_PMAP, "pmap_enter_l2: success for va %#lx in pmap %p",
4729 return (KERN_SUCCESS);
4733 * Maps a sequence of resident pages belonging to the same object.
4734 * The sequence begins with the given page m_start. This page is
4735 * mapped at the given virtual address start. Each subsequent page is
4736 * mapped at a virtual address that is offset from start by the same
4737 * amount as the page is offset from m_start within the object. The
4738 * last page in the sequence is the page with the largest offset from
4739 * m_start that can be mapped at a virtual address less than the given
4740 * virtual address end. Not every virtual page between start and end
4741 * is mapped; only those for which a resident page exists with the
4742 * corresponding offset from m_start are mapped.
4745 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
4746 vm_page_t m_start, vm_prot_t prot)
4748 struct rwlock *lock;
4751 vm_pindex_t diff, psize;
4754 VM_OBJECT_ASSERT_LOCKED(m_start->object);
4756 psize = atop(end - start);
4761 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
4762 va = start + ptoa(diff);
4763 if ((va & L2_OFFSET) == 0 && va + L2_SIZE <= end &&
4764 m->psind == 1 && pmap_ps_enabled(pmap) &&
4765 ((rv = pmap_enter_2mpage(pmap, va, m, prot, &lock)) ==
4766 KERN_SUCCESS || rv == KERN_NO_SPACE))
4767 m = &m[L2_SIZE / PAGE_SIZE - 1];
4769 mpte = pmap_enter_quick_locked(pmap, va, m, prot, mpte,
4771 m = TAILQ_NEXT(m, listq);
4779 * this code makes some *MAJOR* assumptions:
4780 * 1. Current pmap & pmap exists.
4783 * 4. No page table pages.
4784 * but is *MUCH* faster than pmap_enter...
4788 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
4790 struct rwlock *lock;
4794 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
4801 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
4802 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
4805 pt_entry_t *l1, *l2, *l3, l3_val;
4809 KASSERT(!VA_IS_CLEANMAP(va) ||
4810 (m->oflags & VPO_UNMANAGED) != 0,
4811 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
4812 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4813 PMAP_ASSERT_STAGE1(pmap);
4814 KASSERT(ADDR_IS_CANONICAL(va),
4815 ("%s: Address not in canonical form: %lx", __func__, va));
4817 CTR2(KTR_PMAP, "pmap_enter_quick_locked: %p %lx", pmap, va);
4819 * In the case that a page table page is not
4820 * resident, we are creating it here.
4822 if (!ADDR_IS_KERNEL(va)) {
4823 vm_pindex_t l2pindex;
4826 * Calculate pagetable page index
4828 l2pindex = pmap_l2_pindex(va);
4829 if (mpte && (mpte->pindex == l2pindex)) {
4833 * If the page table page is mapped, we just increment
4834 * the hold count, and activate it. Otherwise, we
4835 * attempt to allocate a page table page, passing NULL
4836 * instead of the PV list lock pointer because we don't
4837 * intend to sleep. If this attempt fails, we don't
4838 * retry. Instead, we give up.
4840 l1 = pmap_l1(pmap, va);
4841 if (l1 != NULL && pmap_load(l1) != 0) {
4842 if ((pmap_load(l1) & ATTR_DESCR_MASK) ==
4845 l2 = pmap_l1_to_l2(l1, va);
4846 if (pmap_load(l2) != 0) {
4847 if ((pmap_load(l2) & ATTR_DESCR_MASK) ==
4850 mpte = PHYS_TO_VM_PAGE(pmap_load(l2) &
4854 mpte = _pmap_alloc_l3(pmap, l2pindex,
4860 mpte = _pmap_alloc_l3(pmap, l2pindex, NULL);
4865 l3 = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
4866 l3 = &l3[pmap_l3_index(va)];
4869 pde = pmap_pde(kernel_pmap, va, &lvl);
4870 KASSERT(pde != NULL,
4871 ("pmap_enter_quick_locked: Invalid page entry, va: 0x%lx",
4874 ("pmap_enter_quick_locked: Invalid level %d", lvl));
4875 l3 = pmap_l2_to_l3(pde, va);
4879 * Abort if a mapping already exists.
4881 if (pmap_load(l3) != 0) {
4888 * Enter on the PV list if part of our managed memory.
4890 if ((m->oflags & VPO_UNMANAGED) == 0 &&
4891 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
4893 pmap_abort_ptp(pmap, va, mpte);
4898 * Increment counters
4900 pmap_resident_count_inc(pmap, 1);
4902 pa = VM_PAGE_TO_PHYS(m);
4903 l3_val = pa | ATTR_DEFAULT | ATTR_S1_IDX(m->md.pv_memattr) |
4904 ATTR_S1_AP(ATTR_S1_AP_RO) | L3_PAGE;
4905 if ((prot & VM_PROT_EXECUTE) == 0 ||
4906 m->md.pv_memattr == VM_MEMATTR_DEVICE)
4907 l3_val |= ATTR_S1_XN;
4908 if (!ADDR_IS_KERNEL(va))
4909 l3_val |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
4911 l3_val |= ATTR_S1_UXN;
4912 if (pmap != kernel_pmap)
4913 l3_val |= ATTR_S1_nG;
4916 * Now validate mapping with RO protection
4918 if ((m->oflags & VPO_UNMANAGED) == 0) {
4919 l3_val |= ATTR_SW_MANAGED;
4923 /* Sync icache before the mapping is stored to PTE */
4924 if ((prot & VM_PROT_EXECUTE) && pmap != kernel_pmap &&
4925 m->md.pv_memattr == VM_MEMATTR_WRITE_BACK)
4926 cpu_icache_sync_range(PHYS_TO_DMAP(pa), PAGE_SIZE);
4928 pmap_store(l3, l3_val);
4935 * This code maps large physical mmap regions into the
4936 * processor address space. Note that some shortcuts
4937 * are taken, but the code works.
4940 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
4941 vm_pindex_t pindex, vm_size_t size)
4944 VM_OBJECT_ASSERT_WLOCKED(object);
4945 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
4946 ("pmap_object_init_pt: non-device object"));
4950 * Clear the wired attribute from the mappings for the specified range of
4951 * addresses in the given pmap. Every valid mapping within that range
4952 * must have the wired attribute set. In contrast, invalid mappings
4953 * cannot have the wired attribute set, so they are ignored.
4955 * The wired attribute of the page table entry is not a hardware feature,
4956 * so there is no need to invalidate any TLB entries.
4959 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4961 vm_offset_t va_next;
4962 pd_entry_t *l0, *l1, *l2;
4966 for (; sva < eva; sva = va_next) {
4967 l0 = pmap_l0(pmap, sva);
4968 if (pmap_load(l0) == 0) {
4969 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
4975 l1 = pmap_l0_to_l1(l0, sva);
4976 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
4979 if (pmap_load(l1) == 0)
4982 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
4983 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
4984 KASSERT(va_next <= eva,
4985 ("partial update of non-transparent 1G page "
4986 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
4987 pmap_load(l1), sva, eva, va_next));
4988 MPASS(pmap != kernel_pmap);
4989 MPASS((pmap_load(l1) & (ATTR_SW_MANAGED |
4990 ATTR_SW_WIRED)) == ATTR_SW_WIRED);
4991 pmap_clear_bits(l1, ATTR_SW_WIRED);
4992 pmap->pm_stats.wired_count -= L1_SIZE / PAGE_SIZE;
4996 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
5000 l2 = pmap_l1_to_l2(l1, sva);
5001 if (pmap_load(l2) == 0)
5004 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK) {
5005 if ((pmap_load(l2) & ATTR_SW_WIRED) == 0)
5006 panic("pmap_unwire: l2 %#jx is missing "
5007 "ATTR_SW_WIRED", (uintmax_t)pmap_load(l2));
5010 * Are we unwiring the entire large page? If not,
5011 * demote the mapping and fall through.
5013 if (sva + L2_SIZE == va_next && eva >= va_next) {
5014 pmap_clear_bits(l2, ATTR_SW_WIRED);
5015 pmap->pm_stats.wired_count -= L2_SIZE /
5018 } else if (pmap_demote_l2(pmap, l2, sva) == NULL)
5019 panic("pmap_unwire: demotion failed");
5021 KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
5022 ("pmap_unwire: Invalid l2 entry after demotion"));
5026 for (l3 = pmap_l2_to_l3(l2, sva); sva != va_next; l3++,
5028 if (pmap_load(l3) == 0)
5030 if ((pmap_load(l3) & ATTR_SW_WIRED) == 0)
5031 panic("pmap_unwire: l3 %#jx is missing "
5032 "ATTR_SW_WIRED", (uintmax_t)pmap_load(l3));
5035 * ATTR_SW_WIRED must be cleared atomically. Although
5036 * the pmap lock synchronizes access to ATTR_SW_WIRED,
5037 * the System MMU may write to the entry concurrently.
5039 pmap_clear_bits(l3, ATTR_SW_WIRED);
5040 pmap->pm_stats.wired_count--;
5047 * Copy the range specified by src_addr/len
5048 * from the source map to the range dst_addr/len
5049 * in the destination map.
5051 * This routine is only advisory and need not do anything.
5053 * Because the executable mappings created by this routine are copied,
5054 * it should not have to flush the instruction cache.
5057 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5058 vm_offset_t src_addr)
5060 struct rwlock *lock;
5061 pd_entry_t *l0, *l1, *l2, srcptepaddr;
5062 pt_entry_t *dst_pte, mask, nbits, ptetemp, *src_pte;
5063 vm_offset_t addr, end_addr, va_next;
5064 vm_page_t dst_m, dstmpte, srcmpte;
5066 PMAP_ASSERT_STAGE1(dst_pmap);
5067 PMAP_ASSERT_STAGE1(src_pmap);
5069 if (dst_addr != src_addr)
5071 end_addr = src_addr + len;
5073 if (dst_pmap < src_pmap) {
5074 PMAP_LOCK(dst_pmap);
5075 PMAP_LOCK(src_pmap);
5077 PMAP_LOCK(src_pmap);
5078 PMAP_LOCK(dst_pmap);
5080 for (addr = src_addr; addr < end_addr; addr = va_next) {
5081 l0 = pmap_l0(src_pmap, addr);
5082 if (pmap_load(l0) == 0) {
5083 va_next = (addr + L0_SIZE) & ~L0_OFFSET;
5089 va_next = (addr + L1_SIZE) & ~L1_OFFSET;
5092 l1 = pmap_l0_to_l1(l0, addr);
5093 if (pmap_load(l1) == 0)
5095 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
5096 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
5097 KASSERT(va_next <= end_addr,
5098 ("partial update of non-transparent 1G page "
5099 "l1 %#lx addr %#lx end_addr %#lx va_next %#lx",
5100 pmap_load(l1), addr, end_addr, va_next));
5101 srcptepaddr = pmap_load(l1);
5102 l1 = pmap_l1(dst_pmap, addr);
5104 if (_pmap_alloc_l3(dst_pmap,
5105 pmap_l0_pindex(addr), NULL) == NULL)
5107 l1 = pmap_l1(dst_pmap, addr);
5109 l0 = pmap_l0(dst_pmap, addr);
5110 dst_m = PHYS_TO_VM_PAGE(pmap_load(l0) &
5114 KASSERT(pmap_load(l1) == 0,
5115 ("1G mapping present in dst pmap "
5116 "l1 %#lx addr %#lx end_addr %#lx va_next %#lx",
5117 pmap_load(l1), addr, end_addr, va_next));
5118 pmap_store(l1, srcptepaddr & ~ATTR_SW_WIRED);
5119 pmap_resident_count_inc(dst_pmap, L1_SIZE / PAGE_SIZE);
5123 va_next = (addr + L2_SIZE) & ~L2_OFFSET;
5126 l2 = pmap_l1_to_l2(l1, addr);
5127 srcptepaddr = pmap_load(l2);
5128 if (srcptepaddr == 0)
5130 if ((srcptepaddr & ATTR_DESCR_MASK) == L2_BLOCK) {
5132 * We can only virtual copy whole superpages.
5134 if ((addr & L2_OFFSET) != 0 ||
5135 addr + L2_SIZE > end_addr)
5137 l2 = pmap_alloc_l2(dst_pmap, addr, &dst_m, NULL);
5140 if (pmap_load(l2) == 0 &&
5141 ((srcptepaddr & ATTR_SW_MANAGED) == 0 ||
5142 pmap_pv_insert_l2(dst_pmap, addr, srcptepaddr,
5143 PMAP_ENTER_NORECLAIM, &lock))) {
5145 * We leave the dirty bit unchanged because
5146 * managed read/write superpage mappings are
5147 * required to be dirty. However, managed
5148 * superpage mappings are not required to
5149 * have their accessed bit set, so we clear
5150 * it because we don't know if this mapping
5153 srcptepaddr &= ~ATTR_SW_WIRED;
5154 if ((srcptepaddr & ATTR_SW_MANAGED) != 0)
5155 srcptepaddr &= ~ATTR_AF;
5156 pmap_store(l2, srcptepaddr);
5157 pmap_resident_count_inc(dst_pmap, L2_SIZE /
5159 atomic_add_long(&pmap_l2_mappings, 1);
5161 pmap_abort_ptp(dst_pmap, addr, dst_m);
5164 KASSERT((srcptepaddr & ATTR_DESCR_MASK) == L2_TABLE,
5165 ("pmap_copy: invalid L2 entry"));
5166 srcptepaddr &= ~ATTR_MASK;
5167 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5168 KASSERT(srcmpte->ref_count > 0,
5169 ("pmap_copy: source page table page is unused"));
5170 if (va_next > end_addr)
5172 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5173 src_pte = &src_pte[pmap_l3_index(addr)];
5175 for (; addr < va_next; addr += PAGE_SIZE, src_pte++) {
5176 ptetemp = pmap_load(src_pte);
5179 * We only virtual copy managed pages.
5181 if ((ptetemp & ATTR_SW_MANAGED) == 0)
5184 if (dstmpte != NULL) {
5185 KASSERT(dstmpte->pindex == pmap_l2_pindex(addr),
5186 ("dstmpte pindex/addr mismatch"));
5187 dstmpte->ref_count++;
5188 } else if ((dstmpte = pmap_alloc_l3(dst_pmap, addr,
5191 dst_pte = (pt_entry_t *)
5192 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5193 dst_pte = &dst_pte[pmap_l3_index(addr)];
5194 if (pmap_load(dst_pte) == 0 &&
5195 pmap_try_insert_pv_entry(dst_pmap, addr,
5196 PHYS_TO_VM_PAGE(ptetemp & ~ATTR_MASK), &lock)) {
5198 * Clear the wired, modified, and accessed
5199 * (referenced) bits during the copy.
5201 mask = ATTR_AF | ATTR_SW_WIRED;
5203 if ((ptetemp & ATTR_SW_DBM) != 0)
5204 nbits |= ATTR_S1_AP_RW_BIT;
5205 pmap_store(dst_pte, (ptetemp & ~mask) | nbits);
5206 pmap_resident_count_inc(dst_pmap, 1);
5208 pmap_abort_ptp(dst_pmap, addr, dstmpte);
5211 /* Have we copied all of the valid mappings? */
5212 if (dstmpte->ref_count >= srcmpte->ref_count)
5218 * XXX This barrier may not be needed because the destination pmap is
5225 PMAP_UNLOCK(src_pmap);
5226 PMAP_UNLOCK(dst_pmap);
5230 * pmap_zero_page zeros the specified hardware page by mapping
5231 * the page into KVM and using bzero to clear its contents.
5234 pmap_zero_page(vm_page_t m)
5236 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5238 pagezero((void *)va);
5242 * pmap_zero_page_area zeros the specified hardware page by mapping
5243 * the page into KVM and using bzero to clear its contents.
5245 * off and size may not cover an area beyond a single hardware page.
5248 pmap_zero_page_area(vm_page_t m, int off, int size)
5250 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5252 if (off == 0 && size == PAGE_SIZE)
5253 pagezero((void *)va);
5255 bzero((char *)va + off, size);
5259 * pmap_copy_page copies the specified (machine independent)
5260 * page by mapping the page into virtual memory and using
5261 * bcopy to copy the page, one machine dependent page at a
5265 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5267 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5268 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5270 pagecopy((void *)src, (void *)dst);
5273 int unmapped_buf_allowed = 1;
5276 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5277 vm_offset_t b_offset, int xfersize)
5281 vm_paddr_t p_a, p_b;
5282 vm_offset_t a_pg_offset, b_pg_offset;
5285 while (xfersize > 0) {
5286 a_pg_offset = a_offset & PAGE_MASK;
5287 m_a = ma[a_offset >> PAGE_SHIFT];
5288 p_a = m_a->phys_addr;
5289 b_pg_offset = b_offset & PAGE_MASK;
5290 m_b = mb[b_offset >> PAGE_SHIFT];
5291 p_b = m_b->phys_addr;
5292 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5293 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5294 if (__predict_false(!PHYS_IN_DMAP(p_a))) {
5295 panic("!DMAP a %lx", p_a);
5297 a_cp = (char *)PHYS_TO_DMAP(p_a) + a_pg_offset;
5299 if (__predict_false(!PHYS_IN_DMAP(p_b))) {
5300 panic("!DMAP b %lx", p_b);
5302 b_cp = (char *)PHYS_TO_DMAP(p_b) + b_pg_offset;
5304 bcopy(a_cp, b_cp, cnt);
5312 pmap_quick_enter_page(vm_page_t m)
5315 return (PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)));
5319 pmap_quick_remove_page(vm_offset_t addr)
5324 * Returns true if the pmap's pv is one of the first
5325 * 16 pvs linked to from this page. This count may
5326 * be changed upwards or downwards in the future; it
5327 * is only necessary that true be returned for a small
5328 * subset of pmaps for proper page aging.
5331 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5333 struct md_page *pvh;
5334 struct rwlock *lock;
5339 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5340 ("pmap_page_exists_quick: page %p is not managed", m));
5342 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5344 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5345 if (PV_PMAP(pv) == pmap) {
5353 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5354 pvh = page_to_pvh(m);
5355 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5356 if (PV_PMAP(pv) == pmap) {
5370 * pmap_page_wired_mappings:
5372 * Return the number of managed mappings to the given physical page
5376 pmap_page_wired_mappings(vm_page_t m)
5378 struct rwlock *lock;
5379 struct md_page *pvh;
5383 int count, md_gen, pvh_gen;
5385 if ((m->oflags & VPO_UNMANAGED) != 0)
5387 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5391 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5393 if (!PMAP_TRYLOCK(pmap)) {
5394 md_gen = m->md.pv_gen;
5398 if (md_gen != m->md.pv_gen) {
5403 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
5404 if ((pmap_load(pte) & ATTR_SW_WIRED) != 0)
5408 if ((m->flags & PG_FICTITIOUS) == 0) {
5409 pvh = page_to_pvh(m);
5410 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5412 if (!PMAP_TRYLOCK(pmap)) {
5413 md_gen = m->md.pv_gen;
5414 pvh_gen = pvh->pv_gen;
5418 if (md_gen != m->md.pv_gen ||
5419 pvh_gen != pvh->pv_gen) {
5424 pte = pmap_pte_exists(pmap, pv->pv_va, 2, __func__);
5425 if ((pmap_load(pte) & ATTR_SW_WIRED) != 0)
5435 * Returns true if the given page is mapped individually or as part of
5436 * a 2mpage. Otherwise, returns false.
5439 pmap_page_is_mapped(vm_page_t m)
5441 struct rwlock *lock;
5444 if ((m->oflags & VPO_UNMANAGED) != 0)
5446 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5448 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5449 ((m->flags & PG_FICTITIOUS) == 0 &&
5450 !TAILQ_EMPTY(&page_to_pvh(m)->pv_list));
5456 * Destroy all managed, non-wired mappings in the given user-space
5457 * pmap. This pmap cannot be active on any processor besides the
5460 * This function cannot be applied to the kernel pmap. Moreover, it
5461 * is not intended for general use. It is only to be used during
5462 * process termination. Consequently, it can be implemented in ways
5463 * that make it faster than pmap_remove(). First, it can more quickly
5464 * destroy mappings by iterating over the pmap's collection of PV
5465 * entries, rather than searching the page table. Second, it doesn't
5466 * have to test and clear the page table entries atomically, because
5467 * no processor is currently accessing the user address space. In
5468 * particular, a page table entry's dirty bit won't change state once
5469 * this function starts.
5472 pmap_remove_pages(pmap_t pmap)
5475 pt_entry_t *pte, tpte;
5476 struct spglist free;
5477 struct pv_chunklist free_chunks[PMAP_MEMDOM];
5478 vm_page_t m, ml3, mt;
5480 struct md_page *pvh;
5481 struct pv_chunk *pc, *npc;
5482 struct rwlock *lock;
5484 uint64_t inuse, bitmask;
5485 int allfree, field, i, idx, lvl;
5491 for (i = 0; i < PMAP_MEMDOM; i++)
5492 TAILQ_INIT(&free_chunks[i]);
5495 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5498 for (field = 0; field < _NPCM; field++) {
5499 inuse = ~pc->pc_map[field] & pc_freemask[field];
5500 while (inuse != 0) {
5501 bit = ffsl(inuse) - 1;
5502 bitmask = 1UL << bit;
5503 idx = field * 64 + bit;
5504 pv = &pc->pc_pventry[idx];
5507 pde = pmap_pde(pmap, pv->pv_va, &lvl);
5508 KASSERT(pde != NULL,
5509 ("Attempting to remove an unmapped page"));
5513 pte = pmap_l1_to_l2(pde, pv->pv_va);
5514 tpte = pmap_load(pte);
5515 KASSERT((tpte & ATTR_DESCR_MASK) ==
5517 ("Attempting to remove an invalid "
5518 "block: %lx", tpte));
5521 pte = pmap_l2_to_l3(pde, pv->pv_va);
5522 tpte = pmap_load(pte);
5523 KASSERT((tpte & ATTR_DESCR_MASK) ==
5525 ("Attempting to remove an invalid "
5526 "page: %lx", tpte));
5530 "Invalid page directory level: %d",
5535 * We cannot remove wired pages from a process' mapping at this time
5537 if (tpte & ATTR_SW_WIRED) {
5543 pc->pc_map[field] |= bitmask;
5546 * Because this pmap is not active on other
5547 * processors, the dirty bit cannot have
5548 * changed state since we last loaded pte.
5552 pa = tpte & ~ATTR_MASK;
5554 m = PHYS_TO_VM_PAGE(pa);
5555 KASSERT(m->phys_addr == pa,
5556 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5557 m, (uintmax_t)m->phys_addr,
5560 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5561 m < &vm_page_array[vm_page_array_size],
5562 ("pmap_remove_pages: bad pte %#jx",
5566 * Update the vm_page_t clean/reference bits.
5568 if (pmap_pte_dirty(pmap, tpte)) {
5571 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
5580 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5584 pmap_resident_count_dec(pmap,
5585 L2_SIZE / PAGE_SIZE);
5586 pvh = page_to_pvh(m);
5587 TAILQ_REMOVE(&pvh->pv_list, pv,pv_next);
5589 if (TAILQ_EMPTY(&pvh->pv_list)) {
5590 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
5591 if ((mt->a.flags & PGA_WRITEABLE) != 0 &&
5592 TAILQ_EMPTY(&mt->md.pv_list))
5593 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5595 ml3 = pmap_remove_pt_page(pmap,
5598 KASSERT(ml3->valid == VM_PAGE_BITS_ALL,
5599 ("pmap_remove_pages: l3 page not promoted"));
5600 pmap_resident_count_dec(pmap,1);
5601 KASSERT(ml3->ref_count == NL3PG,
5602 ("pmap_remove_pages: l3 page ref count error"));
5604 pmap_add_delayed_free_list(ml3,
5609 pmap_resident_count_dec(pmap, 1);
5610 TAILQ_REMOVE(&m->md.pv_list, pv,
5613 if ((m->a.flags & PGA_WRITEABLE) != 0 &&
5614 TAILQ_EMPTY(&m->md.pv_list) &&
5615 (m->flags & PG_FICTITIOUS) == 0) {
5616 pvh = page_to_pvh(m);
5617 if (TAILQ_EMPTY(&pvh->pv_list))
5618 vm_page_aflag_clear(m,
5623 pmap_unuse_pt(pmap, pv->pv_va, pmap_load(pde),
5628 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5629 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5630 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5632 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5633 TAILQ_INSERT_TAIL(&free_chunks[pc_to_domain(pc)], pc,
5639 pmap_invalidate_all(pmap);
5640 free_pv_chunk_batch(free_chunks);
5642 vm_page_free_pages_toq(&free, true);
5646 * This is used to check if a page has been accessed or modified.
5649 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
5651 struct rwlock *lock;
5653 struct md_page *pvh;
5654 pt_entry_t *pte, mask, value;
5656 int md_gen, pvh_gen;
5660 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5663 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5665 PMAP_ASSERT_STAGE1(pmap);
5666 if (!PMAP_TRYLOCK(pmap)) {
5667 md_gen = m->md.pv_gen;
5671 if (md_gen != m->md.pv_gen) {
5676 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
5680 mask |= ATTR_S1_AP_RW_BIT;
5681 value |= ATTR_S1_AP(ATTR_S1_AP_RW);
5684 mask |= ATTR_AF | ATTR_DESCR_MASK;
5685 value |= ATTR_AF | L3_PAGE;
5687 rv = (pmap_load(pte) & mask) == value;
5692 if ((m->flags & PG_FICTITIOUS) == 0) {
5693 pvh = page_to_pvh(m);
5694 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5696 PMAP_ASSERT_STAGE1(pmap);
5697 if (!PMAP_TRYLOCK(pmap)) {
5698 md_gen = m->md.pv_gen;
5699 pvh_gen = pvh->pv_gen;
5703 if (md_gen != m->md.pv_gen ||
5704 pvh_gen != pvh->pv_gen) {
5709 pte = pmap_pte_exists(pmap, pv->pv_va, 2, __func__);
5713 mask |= ATTR_S1_AP_RW_BIT;
5714 value |= ATTR_S1_AP(ATTR_S1_AP_RW);
5717 mask |= ATTR_AF | ATTR_DESCR_MASK;
5718 value |= ATTR_AF | L2_BLOCK;
5720 rv = (pmap_load(pte) & mask) == value;
5734 * Return whether or not the specified physical page was modified
5735 * in any physical maps.
5738 pmap_is_modified(vm_page_t m)
5741 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5742 ("pmap_is_modified: page %p is not managed", m));
5745 * If the page is not busied then this check is racy.
5747 if (!pmap_page_is_write_mapped(m))
5749 return (pmap_page_test_mappings(m, FALSE, TRUE));
5753 * pmap_is_prefaultable:
5755 * Return whether or not the specified virtual address is eligible
5759 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
5767 * Return TRUE if and only if the L3 entry for the specified virtual
5768 * address is allocated but invalid.
5772 pde = pmap_pde(pmap, addr, &lvl);
5773 if (pde != NULL && lvl == 2) {
5774 pte = pmap_l2_to_l3(pde, addr);
5775 rv = pmap_load(pte) == 0;
5782 * pmap_is_referenced:
5784 * Return whether or not the specified physical page was referenced
5785 * in any physical maps.
5788 pmap_is_referenced(vm_page_t m)
5791 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5792 ("pmap_is_referenced: page %p is not managed", m));
5793 return (pmap_page_test_mappings(m, TRUE, FALSE));
5797 * Clear the write and modified bits in each of the given page's mappings.
5800 pmap_remove_write(vm_page_t m)
5802 struct md_page *pvh;
5804 struct rwlock *lock;
5805 pv_entry_t next_pv, pv;
5806 pt_entry_t oldpte, *pte, set, clear, mask, val;
5808 int md_gen, pvh_gen;
5810 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5811 ("pmap_remove_write: page %p is not managed", m));
5812 vm_page_assert_busied(m);
5814 if (!pmap_page_is_write_mapped(m))
5816 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5817 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
5820 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
5822 PMAP_ASSERT_STAGE1(pmap);
5823 if (!PMAP_TRYLOCK(pmap)) {
5824 pvh_gen = pvh->pv_gen;
5828 if (pvh_gen != pvh->pv_gen) {
5834 pte = pmap_pte_exists(pmap, va, 2, __func__);
5835 if ((pmap_load(pte) & ATTR_SW_DBM) != 0)
5836 (void)pmap_demote_l2_locked(pmap, pte, va, &lock);
5837 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
5838 ("inconsistent pv lock %p %p for page %p",
5839 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
5842 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5844 if (!PMAP_TRYLOCK(pmap)) {
5845 pvh_gen = pvh->pv_gen;
5846 md_gen = m->md.pv_gen;
5850 if (pvh_gen != pvh->pv_gen ||
5851 md_gen != m->md.pv_gen) {
5856 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
5857 oldpte = pmap_load(pte);
5858 if ((oldpte & ATTR_SW_DBM) != 0) {
5859 if (pmap->pm_stage == PM_STAGE1) {
5860 set = ATTR_S1_AP_RW_BIT;
5862 mask = ATTR_S1_AP_RW_BIT;
5863 val = ATTR_S1_AP(ATTR_S1_AP_RW);
5866 clear = ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
5867 mask = ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
5868 val = ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
5870 clear |= ATTR_SW_DBM;
5871 while (!atomic_fcmpset_64(pte, &oldpte,
5872 (oldpte | set) & ~clear))
5875 if ((oldpte & mask) == val)
5877 pmap_invalidate_page(pmap, pv->pv_va, true);
5882 vm_page_aflag_clear(m, PGA_WRITEABLE);
5886 * pmap_ts_referenced:
5888 * Return a count of reference bits for a page, clearing those bits.
5889 * It is not necessary for every reference bit to be cleared, but it
5890 * is necessary that 0 only be returned when there are truly no
5891 * reference bits set.
5893 * As an optimization, update the page's dirty field if a modified bit is
5894 * found while counting reference bits. This opportunistic update can be
5895 * performed at low cost and can eliminate the need for some future calls
5896 * to pmap_is_modified(). However, since this function stops after
5897 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
5898 * dirty pages. Those dirty pages will only be detected by a future call
5899 * to pmap_is_modified().
5902 pmap_ts_referenced(vm_page_t m)
5904 struct md_page *pvh;
5907 struct rwlock *lock;
5908 pt_entry_t *pte, tpte;
5911 int cleared, md_gen, not_cleared, pvh_gen;
5912 struct spglist free;
5914 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5915 ("pmap_ts_referenced: page %p is not managed", m));
5918 pa = VM_PAGE_TO_PHYS(m);
5919 lock = PHYS_TO_PV_LIST_LOCK(pa);
5920 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
5924 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
5925 goto small_mappings;
5931 if (!PMAP_TRYLOCK(pmap)) {
5932 pvh_gen = pvh->pv_gen;
5936 if (pvh_gen != pvh->pv_gen) {
5942 pte = pmap_pte_exists(pmap, va, 2, __func__);
5943 tpte = pmap_load(pte);
5944 if (pmap_pte_dirty(pmap, tpte)) {
5946 * Although "tpte" is mapping a 2MB page, because
5947 * this function is called at a 4KB page granularity,
5948 * we only update the 4KB page under test.
5952 if ((tpte & ATTR_AF) != 0) {
5954 * Since this reference bit is shared by 512 4KB pages,
5955 * it should not be cleared every time it is tested.
5956 * Apply a simple "hash" function on the physical page
5957 * number, the virtual superpage number, and the pmap
5958 * address to select one 4KB page out of the 512 on
5959 * which testing the reference bit will result in
5960 * clearing that reference bit. This function is
5961 * designed to avoid the selection of the same 4KB page
5962 * for every 2MB page mapping.
5964 * On demotion, a mapping that hasn't been referenced
5965 * is simply destroyed. To avoid the possibility of a
5966 * subsequent page fault on a demoted wired mapping,
5967 * always leave its reference bit set. Moreover,
5968 * since the superpage is wired, the current state of
5969 * its reference bit won't affect page replacement.
5971 if ((((pa >> PAGE_SHIFT) ^ (va >> L2_SHIFT) ^
5972 (uintptr_t)pmap) & (Ln_ENTRIES - 1)) == 0 &&
5973 (tpte & ATTR_SW_WIRED) == 0) {
5974 pmap_clear_bits(pte, ATTR_AF);
5975 pmap_invalidate_page(pmap, va, true);
5981 /* Rotate the PV list if it has more than one entry. */
5982 if (TAILQ_NEXT(pv, pv_next) != NULL) {
5983 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5984 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5987 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
5989 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
5991 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
5998 if (!PMAP_TRYLOCK(pmap)) {
5999 pvh_gen = pvh->pv_gen;
6000 md_gen = m->md.pv_gen;
6004 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6009 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
6010 tpte = pmap_load(pte);
6011 if (pmap_pte_dirty(pmap, tpte))
6013 if ((tpte & ATTR_AF) != 0) {
6014 if ((tpte & ATTR_SW_WIRED) == 0) {
6015 pmap_clear_bits(pte, ATTR_AF);
6016 pmap_invalidate_page(pmap, pv->pv_va, true);
6022 /* Rotate the PV list if it has more than one entry. */
6023 if (TAILQ_NEXT(pv, pv_next) != NULL) {
6024 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6025 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6028 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6029 not_cleared < PMAP_TS_REFERENCED_MAX);
6032 vm_page_free_pages_toq(&free, true);
6033 return (cleared + not_cleared);
6037 * Apply the given advice to the specified range of addresses within the
6038 * given pmap. Depending on the advice, clear the referenced and/or
6039 * modified flags in each mapping and set the mapped page's dirty field.
6042 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6044 struct rwlock *lock;
6045 vm_offset_t va, va_next;
6047 pd_entry_t *l0, *l1, *l2, oldl2;
6048 pt_entry_t *l3, oldl3;
6050 PMAP_ASSERT_STAGE1(pmap);
6052 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6056 for (; sva < eva; sva = va_next) {
6057 l0 = pmap_l0(pmap, sva);
6058 if (pmap_load(l0) == 0) {
6059 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
6065 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
6068 l1 = pmap_l0_to_l1(l0, sva);
6069 if (pmap_load(l1) == 0)
6071 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
6072 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
6076 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
6079 l2 = pmap_l1_to_l2(l1, sva);
6080 oldl2 = pmap_load(l2);
6083 if ((oldl2 & ATTR_DESCR_MASK) == L2_BLOCK) {
6084 if ((oldl2 & ATTR_SW_MANAGED) == 0)
6087 if (!pmap_demote_l2_locked(pmap, l2, sva, &lock)) {
6092 * The 2MB page mapping was destroyed.
6098 * Unless the page mappings are wired, remove the
6099 * mapping to a single page so that a subsequent
6100 * access may repromote. Choosing the last page
6101 * within the address range [sva, min(va_next, eva))
6102 * generally results in more repromotions. Since the
6103 * underlying page table page is fully populated, this
6104 * removal never frees a page table page.
6106 if ((oldl2 & ATTR_SW_WIRED) == 0) {
6112 ("pmap_advise: no address gap"));
6113 l3 = pmap_l2_to_l3(l2, va);
6114 KASSERT(pmap_load(l3) != 0,
6115 ("pmap_advise: invalid PTE"));
6116 pmap_remove_l3(pmap, l3, va, pmap_load(l2),
6122 KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
6123 ("pmap_advise: invalid L2 entry after demotion"));
6127 for (l3 = pmap_l2_to_l3(l2, sva); sva != va_next; l3++,
6129 oldl3 = pmap_load(l3);
6130 if ((oldl3 & (ATTR_SW_MANAGED | ATTR_DESCR_MASK)) !=
6131 (ATTR_SW_MANAGED | L3_PAGE))
6133 else if (pmap_pte_dirty(pmap, oldl3)) {
6134 if (advice == MADV_DONTNEED) {
6136 * Future calls to pmap_is_modified()
6137 * can be avoided by making the page
6140 m = PHYS_TO_VM_PAGE(oldl3 & ~ATTR_MASK);
6143 while (!atomic_fcmpset_long(l3, &oldl3,
6144 (oldl3 & ~ATTR_AF) |
6145 ATTR_S1_AP(ATTR_S1_AP_RO)))
6147 } else if ((oldl3 & ATTR_AF) != 0)
6148 pmap_clear_bits(l3, ATTR_AF);
6155 if (va != va_next) {
6156 pmap_s1_invalidate_range(pmap, va, sva, true);
6161 pmap_s1_invalidate_range(pmap, va, sva, true);
6167 * Clear the modify bits on the specified physical page.
6170 pmap_clear_modify(vm_page_t m)
6172 struct md_page *pvh;
6173 struct rwlock *lock;
6175 pv_entry_t next_pv, pv;
6176 pd_entry_t *l2, oldl2;
6177 pt_entry_t *l3, oldl3;
6179 int md_gen, pvh_gen;
6181 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6182 ("pmap_clear_modify: page %p is not managed", m));
6183 vm_page_assert_busied(m);
6185 if (!pmap_page_is_write_mapped(m))
6187 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
6188 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6191 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6193 PMAP_ASSERT_STAGE1(pmap);
6194 if (!PMAP_TRYLOCK(pmap)) {
6195 pvh_gen = pvh->pv_gen;
6199 if (pvh_gen != pvh->pv_gen) {
6205 l2 = pmap_l2(pmap, va);
6206 oldl2 = pmap_load(l2);
6207 /* If oldl2 has ATTR_SW_DBM set, then it is also dirty. */
6208 if ((oldl2 & ATTR_SW_DBM) != 0 &&
6209 pmap_demote_l2_locked(pmap, l2, va, &lock) &&
6210 (oldl2 & ATTR_SW_WIRED) == 0) {
6212 * Write protect the mapping to a single page so that
6213 * a subsequent write access may repromote.
6215 va += VM_PAGE_TO_PHYS(m) - (oldl2 & ~ATTR_MASK);
6216 l3 = pmap_l2_to_l3(l2, va);
6217 oldl3 = pmap_load(l3);
6218 while (!atomic_fcmpset_long(l3, &oldl3,
6219 (oldl3 & ~ATTR_SW_DBM) | ATTR_S1_AP(ATTR_S1_AP_RO)))
6222 pmap_s1_invalidate_page(pmap, va, true);
6226 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6228 PMAP_ASSERT_STAGE1(pmap);
6229 if (!PMAP_TRYLOCK(pmap)) {
6230 md_gen = m->md.pv_gen;
6231 pvh_gen = pvh->pv_gen;
6235 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6240 l2 = pmap_l2(pmap, pv->pv_va);
6241 l3 = pmap_l2_to_l3(l2, pv->pv_va);
6242 oldl3 = pmap_load(l3);
6243 if ((oldl3 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) == ATTR_SW_DBM){
6244 pmap_set_bits(l3, ATTR_S1_AP(ATTR_S1_AP_RO));
6245 pmap_s1_invalidate_page(pmap, pv->pv_va, true);
6253 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6255 struct pmap_preinit_mapping *ppim;
6256 vm_offset_t va, offset;
6259 int i, lvl, l2_blocks, free_l2_count, start_idx;
6261 if (!vm_initialized) {
6263 * No L3 ptables so map entire L2 blocks where start VA is:
6264 * preinit_map_va + start_idx * L2_SIZE
6265 * There may be duplicate mappings (multiple VA -> same PA) but
6266 * ARM64 dcache is always PIPT so that's acceptable.
6271 /* Calculate how many L2 blocks are needed for the mapping */
6272 l2_blocks = (roundup2(pa + size, L2_SIZE) -
6273 rounddown2(pa, L2_SIZE)) >> L2_SHIFT;
6275 offset = pa & L2_OFFSET;
6277 if (preinit_map_va == 0)
6280 /* Map 2MiB L2 blocks from reserved VA space */
6284 /* Find enough free contiguous VA space */
6285 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6286 ppim = pmap_preinit_mapping + i;
6287 if (free_l2_count > 0 && ppim->pa != 0) {
6288 /* Not enough space here */
6294 if (ppim->pa == 0) {
6296 if (start_idx == -1)
6299 if (free_l2_count == l2_blocks)
6303 if (free_l2_count != l2_blocks)
6304 panic("%s: too many preinit mappings", __func__);
6306 va = preinit_map_va + (start_idx * L2_SIZE);
6307 for (i = start_idx; i < start_idx + l2_blocks; i++) {
6308 /* Mark entries as allocated */
6309 ppim = pmap_preinit_mapping + i;
6311 ppim->va = va + offset;
6316 pa = rounddown2(pa, L2_SIZE);
6317 for (i = 0; i < l2_blocks; i++) {
6318 pde = pmap_pde(kernel_pmap, va, &lvl);
6319 KASSERT(pde != NULL,
6320 ("pmap_mapbios: Invalid page entry, va: 0x%lx",
6323 ("pmap_mapbios: Invalid level %d", lvl));
6325 /* Insert L2_BLOCK */
6326 l2 = pmap_l1_to_l2(pde, va);
6328 pa | ATTR_DEFAULT | ATTR_S1_XN |
6329 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) | L2_BLOCK);
6334 pmap_s1_invalidate_all(kernel_pmap);
6336 va = preinit_map_va + (start_idx * L2_SIZE);
6339 /* kva_alloc may be used to map the pages */
6340 offset = pa & PAGE_MASK;
6341 size = round_page(offset + size);
6343 va = kva_alloc(size);
6345 panic("%s: Couldn't allocate KVA", __func__);
6347 pde = pmap_pde(kernel_pmap, va, &lvl);
6348 KASSERT(lvl == 2, ("pmap_mapbios: Invalid level %d", lvl));
6350 /* L3 table is linked */
6351 va = trunc_page(va);
6352 pa = trunc_page(pa);
6353 pmap_kenter(va, size, pa, memory_mapping_mode(pa));
6356 return ((void *)(va + offset));
6360 pmap_unmapbios(void *p, vm_size_t size)
6362 struct pmap_preinit_mapping *ppim;
6363 vm_offset_t offset, tmpsize, va, va_trunc;
6366 int i, lvl, l2_blocks, block;
6369 va = (vm_offset_t)p;
6371 (roundup2(va + size, L2_SIZE) - rounddown2(va, L2_SIZE)) >> L2_SHIFT;
6372 KASSERT(l2_blocks > 0, ("pmap_unmapbios: invalid size %lx", size));
6374 /* Remove preinit mapping */
6375 preinit_map = false;
6377 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6378 ppim = pmap_preinit_mapping + i;
6379 if (ppim->va == va) {
6380 KASSERT(ppim->size == size,
6381 ("pmap_unmapbios: size mismatch"));
6386 offset = block * L2_SIZE;
6387 va_trunc = rounddown2(va, L2_SIZE) + offset;
6389 /* Remove L2_BLOCK */
6390 pde = pmap_pde(kernel_pmap, va_trunc, &lvl);
6391 KASSERT(pde != NULL,
6392 ("pmap_unmapbios: Invalid page entry, va: 0x%lx",
6394 l2 = pmap_l1_to_l2(pde, va_trunc);
6397 if (block == (l2_blocks - 1))
6403 pmap_s1_invalidate_all(kernel_pmap);
6407 /* Unmap the pages reserved with kva_alloc. */
6408 if (vm_initialized) {
6409 offset = va & PAGE_MASK;
6410 size = round_page(offset + size);
6411 va = trunc_page(va);
6413 pde = pmap_pde(kernel_pmap, va, &lvl);
6414 KASSERT(pde != NULL,
6415 ("pmap_unmapbios: Invalid page entry, va: 0x%lx", va));
6416 KASSERT(lvl == 2, ("pmap_unmapbios: Invalid level %d", lvl));
6418 /* Unmap and invalidate the pages */
6419 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6420 pmap_kremove(va + tmpsize);
6427 * Sets the memory attribute for the specified page.
6430 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6433 m->md.pv_memattr = ma;
6436 * If "m" is a normal page, update its direct mapping. This update
6437 * can be relied upon to perform any cache operations that are
6438 * required for data coherence.
6440 if ((m->flags & PG_FICTITIOUS) == 0 &&
6441 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6442 m->md.pv_memattr) != 0)
6443 panic("memory attribute change on the direct map failed");
6447 * Changes the specified virtual address range's memory type to that given by
6448 * the parameter "mode". The specified virtual address range must be
6449 * completely contained within either the direct map or the kernel map. If
6450 * the virtual address range is contained within the kernel map, then the
6451 * memory type for each of the corresponding ranges of the direct map is also
6452 * changed. (The corresponding ranges of the direct map are those ranges that
6453 * map the same physical pages as the specified virtual address range.) These
6454 * changes to the direct map are necessary because Intel describes the
6455 * behavior of their processors as "undefined" if two or more mappings to the
6456 * same physical page have different memory types.
6458 * Returns zero if the change completed successfully, and either EINVAL or
6459 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6460 * of the virtual address range was not mapped, and ENOMEM is returned if
6461 * there was insufficient memory available to complete the change. In the
6462 * latter case, the memory type may have been changed on some part of the
6463 * virtual address range or the direct map.
6466 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6470 PMAP_LOCK(kernel_pmap);
6471 error = pmap_change_props_locked(va, size, PROT_NONE, mode, false);
6472 PMAP_UNLOCK(kernel_pmap);
6477 * Changes the specified virtual address range's protections to those
6478 * specified by "prot". Like pmap_change_attr(), protections for aliases
6479 * in the direct map are updated as well. Protections on aliasing mappings may
6480 * be a subset of the requested protections; for example, mappings in the direct
6481 * map are never executable.
6484 pmap_change_prot(vm_offset_t va, vm_size_t size, vm_prot_t prot)
6488 /* Only supported within the kernel map. */
6489 if (va < VM_MIN_KERNEL_ADDRESS)
6492 PMAP_LOCK(kernel_pmap);
6493 error = pmap_change_props_locked(va, size, prot, -1, false);
6494 PMAP_UNLOCK(kernel_pmap);
6499 pmap_change_props_locked(vm_offset_t va, vm_size_t size, vm_prot_t prot,
6500 int mode, bool skip_unmapped)
6502 vm_offset_t base, offset, tmpva;
6505 pt_entry_t pte, *ptep, *newpte;
6506 pt_entry_t bits, mask;
6509 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6510 base = trunc_page(va);
6511 offset = va & PAGE_MASK;
6512 size = round_page(offset + size);
6514 if (!VIRT_IN_DMAP(base) &&
6515 !(base >= VM_MIN_KERNEL_ADDRESS && base < VM_MAX_KERNEL_ADDRESS))
6521 bits = ATTR_S1_IDX(mode);
6522 mask = ATTR_S1_IDX_MASK;
6523 if (mode == VM_MEMATTR_DEVICE) {
6528 if (prot != VM_PROT_NONE) {
6529 /* Don't mark the DMAP as executable. It never is on arm64. */
6530 if (VIRT_IN_DMAP(base)) {
6531 prot &= ~VM_PROT_EXECUTE;
6533 * XXX Mark the DMAP as writable for now. We rely
6534 * on this in ddb & dtrace to insert breakpoint
6537 prot |= VM_PROT_WRITE;
6540 if ((prot & VM_PROT_WRITE) == 0) {
6541 bits |= ATTR_S1_AP(ATTR_S1_AP_RO);
6543 if ((prot & VM_PROT_EXECUTE) == 0) {
6544 bits |= ATTR_S1_PXN;
6546 bits |= ATTR_S1_UXN;
6547 mask |= ATTR_S1_AP_MASK | ATTR_S1_XN;
6550 for (tmpva = base; tmpva < base + size; ) {
6551 ptep = pmap_pte(kernel_pmap, tmpva, &lvl);
6552 if (ptep == NULL && !skip_unmapped) {
6554 } else if ((ptep == NULL && skip_unmapped) ||
6555 (pmap_load(ptep) & mask) == bits) {
6557 * We already have the correct attribute or there
6558 * is no memory mapped at this address and we are
6559 * skipping unmapped memory.
6563 panic("Invalid DMAP table level: %d\n", lvl);
6565 tmpva = (tmpva & ~L1_OFFSET) + L1_SIZE;
6568 tmpva = (tmpva & ~L2_OFFSET) + L2_SIZE;
6575 /* We can't demote/promote this entry */
6576 MPASS((pmap_load(ptep) & ATTR_SW_NO_PROMOTE) == 0);
6579 * Split the entry to an level 3 table, then
6580 * set the new attribute.
6584 panic("Invalid DMAP table level: %d\n", lvl);
6586 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
6587 if ((tmpva & L1_OFFSET) == 0 &&
6588 (base + size - tmpva) >= L1_SIZE) {
6592 newpte = pmap_demote_l1(kernel_pmap, ptep,
6593 tmpva & ~L1_OFFSET);
6596 ptep = pmap_l1_to_l2(ptep, tmpva);
6599 if ((tmpva & L2_OFFSET) == 0 &&
6600 (base + size - tmpva) >= L2_SIZE) {
6604 newpte = pmap_demote_l2(kernel_pmap, ptep,
6608 ptep = pmap_l2_to_l3(ptep, tmpva);
6611 pte_size = PAGE_SIZE;
6615 /* Update the entry */
6616 pte = pmap_load(ptep);
6620 pmap_update_entry(kernel_pmap, ptep, pte, tmpva,
6623 pa = pte & ~ATTR_MASK;
6624 if (!VIRT_IN_DMAP(tmpva) && PHYS_IN_DMAP(pa)) {
6626 * Keep the DMAP memory in sync.
6628 rv = pmap_change_props_locked(
6629 PHYS_TO_DMAP(pa), pte_size,
6636 * If moving to a non-cacheable entry flush
6639 if (mode == VM_MEMATTR_UNCACHEABLE)
6640 cpu_dcache_wbinv_range(tmpva, pte_size);
6649 * Create an L2 table to map all addresses within an L1 mapping.
6652 pmap_demote_l1(pmap_t pmap, pt_entry_t *l1, vm_offset_t va)
6654 pt_entry_t *l2, newl2, oldl1;
6656 vm_paddr_t l2phys, phys;
6660 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6661 oldl1 = pmap_load(l1);
6662 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
6663 KASSERT((oldl1 & ATTR_DESCR_MASK) == L1_BLOCK,
6664 ("pmap_demote_l1: Demoting a non-block entry"));
6665 KASSERT((va & L1_OFFSET) == 0,
6666 ("pmap_demote_l1: Invalid virtual address %#lx", va));
6667 KASSERT((oldl1 & ATTR_SW_MANAGED) == 0,
6668 ("pmap_demote_l1: Level 1 table shouldn't be managed"));
6669 KASSERT((oldl1 & ATTR_SW_NO_PROMOTE) == 0,
6670 ("pmap_demote_l1: Demoting entry with no-demote flag set"));
6673 if (va <= (vm_offset_t)l1 && va + L1_SIZE > (vm_offset_t)l1) {
6674 tmpl1 = kva_alloc(PAGE_SIZE);
6679 if ((ml2 = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED)) ==
6681 CTR2(KTR_PMAP, "pmap_demote_l1: failure for va %#lx"
6682 " in pmap %p", va, pmap);
6687 l2phys = VM_PAGE_TO_PHYS(ml2);
6688 l2 = (pt_entry_t *)PHYS_TO_DMAP(l2phys);
6690 /* Address the range points at */
6691 phys = oldl1 & ~ATTR_MASK;
6692 /* The attributed from the old l1 table to be copied */
6693 newl2 = oldl1 & ATTR_MASK;
6695 /* Create the new entries */
6696 for (i = 0; i < Ln_ENTRIES; i++) {
6697 l2[i] = newl2 | phys;
6700 KASSERT(l2[0] == ((oldl1 & ~ATTR_DESCR_MASK) | L2_BLOCK),
6701 ("Invalid l2 page (%lx != %lx)", l2[0],
6702 (oldl1 & ~ATTR_DESCR_MASK) | L2_BLOCK));
6705 pmap_kenter(tmpl1, PAGE_SIZE,
6706 DMAP_TO_PHYS((vm_offset_t)l1) & ~L3_OFFSET,
6707 VM_MEMATTR_WRITE_BACK);
6708 l1 = (pt_entry_t *)(tmpl1 + ((vm_offset_t)l1 & PAGE_MASK));
6711 pmap_update_entry(pmap, l1, l2phys | L1_TABLE, va, PAGE_SIZE);
6715 pmap_kremove(tmpl1);
6716 kva_free(tmpl1, PAGE_SIZE);
6723 pmap_fill_l3(pt_entry_t *firstl3, pt_entry_t newl3)
6727 for (l3 = firstl3; l3 - firstl3 < Ln_ENTRIES; l3++) {
6734 pmap_demote_l2_abort(pmap_t pmap, vm_offset_t va, pt_entry_t *l2,
6735 struct rwlock **lockp)
6737 struct spglist free;
6740 (void)pmap_remove_l2(pmap, l2, va, pmap_load(pmap_l1(pmap, va)), &free,
6742 vm_page_free_pages_toq(&free, true);
6746 * Create an L3 table to map all addresses within an L2 mapping.
6749 pmap_demote_l2_locked(pmap_t pmap, pt_entry_t *l2, vm_offset_t va,
6750 struct rwlock **lockp)
6752 pt_entry_t *l3, newl3, oldl2;
6757 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6758 PMAP_ASSERT_STAGE1(pmap);
6759 KASSERT(ADDR_IS_CANONICAL(va),
6760 ("%s: Address not in canonical form: %lx", __func__, va));
6763 oldl2 = pmap_load(l2);
6764 KASSERT((oldl2 & ATTR_DESCR_MASK) == L2_BLOCK,
6765 ("pmap_demote_l2: Demoting a non-block entry"));
6766 KASSERT((oldl2 & ATTR_SW_NO_PROMOTE) == 0,
6767 ("pmap_demote_l2: Demoting entry with no-demote flag set"));
6771 if (va <= (vm_offset_t)l2 && va + L2_SIZE > (vm_offset_t)l2) {
6772 tmpl2 = kva_alloc(PAGE_SIZE);
6778 * Invalidate the 2MB page mapping and return "failure" if the
6779 * mapping was never accessed.
6781 if ((oldl2 & ATTR_AF) == 0) {
6782 KASSERT((oldl2 & ATTR_SW_WIRED) == 0,
6783 ("pmap_demote_l2: a wired mapping is missing ATTR_AF"));
6784 pmap_demote_l2_abort(pmap, va, l2, lockp);
6785 CTR2(KTR_PMAP, "pmap_demote_l2: failure for va %#lx in pmap %p",
6790 if ((ml3 = pmap_remove_pt_page(pmap, va)) == NULL) {
6791 KASSERT((oldl2 & ATTR_SW_WIRED) == 0,
6792 ("pmap_demote_l2: page table page for a wired mapping"
6796 * If the page table page is missing and the mapping
6797 * is for a kernel address, the mapping must belong to
6798 * either the direct map or the early kernel memory.
6799 * Page table pages are preallocated for every other
6800 * part of the kernel address space, so the direct map
6801 * region and early kernel memory are the only parts of the
6802 * kernel address space that must be handled here.
6804 KASSERT(!ADDR_IS_KERNEL(va) || VIRT_IN_DMAP(va) ||
6805 (va >= VM_MIN_KERNEL_ADDRESS && va < kernel_vm_end),
6806 ("pmap_demote_l2: No saved mpte for va %#lx", va));
6809 * If the 2MB page mapping belongs to the direct map
6810 * region of the kernel's address space, then the page
6811 * allocation request specifies the highest possible
6812 * priority (VM_ALLOC_INTERRUPT). Otherwise, the
6813 * priority is normal.
6815 ml3 = vm_page_alloc_noobj(
6816 (VIRT_IN_DMAP(va) ? VM_ALLOC_INTERRUPT : 0) |
6820 * If the allocation of the new page table page fails,
6821 * invalidate the 2MB page mapping and return "failure".
6824 pmap_demote_l2_abort(pmap, va, l2, lockp);
6825 CTR2(KTR_PMAP, "pmap_demote_l2: failure for va %#lx"
6826 " in pmap %p", va, pmap);
6829 ml3->pindex = pmap_l2_pindex(va);
6831 if (!ADDR_IS_KERNEL(va)) {
6832 ml3->ref_count = NL3PG;
6833 pmap_resident_count_inc(pmap, 1);
6836 l3phys = VM_PAGE_TO_PHYS(ml3);
6837 l3 = (pt_entry_t *)PHYS_TO_DMAP(l3phys);
6838 newl3 = (oldl2 & ~ATTR_DESCR_MASK) | L3_PAGE;
6839 KASSERT((oldl2 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) !=
6840 (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM),
6841 ("pmap_demote_l2: L2 entry is writeable but not dirty"));
6844 * If the page table page is not leftover from an earlier promotion,
6845 * or the mapping attributes have changed, (re)initialize the L3 table.
6847 * When pmap_update_entry() clears the old L2 mapping, it (indirectly)
6848 * performs a dsb(). That dsb() ensures that the stores for filling
6849 * "l3" are visible before "l3" is added to the page table.
6851 if (ml3->valid == 0 || (l3[0] & ATTR_MASK) != (newl3 & ATTR_MASK))
6852 pmap_fill_l3(l3, newl3);
6855 * Map the temporary page so we don't lose access to the l2 table.
6858 pmap_kenter(tmpl2, PAGE_SIZE,
6859 DMAP_TO_PHYS((vm_offset_t)l2) & ~L3_OFFSET,
6860 VM_MEMATTR_WRITE_BACK);
6861 l2 = (pt_entry_t *)(tmpl2 + ((vm_offset_t)l2 & PAGE_MASK));
6865 * The spare PV entries must be reserved prior to demoting the
6866 * mapping, that is, prior to changing the PDE. Otherwise, the state
6867 * of the L2 and the PV lists will be inconsistent, which can result
6868 * in reclaim_pv_chunk() attempting to remove a PV entry from the
6869 * wrong PV list and pmap_pv_demote_l2() failing to find the expected
6870 * PV entry for the 2MB page mapping that is being demoted.
6872 if ((oldl2 & ATTR_SW_MANAGED) != 0)
6873 reserve_pv_entries(pmap, Ln_ENTRIES - 1, lockp);
6876 * Pass PAGE_SIZE so that a single TLB invalidation is performed on
6877 * the 2MB page mapping.
6879 pmap_update_entry(pmap, l2, l3phys | L2_TABLE, va, PAGE_SIZE);
6882 * Demote the PV entry.
6884 if ((oldl2 & ATTR_SW_MANAGED) != 0)
6885 pmap_pv_demote_l2(pmap, va, oldl2 & ~ATTR_MASK, lockp);
6887 atomic_add_long(&pmap_l2_demotions, 1);
6888 CTR3(KTR_PMAP, "pmap_demote_l2: success for va %#lx"
6889 " in pmap %p %lx", va, pmap, l3[0]);
6893 pmap_kremove(tmpl2);
6894 kva_free(tmpl2, PAGE_SIZE);
6902 pmap_demote_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va)
6904 struct rwlock *lock;
6908 l3 = pmap_demote_l2_locked(pmap, l2, va, &lock);
6915 * Perform the pmap work for mincore(2). If the page is not both referenced and
6916 * modified by this pmap, returns its physical address so that the caller can
6917 * find other mappings.
6920 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
6922 pt_entry_t *pte, tpte;
6923 vm_paddr_t mask, pa;
6927 PMAP_ASSERT_STAGE1(pmap);
6929 pte = pmap_pte(pmap, addr, &lvl);
6931 tpte = pmap_load(pte);
6944 panic("pmap_mincore: invalid level %d", lvl);
6947 managed = (tpte & ATTR_SW_MANAGED) != 0;
6948 val = MINCORE_INCORE;
6950 val |= MINCORE_PSIND(3 - lvl);
6951 if ((managed && pmap_pte_dirty(pmap, tpte)) || (!managed &&
6952 (tpte & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP(ATTR_S1_AP_RW)))
6953 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
6954 if ((tpte & ATTR_AF) == ATTR_AF)
6955 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
6957 pa = (tpte & ~ATTR_MASK) | (addr & mask);
6963 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
6964 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) && managed) {
6972 * Garbage collect every ASID that is neither active on a processor nor
6976 pmap_reset_asid_set(pmap_t pmap)
6979 int asid, cpuid, epoch;
6980 struct asid_set *set;
6981 enum pmap_stage stage;
6983 set = pmap->pm_asid_set;
6984 stage = pmap->pm_stage;
6986 set = pmap->pm_asid_set;
6987 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
6988 mtx_assert(&set->asid_set_mutex, MA_OWNED);
6991 * Ensure that the store to asid_epoch is globally visible before the
6992 * loads from pc_curpmap are performed.
6994 epoch = set->asid_epoch + 1;
6995 if (epoch == INT_MAX)
6997 set->asid_epoch = epoch;
6999 if (stage == PM_STAGE1) {
7000 __asm __volatile("tlbi vmalle1is");
7002 KASSERT(pmap_clean_stage2_tlbi != NULL,
7003 ("%s: Unset stage 2 tlb invalidation callback\n",
7005 pmap_clean_stage2_tlbi();
7008 bit_nclear(set->asid_set, ASID_FIRST_AVAILABLE,
7009 set->asid_set_size - 1);
7010 CPU_FOREACH(cpuid) {
7011 if (cpuid == curcpu)
7013 if (stage == PM_STAGE1) {
7014 curpmap = pcpu_find(cpuid)->pc_curpmap;
7015 PMAP_ASSERT_STAGE1(pmap);
7017 curpmap = pcpu_find(cpuid)->pc_curvmpmap;
7018 if (curpmap == NULL)
7020 PMAP_ASSERT_STAGE2(pmap);
7022 KASSERT(curpmap->pm_asid_set == set, ("Incorrect set"));
7023 asid = COOKIE_TO_ASID(curpmap->pm_cookie);
7026 bit_set(set->asid_set, asid);
7027 curpmap->pm_cookie = COOKIE_FROM(asid, epoch);
7032 * Allocate a new ASID for the specified pmap.
7035 pmap_alloc_asid(pmap_t pmap)
7037 struct asid_set *set;
7040 set = pmap->pm_asid_set;
7041 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
7043 mtx_lock_spin(&set->asid_set_mutex);
7046 * While this processor was waiting to acquire the asid set mutex,
7047 * pmap_reset_asid_set() running on another processor might have
7048 * updated this pmap's cookie to the current epoch. In which case, we
7049 * don't need to allocate a new ASID.
7051 if (COOKIE_TO_EPOCH(pmap->pm_cookie) == set->asid_epoch)
7054 bit_ffc_at(set->asid_set, set->asid_next, set->asid_set_size,
7056 if (new_asid == -1) {
7057 bit_ffc_at(set->asid_set, ASID_FIRST_AVAILABLE,
7058 set->asid_next, &new_asid);
7059 if (new_asid == -1) {
7060 pmap_reset_asid_set(pmap);
7061 bit_ffc_at(set->asid_set, ASID_FIRST_AVAILABLE,
7062 set->asid_set_size, &new_asid);
7063 KASSERT(new_asid != -1, ("ASID allocation failure"));
7066 bit_set(set->asid_set, new_asid);
7067 set->asid_next = new_asid + 1;
7068 pmap->pm_cookie = COOKIE_FROM(new_asid, set->asid_epoch);
7070 mtx_unlock_spin(&set->asid_set_mutex);
7073 static uint64_t __read_mostly ttbr_flags;
7076 * Compute the value that should be stored in ttbr0 to activate the specified
7077 * pmap. This value may change from time to time.
7080 pmap_to_ttbr0(pmap_t pmap)
7084 ttbr = pmap->pm_ttbr;
7085 ttbr |= ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
7092 pmap_set_cnp(void *arg)
7094 uint64_t ttbr0, ttbr1;
7097 cpuid = *(u_int *)arg;
7098 if (cpuid == curcpu) {
7100 * Set the flags while all CPUs are handling the
7101 * smp_rendezvous so will not call pmap_to_ttbr0. Any calls
7102 * to pmap_to_ttbr0 after this will have the CnP flag set.
7103 * The dsb after invalidating the TLB will act as a barrier
7104 * to ensure all CPUs can observe this change.
7106 ttbr_flags |= TTBR_CnP;
7109 ttbr0 = READ_SPECIALREG(ttbr0_el1);
7112 ttbr1 = READ_SPECIALREG(ttbr1_el1);
7115 /* Update ttbr{0,1}_el1 with the CnP flag */
7116 WRITE_SPECIALREG(ttbr0_el1, ttbr0);
7117 WRITE_SPECIALREG(ttbr1_el1, ttbr1);
7119 __asm __volatile("tlbi vmalle1is");
7125 * Defer enabling CnP until we have read the ID registers to know if it's
7126 * supported on all CPUs.
7129 pmap_init_cnp(void *dummy __unused)
7134 if (!get_kernel_reg(ID_AA64MMFR2_EL1, ®))
7137 if (ID_AA64MMFR2_CnP_VAL(reg) != ID_AA64MMFR2_CnP_NONE) {
7139 printf("Enabling CnP\n");
7141 smp_rendezvous(NULL, pmap_set_cnp, NULL, &cpuid);
7145 SYSINIT(pmap_init_cnp, SI_SUB_SMP, SI_ORDER_ANY, pmap_init_cnp, NULL);
7148 pmap_activate_int(pmap_t pmap)
7150 struct asid_set *set;
7153 KASSERT(PCPU_GET(curpmap) != NULL, ("no active pmap"));
7154 KASSERT(pmap != kernel_pmap, ("kernel pmap activation"));
7156 if ((pmap->pm_stage == PM_STAGE1 && pmap == PCPU_GET(curpmap)) ||
7157 (pmap->pm_stage == PM_STAGE2 && pmap == PCPU_GET(curvmpmap))) {
7159 * Handle the possibility that the old thread was preempted
7160 * after an "ic" or "tlbi" instruction but before it performed
7161 * a "dsb" instruction. If the old thread migrates to a new
7162 * processor, its completion of a "dsb" instruction on that
7163 * new processor does not guarantee that the "ic" or "tlbi"
7164 * instructions performed on the old processor have completed.
7170 set = pmap->pm_asid_set;
7171 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
7174 * Ensure that the store to curpmap is globally visible before the
7175 * load from asid_epoch is performed.
7177 if (pmap->pm_stage == PM_STAGE1)
7178 PCPU_SET(curpmap, pmap);
7180 PCPU_SET(curvmpmap, pmap);
7182 epoch = COOKIE_TO_EPOCH(pmap->pm_cookie);
7183 if (epoch >= 0 && epoch != set->asid_epoch)
7184 pmap_alloc_asid(pmap);
7186 if (pmap->pm_stage == PM_STAGE1) {
7187 set_ttbr0(pmap_to_ttbr0(pmap));
7188 if (PCPU_GET(bcast_tlbi_workaround) != 0)
7189 invalidate_local_icache();
7195 pmap_activate_vm(pmap_t pmap)
7198 PMAP_ASSERT_STAGE2(pmap);
7200 (void)pmap_activate_int(pmap);
7204 pmap_activate(struct thread *td)
7208 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7209 PMAP_ASSERT_STAGE1(pmap);
7211 (void)pmap_activate_int(pmap);
7216 * Activate the thread we are switching to.
7217 * To simplify the assembly in cpu_throw return the new threads pcb.
7220 pmap_switch(struct thread *new)
7222 pcpu_bp_harden bp_harden;
7225 /* Store the new curthread */
7226 PCPU_SET(curthread, new);
7228 /* And the new pcb */
7230 PCPU_SET(curpcb, pcb);
7233 * TODO: We may need to flush the cache here if switching
7234 * to a user process.
7237 if (pmap_activate_int(vmspace_pmap(new->td_proc->p_vmspace))) {
7239 * Stop userspace from training the branch predictor against
7240 * other processes. This will call into a CPU specific
7241 * function that clears the branch predictor state.
7243 bp_harden = PCPU_GET(bp_harden);
7244 if (bp_harden != NULL)
7252 pmap_sync_icache(pmap_t pmap, vm_offset_t va, vm_size_t sz)
7255 PMAP_ASSERT_STAGE1(pmap);
7256 KASSERT(ADDR_IS_CANONICAL(va),
7257 ("%s: Address not in canonical form: %lx", __func__, va));
7259 if (ADDR_IS_KERNEL(va)) {
7260 cpu_icache_sync_range(va, sz);
7265 /* Find the length of data in this page to flush */
7266 offset = va & PAGE_MASK;
7267 len = imin(PAGE_SIZE - offset, sz);
7270 /* Extract the physical address & find it in the DMAP */
7271 pa = pmap_extract(pmap, va);
7273 cpu_icache_sync_range(PHYS_TO_DMAP(pa), len);
7275 /* Move to the next page */
7278 /* Set the length for the next iteration */
7279 len = imin(PAGE_SIZE, sz);
7285 pmap_stage2_fault(pmap_t pmap, uint64_t esr, uint64_t far)
7288 pt_entry_t *ptep, pte;
7291 PMAP_ASSERT_STAGE2(pmap);
7294 /* Data and insn aborts use same encoding for FSC field. */
7295 dfsc = esr & ISS_DATA_DFSC_MASK;
7297 case ISS_DATA_DFSC_TF_L0:
7298 case ISS_DATA_DFSC_TF_L1:
7299 case ISS_DATA_DFSC_TF_L2:
7300 case ISS_DATA_DFSC_TF_L3:
7302 pdep = pmap_pde(pmap, far, &lvl);
7303 if (pdep == NULL || lvl != (dfsc - ISS_DATA_DFSC_TF_L1)) {
7310 ptep = pmap_l0_to_l1(pdep, far);
7313 ptep = pmap_l1_to_l2(pdep, far);
7316 ptep = pmap_l2_to_l3(pdep, far);
7319 panic("%s: Invalid pde level %d", __func__,lvl);
7323 case ISS_DATA_DFSC_AFF_L1:
7324 case ISS_DATA_DFSC_AFF_L2:
7325 case ISS_DATA_DFSC_AFF_L3:
7327 ptep = pmap_pte(pmap, far, &lvl);
7329 if (ptep != NULL && (pte = pmap_load(ptep)) != 0) {
7331 pmap_invalidate_vpipt_icache();
7334 * If accessing an executable page invalidate
7335 * the I-cache so it will be valid when we
7336 * continue execution in the guest. The D-cache
7337 * is assumed to already be clean to the Point
7340 if ((pte & ATTR_S2_XN_MASK) !=
7341 ATTR_S2_XN(ATTR_S2_XN_NONE)) {
7342 invalidate_icache();
7345 pmap_set_bits(ptep, ATTR_AF | ATTR_DESCR_VALID);
7356 pmap_fault(pmap_t pmap, uint64_t esr, uint64_t far)
7358 pt_entry_t pte, *ptep;
7365 ec = ESR_ELx_EXCEPTION(esr);
7367 case EXCP_INSN_ABORT_L:
7368 case EXCP_INSN_ABORT:
7369 case EXCP_DATA_ABORT_L:
7370 case EXCP_DATA_ABORT:
7376 if (pmap->pm_stage == PM_STAGE2)
7377 return (pmap_stage2_fault(pmap, esr, far));
7379 /* Data and insn aborts use same encoding for FSC field. */
7380 switch (esr & ISS_DATA_DFSC_MASK) {
7381 case ISS_DATA_DFSC_AFF_L1:
7382 case ISS_DATA_DFSC_AFF_L2:
7383 case ISS_DATA_DFSC_AFF_L3:
7385 ptep = pmap_pte(pmap, far, &lvl);
7387 pmap_set_bits(ptep, ATTR_AF);
7390 * XXXMJ as an optimization we could mark the entry
7391 * dirty if this is a write fault.
7396 case ISS_DATA_DFSC_PF_L1:
7397 case ISS_DATA_DFSC_PF_L2:
7398 case ISS_DATA_DFSC_PF_L3:
7399 if ((ec != EXCP_DATA_ABORT_L && ec != EXCP_DATA_ABORT) ||
7400 (esr & ISS_DATA_WnR) == 0)
7403 ptep = pmap_pte(pmap, far, &lvl);
7405 ((pte = pmap_load(ptep)) & ATTR_SW_DBM) != 0) {
7406 if ((pte & ATTR_S1_AP_RW_BIT) ==
7407 ATTR_S1_AP(ATTR_S1_AP_RO)) {
7408 pmap_clear_bits(ptep, ATTR_S1_AP_RW_BIT);
7409 pmap_s1_invalidate_page(pmap, far, true);
7415 case ISS_DATA_DFSC_TF_L0:
7416 case ISS_DATA_DFSC_TF_L1:
7417 case ISS_DATA_DFSC_TF_L2:
7418 case ISS_DATA_DFSC_TF_L3:
7420 * Retry the translation. A break-before-make sequence can
7421 * produce a transient fault.
7423 if (pmap == kernel_pmap) {
7425 * The translation fault may have occurred within a
7426 * critical section. Therefore, we must check the
7427 * address without acquiring the kernel pmap's lock.
7429 if (pmap_klookup(far, NULL))
7433 /* Ask the MMU to check the address. */
7434 intr = intr_disable();
7435 par = arm64_address_translate_s1e0r(far);
7440 * If the translation was successful, then we can
7441 * return success to the trap handler.
7443 if (PAR_SUCCESS(par))
7453 * Increase the starting virtual address of the given mapping if a
7454 * different alignment might result in more superpage mappings.
7457 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7458 vm_offset_t *addr, vm_size_t size)
7460 vm_offset_t superpage_offset;
7464 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7465 offset += ptoa(object->pg_color);
7466 superpage_offset = offset & L2_OFFSET;
7467 if (size - ((L2_SIZE - superpage_offset) & L2_OFFSET) < L2_SIZE ||
7468 (*addr & L2_OFFSET) == superpage_offset)
7470 if ((*addr & L2_OFFSET) < superpage_offset)
7471 *addr = (*addr & ~L2_OFFSET) + superpage_offset;
7473 *addr = ((*addr + L2_OFFSET) & ~L2_OFFSET) + superpage_offset;
7477 * Get the kernel virtual address of a set of physical pages. If there are
7478 * physical addresses not covered by the DMAP perform a transient mapping
7479 * that will be removed when calling pmap_unmap_io_transient.
7481 * \param page The pages the caller wishes to obtain the virtual
7482 * address on the kernel memory map.
7483 * \param vaddr On return contains the kernel virtual memory address
7484 * of the pages passed in the page parameter.
7485 * \param count Number of pages passed in.
7486 * \param can_fault TRUE if the thread using the mapped pages can take
7487 * page faults, FALSE otherwise.
7489 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7490 * finished or FALSE otherwise.
7494 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7495 boolean_t can_fault)
7498 boolean_t needs_mapping;
7499 int error __diagused, i;
7502 * Allocate any KVA space that we need, this is done in a separate
7503 * loop to prevent calling vmem_alloc while pinned.
7505 needs_mapping = FALSE;
7506 for (i = 0; i < count; i++) {
7507 paddr = VM_PAGE_TO_PHYS(page[i]);
7508 if (__predict_false(!PHYS_IN_DMAP(paddr))) {
7509 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7510 M_BESTFIT | M_WAITOK, &vaddr[i]);
7511 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7512 needs_mapping = TRUE;
7514 vaddr[i] = PHYS_TO_DMAP(paddr);
7518 /* Exit early if everything is covered by the DMAP */
7524 for (i = 0; i < count; i++) {
7525 paddr = VM_PAGE_TO_PHYS(page[i]);
7526 if (!PHYS_IN_DMAP(paddr)) {
7528 "pmap_map_io_transient: TODO: Map out of DMAP data");
7532 return (needs_mapping);
7536 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7537 boolean_t can_fault)
7544 for (i = 0; i < count; i++) {
7545 paddr = VM_PAGE_TO_PHYS(page[i]);
7546 if (!PHYS_IN_DMAP(paddr)) {
7547 panic("ARM64TODO: pmap_unmap_io_transient: Unmap data");
7553 pmap_is_valid_memattr(pmap_t pmap __unused, vm_memattr_t mode)
7556 return (mode >= VM_MEMATTR_DEVICE && mode <= VM_MEMATTR_WRITE_THROUGH);
7560 * Track a range of the kernel's virtual address space that is contiguous
7561 * in various mapping attributes.
7563 struct pmap_kernel_map_range {
7573 sysctl_kmaps_dump(struct sbuf *sb, struct pmap_kernel_map_range *range,
7579 if (eva <= range->sva)
7582 index = range->attrs & ATTR_S1_IDX_MASK;
7584 case ATTR_S1_IDX(VM_MEMATTR_DEVICE):
7587 case ATTR_S1_IDX(VM_MEMATTR_UNCACHEABLE):
7590 case ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK):
7593 case ATTR_S1_IDX(VM_MEMATTR_WRITE_THROUGH):
7598 "%s: unknown memory type %x for range 0x%016lx-0x%016lx\n",
7599 __func__, index, range->sva, eva);
7604 sbuf_printf(sb, "0x%016lx-0x%016lx r%c%c%c%c %3s %d %d %d %d\n",
7606 (range->attrs & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP_RW ? 'w' : '-',
7607 (range->attrs & ATTR_S1_PXN) != 0 ? '-' : 'x',
7608 (range->attrs & ATTR_S1_UXN) != 0 ? '-' : 'X',
7609 (range->attrs & ATTR_S1_AP(ATTR_S1_AP_USER)) != 0 ? 'u' : 's',
7610 mode, range->l1blocks, range->l2blocks, range->l3contig,
7613 /* Reset to sentinel value. */
7614 range->sva = 0xfffffffffffffffful;
7618 * Determine whether the attributes specified by a page table entry match those
7619 * being tracked by the current range.
7622 sysctl_kmaps_match(struct pmap_kernel_map_range *range, pt_entry_t attrs)
7625 return (range->attrs == attrs);
7629 sysctl_kmaps_reinit(struct pmap_kernel_map_range *range, vm_offset_t va,
7633 memset(range, 0, sizeof(*range));
7635 range->attrs = attrs;
7638 /* Get the block/page attributes that correspond to the table attributes */
7640 sysctl_kmaps_table_attrs(pd_entry_t table)
7645 if ((table & TATTR_UXN_TABLE) != 0)
7646 attrs |= ATTR_S1_UXN;
7647 if ((table & TATTR_PXN_TABLE) != 0)
7648 attrs |= ATTR_S1_PXN;
7649 if ((table & TATTR_AP_TABLE_RO) != 0)
7650 attrs |= ATTR_S1_AP(ATTR_S1_AP_RO);
7655 /* Read the block/page attributes we care about */
7657 sysctl_kmaps_block_attrs(pt_entry_t block)
7659 return (block & (ATTR_S1_AP_MASK | ATTR_S1_XN | ATTR_S1_IDX_MASK));
7663 * Given a leaf PTE, derive the mapping's attributes. If they do not match
7664 * those of the current run, dump the address range and its attributes, and
7668 sysctl_kmaps_check(struct sbuf *sb, struct pmap_kernel_map_range *range,
7669 vm_offset_t va, pd_entry_t l0e, pd_entry_t l1e, pd_entry_t l2e,
7674 attrs = sysctl_kmaps_table_attrs(l0e);
7676 if ((l1e & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
7677 attrs |= sysctl_kmaps_block_attrs(l1e);
7680 attrs |= sysctl_kmaps_table_attrs(l1e);
7682 if ((l2e & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
7683 attrs |= sysctl_kmaps_block_attrs(l2e);
7686 attrs |= sysctl_kmaps_table_attrs(l2e);
7687 attrs |= sysctl_kmaps_block_attrs(l3e);
7690 if (range->sva > va || !sysctl_kmaps_match(range, attrs)) {
7691 sysctl_kmaps_dump(sb, range, va);
7692 sysctl_kmaps_reinit(range, va, attrs);
7697 sysctl_kmaps(SYSCTL_HANDLER_ARGS)
7699 struct pmap_kernel_map_range range;
7700 struct sbuf sbuf, *sb;
7701 pd_entry_t l0e, *l1, l1e, *l2, l2e;
7702 pt_entry_t *l3, l3e;
7705 int error, i, j, k, l;
7707 error = sysctl_wire_old_buffer(req, 0);
7711 sbuf_new_for_sysctl(sb, NULL, PAGE_SIZE, req);
7713 /* Sentinel value. */
7714 range.sva = 0xfffffffffffffffful;
7717 * Iterate over the kernel page tables without holding the kernel pmap
7718 * lock. Kernel page table pages are never freed, so at worst we will
7719 * observe inconsistencies in the output.
7721 for (sva = 0xffff000000000000ul, i = pmap_l0_index(sva); i < Ln_ENTRIES;
7723 if (i == pmap_l0_index(DMAP_MIN_ADDRESS))
7724 sbuf_printf(sb, "\nDirect map:\n");
7725 else if (i == pmap_l0_index(VM_MIN_KERNEL_ADDRESS))
7726 sbuf_printf(sb, "\nKernel map:\n");
7728 l0e = kernel_pmap->pm_l0[i];
7729 if ((l0e & ATTR_DESCR_VALID) == 0) {
7730 sysctl_kmaps_dump(sb, &range, sva);
7734 pa = l0e & ~ATTR_MASK;
7735 l1 = (pd_entry_t *)PHYS_TO_DMAP(pa);
7737 for (j = pmap_l1_index(sva); j < Ln_ENTRIES; j++) {
7739 if ((l1e & ATTR_DESCR_VALID) == 0) {
7740 sysctl_kmaps_dump(sb, &range, sva);
7744 if ((l1e & ATTR_DESCR_MASK) == L1_BLOCK) {
7745 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
7746 sysctl_kmaps_check(sb, &range, sva, l0e, l1e,
7752 pa = l1e & ~ATTR_MASK;
7753 l2 = (pd_entry_t *)PHYS_TO_DMAP(pa);
7755 for (k = pmap_l2_index(sva); k < Ln_ENTRIES; k++) {
7757 if ((l2e & ATTR_DESCR_VALID) == 0) {
7758 sysctl_kmaps_dump(sb, &range, sva);
7762 if ((l2e & ATTR_DESCR_MASK) == L2_BLOCK) {
7763 sysctl_kmaps_check(sb, &range, sva,
7769 pa = l2e & ~ATTR_MASK;
7770 l3 = (pt_entry_t *)PHYS_TO_DMAP(pa);
7772 for (l = pmap_l3_index(sva); l < Ln_ENTRIES;
7773 l++, sva += L3_SIZE) {
7775 if ((l3e & ATTR_DESCR_VALID) == 0) {
7776 sysctl_kmaps_dump(sb, &range,
7780 sysctl_kmaps_check(sb, &range, sva,
7781 l0e, l1e, l2e, l3e);
7782 if ((l3e & ATTR_CONTIGUOUS) != 0)
7783 range.l3contig += l % 16 == 0 ?
7792 error = sbuf_finish(sb);
7796 SYSCTL_OID(_vm_pmap, OID_AUTO, kernel_maps,
7797 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
7798 NULL, 0, sysctl_kmaps, "A",
7799 "Dump kernel address layout");