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);
407 * A pmap's cookie encodes an ASID and epoch number. Cookies for reserved
408 * ASIDs have a negative epoch number, specifically, INT_MIN. Cookies for
409 * dynamically allocated ASIDs have a non-negative epoch number.
411 * An invalid ASID is represented by -1.
413 * There are two special-case cookie values: (1) COOKIE_FROM(-1, INT_MIN),
414 * which indicates that an ASID should never be allocated to the pmap, and
415 * (2) COOKIE_FROM(-1, INT_MAX), which indicates that an ASID should be
416 * allocated when the pmap is next activated.
418 #define COOKIE_FROM(asid, epoch) ((long)((u_int)(asid) | \
419 ((u_long)(epoch) << 32)))
420 #define COOKIE_TO_ASID(cookie) ((int)(cookie))
421 #define COOKIE_TO_EPOCH(cookie) ((int)((u_long)(cookie) >> 32))
423 #define TLBI_VA_SHIFT 12
424 #define TLBI_VA_MASK ((1ul << 44) - 1)
425 #define TLBI_VA(addr) (((addr) >> TLBI_VA_SHIFT) & TLBI_VA_MASK)
426 #define TLBI_VA_L3_INCR (L3_SIZE >> TLBI_VA_SHIFT)
428 static int superpages_enabled = 1;
429 SYSCTL_INT(_vm_pmap, OID_AUTO, superpages_enabled,
430 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &superpages_enabled, 0,
431 "Are large page mappings enabled?");
434 * Internal flags for pmap_enter()'s helper functions.
436 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
437 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
439 TAILQ_HEAD(pv_chunklist, pv_chunk);
441 static void free_pv_chunk(struct pv_chunk *pc);
442 static void free_pv_chunk_batch(struct pv_chunklist *batch);
443 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
444 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
445 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
446 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
447 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
450 static void pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte);
451 static bool pmap_activate_int(pmap_t pmap);
452 static void pmap_alloc_asid(pmap_t pmap);
453 static int pmap_change_props_locked(vm_offset_t va, vm_size_t size,
454 vm_prot_t prot, int mode, bool skip_unmapped);
455 static pt_entry_t *pmap_demote_l1(pmap_t pmap, pt_entry_t *l1, vm_offset_t va);
456 static pt_entry_t *pmap_demote_l2_locked(pmap_t pmap, pt_entry_t *l2,
457 vm_offset_t va, struct rwlock **lockp);
458 static pt_entry_t *pmap_demote_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va);
459 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
460 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
461 static int pmap_enter_l2(pmap_t pmap, vm_offset_t va, pd_entry_t new_l2,
462 u_int flags, vm_page_t m, struct rwlock **lockp);
463 static int pmap_remove_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva,
464 pd_entry_t l1e, struct spglist *free, struct rwlock **lockp);
465 static int pmap_remove_l3(pmap_t pmap, pt_entry_t *l3, vm_offset_t sva,
466 pd_entry_t l2e, struct spglist *free, struct rwlock **lockp);
467 static void pmap_reset_asid_set(pmap_t pmap);
468 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
469 vm_page_t m, struct rwlock **lockp);
471 static vm_page_t _pmap_alloc_l3(pmap_t pmap, vm_pindex_t ptepindex,
472 struct rwlock **lockp);
474 static void _pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m,
475 struct spglist *free);
476 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
477 static __inline vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
480 * These load the old table data and store the new value.
481 * They need to be atomic as the System MMU may write to the table at
482 * the same time as the CPU.
484 #define pmap_clear(table) atomic_store_64(table, 0)
485 #define pmap_clear_bits(table, bits) atomic_clear_64(table, bits)
486 #define pmap_load(table) (*table)
487 #define pmap_load_clear(table) atomic_swap_64(table, 0)
488 #define pmap_load_store(table, entry) atomic_swap_64(table, entry)
489 #define pmap_set_bits(table, bits) atomic_set_64(table, bits)
490 #define pmap_store(table, entry) atomic_store_64(table, entry)
492 /********************/
493 /* Inline functions */
494 /********************/
497 pagecopy(void *s, void *d)
500 memcpy(d, s, PAGE_SIZE);
503 static __inline pd_entry_t *
504 pmap_l0(pmap_t pmap, vm_offset_t va)
507 return (&pmap->pm_l0[pmap_l0_index(va)]);
510 static __inline pd_entry_t *
511 pmap_l0_to_l1(pd_entry_t *l0, vm_offset_t va)
515 l1 = (pd_entry_t *)PHYS_TO_DMAP(pmap_load(l0) & ~ATTR_MASK);
516 return (&l1[pmap_l1_index(va)]);
519 static __inline pd_entry_t *
520 pmap_l1(pmap_t pmap, vm_offset_t va)
524 l0 = pmap_l0(pmap, va);
525 if ((pmap_load(l0) & ATTR_DESCR_MASK) != L0_TABLE)
528 return (pmap_l0_to_l1(l0, va));
531 static __inline pd_entry_t *
532 pmap_l1_to_l2(pd_entry_t *l1p, vm_offset_t va)
538 KASSERT(ADDR_IS_CANONICAL(va),
539 ("%s: Address not in canonical form: %lx", __func__, va));
541 * The valid bit may be clear if pmap_update_entry() is concurrently
542 * modifying the entry, so for KVA only the entry type may be checked.
544 KASSERT(ADDR_IS_KERNEL(va) || (l1 & ATTR_DESCR_VALID) != 0,
545 ("%s: L1 entry %#lx for %#lx is invalid", __func__, l1, va));
546 KASSERT((l1 & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_TABLE,
547 ("%s: L1 entry %#lx for %#lx is a leaf", __func__, l1, va));
548 l2p = (pd_entry_t *)PHYS_TO_DMAP(l1 & ~ATTR_MASK);
549 return (&l2p[pmap_l2_index(va)]);
552 static __inline pd_entry_t *
553 pmap_l2(pmap_t pmap, vm_offset_t va)
557 l1 = pmap_l1(pmap, va);
558 if ((pmap_load(l1) & ATTR_DESCR_MASK) != L1_TABLE)
561 return (pmap_l1_to_l2(l1, va));
564 static __inline pt_entry_t *
565 pmap_l2_to_l3(pd_entry_t *l2p, vm_offset_t va)
572 KASSERT(ADDR_IS_CANONICAL(va),
573 ("%s: Address not in canonical form: %lx", __func__, va));
575 * The valid bit may be clear if pmap_update_entry() is concurrently
576 * modifying the entry, so for KVA only the entry type may be checked.
578 KASSERT(ADDR_IS_KERNEL(va) || (l2 & ATTR_DESCR_VALID) != 0,
579 ("%s: L2 entry %#lx for %#lx is invalid", __func__, l2, va));
580 KASSERT((l2 & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_TABLE,
581 ("%s: L2 entry %#lx for %#lx is a leaf", __func__, l2, va));
582 l3p = (pt_entry_t *)PHYS_TO_DMAP(l2 & ~ATTR_MASK);
583 return (&l3p[pmap_l3_index(va)]);
587 * Returns the lowest valid pde for a given virtual address.
588 * The next level may or may not point to a valid page or block.
590 static __inline pd_entry_t *
591 pmap_pde(pmap_t pmap, vm_offset_t va, int *level)
593 pd_entry_t *l0, *l1, *l2, desc;
595 l0 = pmap_l0(pmap, va);
596 desc = pmap_load(l0) & ATTR_DESCR_MASK;
597 if (desc != L0_TABLE) {
602 l1 = pmap_l0_to_l1(l0, va);
603 desc = pmap_load(l1) & ATTR_DESCR_MASK;
604 if (desc != L1_TABLE) {
609 l2 = pmap_l1_to_l2(l1, va);
610 desc = pmap_load(l2) & ATTR_DESCR_MASK;
611 if (desc != L2_TABLE) {
621 * Returns the lowest valid pte block or table entry for a given virtual
622 * address. If there are no valid entries return NULL and set the level to
623 * the first invalid level.
625 static __inline pt_entry_t *
626 pmap_pte(pmap_t pmap, vm_offset_t va, int *level)
628 pd_entry_t *l1, *l2, desc;
631 l1 = pmap_l1(pmap, va);
636 desc = pmap_load(l1) & ATTR_DESCR_MASK;
637 if (desc == L1_BLOCK) {
638 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
643 if (desc != L1_TABLE) {
648 l2 = pmap_l1_to_l2(l1, va);
649 desc = pmap_load(l2) & ATTR_DESCR_MASK;
650 if (desc == L2_BLOCK) {
655 if (desc != L2_TABLE) {
661 l3 = pmap_l2_to_l3(l2, va);
662 if ((pmap_load(l3) & ATTR_DESCR_MASK) != L3_PAGE)
669 * If the given pmap has an L{1,2}_BLOCK or L3_PAGE entry at the specified
670 * level that maps the specified virtual address, then a pointer to that entry
671 * is returned. Otherwise, NULL is returned, unless INVARIANTS are enabled
672 * and a diagnostic message is provided, in which case this function panics.
674 static __always_inline pt_entry_t *
675 pmap_pte_exists(pmap_t pmap, vm_offset_t va, int level, const char *diag)
677 pd_entry_t *l0p, *l1p, *l2p;
678 pt_entry_t desc, *l3p;
679 int walk_level __diagused;
681 KASSERT(level >= 0 && level < 4,
682 ("%s: %s passed an out-of-range level (%d)", __func__, diag,
684 l0p = pmap_l0(pmap, va);
685 desc = pmap_load(l0p) & ATTR_DESCR_MASK;
686 if (desc == L0_TABLE && level > 0) {
687 l1p = pmap_l0_to_l1(l0p, va);
688 desc = pmap_load(l1p) & ATTR_DESCR_MASK;
689 if (desc == L1_BLOCK && level == 1) {
690 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
693 if (desc == L1_TABLE && level > 1) {
694 l2p = pmap_l1_to_l2(l1p, va);
695 desc = pmap_load(l2p) & ATTR_DESCR_MASK;
696 if (desc == L2_BLOCK && level == 2)
698 else if (desc == L2_TABLE && level > 2) {
699 l3p = pmap_l2_to_l3(l2p, va);
700 desc = pmap_load(l3p) & ATTR_DESCR_MASK;
701 if (desc == L3_PAGE && level == 3)
711 KASSERT(diag == NULL,
712 ("%s: va %#lx not mapped at level %d, desc %ld at level %d",
713 diag, va, level, desc, walk_level));
718 pmap_ps_enabled(pmap_t pmap)
721 * Promotion requires a hypervisor call when the kernel is running
722 * in EL1. To stop this disable superpage support on non-stage 1
725 if (pmap->pm_stage != PM_STAGE1)
728 return (superpages_enabled != 0);
732 pmap_get_tables(pmap_t pmap, vm_offset_t va, pd_entry_t **l0, pd_entry_t **l1,
733 pd_entry_t **l2, pt_entry_t **l3)
735 pd_entry_t *l0p, *l1p, *l2p;
737 if (pmap->pm_l0 == NULL)
740 l0p = pmap_l0(pmap, va);
743 if ((pmap_load(l0p) & ATTR_DESCR_MASK) != L0_TABLE)
746 l1p = pmap_l0_to_l1(l0p, va);
749 if ((pmap_load(l1p) & ATTR_DESCR_MASK) == L1_BLOCK) {
750 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
756 if ((pmap_load(l1p) & ATTR_DESCR_MASK) != L1_TABLE)
759 l2p = pmap_l1_to_l2(l1p, va);
762 if ((pmap_load(l2p) & ATTR_DESCR_MASK) == L2_BLOCK) {
767 if ((pmap_load(l2p) & ATTR_DESCR_MASK) != L2_TABLE)
770 *l3 = pmap_l2_to_l3(l2p, va);
776 pmap_l3_valid(pt_entry_t l3)
779 return ((l3 & ATTR_DESCR_MASK) == L3_PAGE);
782 CTASSERT(L1_BLOCK == L2_BLOCK);
785 pmap_pte_memattr(pmap_t pmap, vm_memattr_t memattr)
789 if (pmap->pm_stage == PM_STAGE1) {
790 val = ATTR_S1_IDX(memattr);
791 if (memattr == VM_MEMATTR_DEVICE)
799 case VM_MEMATTR_DEVICE:
800 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_DEVICE_nGnRnE) |
801 ATTR_S2_XN(ATTR_S2_XN_ALL));
802 case VM_MEMATTR_UNCACHEABLE:
803 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_NC));
804 case VM_MEMATTR_WRITE_BACK:
805 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_WB));
806 case VM_MEMATTR_WRITE_THROUGH:
807 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_WT));
809 panic("%s: invalid memory attribute %x", __func__, memattr);
814 pmap_pte_prot(pmap_t pmap, vm_prot_t prot)
819 if (pmap->pm_stage == PM_STAGE1) {
820 if ((prot & VM_PROT_EXECUTE) == 0)
822 if ((prot & VM_PROT_WRITE) == 0)
823 val |= ATTR_S1_AP(ATTR_S1_AP_RO);
825 if ((prot & VM_PROT_WRITE) != 0)
826 val |= ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
827 if ((prot & VM_PROT_READ) != 0)
828 val |= ATTR_S2_S2AP(ATTR_S2_S2AP_READ);
829 if ((prot & VM_PROT_EXECUTE) == 0)
830 val |= ATTR_S2_XN(ATTR_S2_XN_ALL);
837 * Checks if the PTE is dirty.
840 pmap_pte_dirty(pmap_t pmap, pt_entry_t pte)
843 KASSERT((pte & ATTR_SW_MANAGED) != 0, ("pte %#lx is unmanaged", pte));
845 if (pmap->pm_stage == PM_STAGE1) {
846 KASSERT((pte & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) != 0,
847 ("pte %#lx is writeable and missing ATTR_SW_DBM", pte));
849 return ((pte & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
850 (ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_SW_DBM));
853 return ((pte & ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE)) ==
854 ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE));
858 pmap_resident_count_inc(pmap_t pmap, int count)
861 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
862 pmap->pm_stats.resident_count += count;
866 pmap_resident_count_dec(pmap_t pmap, int count)
869 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
870 KASSERT(pmap->pm_stats.resident_count >= count,
871 ("pmap %p resident count underflow %ld %d", pmap,
872 pmap->pm_stats.resident_count, count));
873 pmap->pm_stats.resident_count -= count;
877 pmap_early_vtophys(vm_offset_t va)
881 pa_page = arm64_address_translate_s1e1r(va) & PAR_PA_MASK;
882 return (pa_page | (va & PAR_LOW_MASK));
885 /* State of the bootstrapped DMAP page tables */
886 struct pmap_bootstrap_state {
890 vm_offset_t freemempos;
893 pt_entry_t table_attrs;
900 /* The bootstrap state */
901 static struct pmap_bootstrap_state bs_state = {
905 .table_attrs = TATTR_PXN_TABLE,
906 .l0_slot = L0_ENTRIES,
907 .l1_slot = Ln_ENTRIES,
908 .l2_slot = Ln_ENTRIES,
913 pmap_bootstrap_l0_table(struct pmap_bootstrap_state *state)
919 /* Link the level 0 table to a level 1 table */
920 l0_slot = pmap_l0_index(state->va);
921 if (l0_slot != state->l0_slot) {
923 * Make sure we move from a low address to high address
924 * before the DMAP region is ready. This ensures we never
925 * modify an existing mapping until we can map from a
926 * physical address to a virtual address.
928 MPASS(state->l0_slot < l0_slot ||
929 state->l0_slot == L0_ENTRIES ||
932 /* Reset lower levels */
935 state->l1_slot = Ln_ENTRIES;
936 state->l2_slot = Ln_ENTRIES;
938 /* Check the existing L0 entry */
939 state->l0_slot = l0_slot;
940 if (state->dmap_valid) {
941 l0e = pagetable_l0_ttbr1[l0_slot];
942 if ((l0e & ATTR_DESCR_VALID) != 0) {
943 MPASS((l0e & ATTR_DESCR_MASK) == L0_TABLE);
944 l1_pa = l0e & ~ATTR_MASK;
945 state->l1 = (pt_entry_t *)PHYS_TO_DMAP(l1_pa);
950 /* Create a new L0 table entry */
951 state->l1 = (pt_entry_t *)state->freemempos;
952 memset(state->l1, 0, PAGE_SIZE);
953 state->freemempos += PAGE_SIZE;
955 l1_pa = pmap_early_vtophys((vm_offset_t)state->l1);
956 MPASS((l1_pa & Ln_TABLE_MASK) == 0);
957 MPASS(pagetable_l0_ttbr1[l0_slot] == 0);
958 pmap_store(&pagetable_l0_ttbr1[l0_slot], l1_pa |
959 TATTR_UXN_TABLE | TATTR_AP_TABLE_NO_EL0 | L0_TABLE);
961 KASSERT(state->l1 != NULL, ("%s: NULL l1", __func__));
965 pmap_bootstrap_l1_table(struct pmap_bootstrap_state *state)
971 /* Make sure there is a valid L0 -> L1 table */
972 pmap_bootstrap_l0_table(state);
974 /* Link the level 1 table to a level 2 table */
975 l1_slot = pmap_l1_index(state->va);
976 if (l1_slot != state->l1_slot) {
977 /* See pmap_bootstrap_l0_table for a description */
978 MPASS(state->l1_slot < l1_slot ||
979 state->l1_slot == Ln_ENTRIES ||
982 /* Reset lower levels */
984 state->l2_slot = Ln_ENTRIES;
986 /* Check the existing L1 entry */
987 state->l1_slot = l1_slot;
988 if (state->dmap_valid) {
989 l1e = state->l1[l1_slot];
990 if ((l1e & ATTR_DESCR_VALID) != 0) {
991 MPASS((l1e & ATTR_DESCR_MASK) == L1_TABLE);
992 l2_pa = l1e & ~ATTR_MASK;
993 state->l2 = (pt_entry_t *)PHYS_TO_DMAP(l2_pa);
998 /* Create a new L1 table entry */
999 state->l2 = (pt_entry_t *)state->freemempos;
1000 memset(state->l2, 0, PAGE_SIZE);
1001 state->freemempos += PAGE_SIZE;
1003 l2_pa = pmap_early_vtophys((vm_offset_t)state->l2);
1004 MPASS((l2_pa & Ln_TABLE_MASK) == 0);
1005 MPASS(state->l1[l1_slot] == 0);
1006 pmap_store(&state->l1[l1_slot], l2_pa | state->table_attrs |
1009 KASSERT(state->l2 != NULL, ("%s: NULL l2", __func__));
1013 pmap_bootstrap_l2_table(struct pmap_bootstrap_state *state)
1019 /* Make sure there is a valid L1 -> L2 table */
1020 pmap_bootstrap_l1_table(state);
1022 /* Link the level 2 table to a level 3 table */
1023 l2_slot = pmap_l2_index(state->va);
1024 if (l2_slot != state->l2_slot) {
1025 /* See pmap_bootstrap_l0_table for a description */
1026 MPASS(state->l2_slot < l2_slot ||
1027 state->l2_slot == Ln_ENTRIES ||
1030 /* Check the existing L2 entry */
1031 state->l2_slot = l2_slot;
1032 if (state->dmap_valid) {
1033 l2e = state->l2[l2_slot];
1034 if ((l2e & ATTR_DESCR_VALID) != 0) {
1035 MPASS((l2e & ATTR_DESCR_MASK) == L2_TABLE);
1036 l3_pa = l2e & ~ATTR_MASK;
1037 state->l3 = (pt_entry_t *)PHYS_TO_DMAP(l3_pa);
1042 /* Create a new L2 table entry */
1043 state->l3 = (pt_entry_t *)state->freemempos;
1044 memset(state->l3, 0, PAGE_SIZE);
1045 state->freemempos += PAGE_SIZE;
1047 l3_pa = pmap_early_vtophys((vm_offset_t)state->l3);
1048 MPASS((l3_pa & Ln_TABLE_MASK) == 0);
1049 MPASS(state->l2[l2_slot] == 0);
1050 pmap_store(&state->l2[l2_slot], l3_pa | state->table_attrs |
1053 KASSERT(state->l3 != NULL, ("%s: NULL l3", __func__));
1057 pmap_bootstrap_l2_block(struct pmap_bootstrap_state *state, int i)
1062 if ((physmap[i + 1] - state->pa) < L2_SIZE)
1065 /* Make sure there is a valid L1 table */
1066 pmap_bootstrap_l1_table(state);
1068 MPASS((state->va & L2_OFFSET) == 0);
1070 state->va < DMAP_MAX_ADDRESS &&
1071 (physmap[i + 1] - state->pa) >= L2_SIZE;
1072 state->va += L2_SIZE, state->pa += L2_SIZE) {
1074 * Stop if we are about to walk off the end of what the
1075 * current L1 slot can address.
1077 if (!first && (state->pa & L1_OFFSET) == 0)
1081 l2_slot = pmap_l2_index(state->va);
1082 MPASS((state->pa & L2_OFFSET) == 0);
1083 MPASS(state->l2[l2_slot] == 0);
1084 pmap_store(&state->l2[l2_slot], state->pa | ATTR_DEFAULT |
1085 ATTR_S1_XN | ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) |
1088 MPASS(state->va == (state->pa - dmap_phys_base + DMAP_MIN_ADDRESS));
1092 pmap_bootstrap_l3_page(struct pmap_bootstrap_state *state, int i)
1097 if ((physmap[i + 1] - state->pa) < L3_SIZE)
1100 /* Make sure there is a valid L2 table */
1101 pmap_bootstrap_l2_table(state);
1103 MPASS((state->va & L3_OFFSET) == 0);
1105 state->va < DMAP_MAX_ADDRESS &&
1106 (physmap[i + 1] - state->pa) >= L3_SIZE;
1107 state->va += L3_SIZE, state->pa += L3_SIZE) {
1109 * Stop if we are about to walk off the end of what the
1110 * current L2 slot can address.
1112 if (!first && (state->pa & L2_OFFSET) == 0)
1116 l3_slot = pmap_l3_index(state->va);
1117 MPASS((state->pa & L3_OFFSET) == 0);
1118 MPASS(state->l3[l3_slot] == 0);
1119 pmap_store(&state->l3[l3_slot], state->pa | ATTR_DEFAULT |
1120 ATTR_S1_XN | ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) |
1123 MPASS(state->va == (state->pa - dmap_phys_base + DMAP_MIN_ADDRESS));
1127 pmap_bootstrap_dmap(vm_paddr_t min_pa)
1131 dmap_phys_base = min_pa & ~L1_OFFSET;
1135 for (i = 0; i < (physmap_idx * 2); i += 2) {
1136 bs_state.pa = physmap[i] & ~L3_OFFSET;
1137 bs_state.va = bs_state.pa - dmap_phys_base + DMAP_MIN_ADDRESS;
1139 /* Create L3 mappings at the start of the region */
1140 if ((bs_state.pa & L2_OFFSET) != 0)
1141 pmap_bootstrap_l3_page(&bs_state, i);
1142 MPASS(bs_state.pa <= physmap[i + 1]);
1144 if (L1_BLOCKS_SUPPORTED) {
1145 /* Create L2 mappings at the start of the region */
1146 if ((bs_state.pa & L1_OFFSET) != 0)
1147 pmap_bootstrap_l2_block(&bs_state, i);
1148 MPASS(bs_state.pa <= physmap[i + 1]);
1150 /* Create the main L1 block mappings */
1151 for (; bs_state.va < DMAP_MAX_ADDRESS &&
1152 (physmap[i + 1] - bs_state.pa) >= L1_SIZE;
1153 bs_state.va += L1_SIZE, bs_state.pa += L1_SIZE) {
1154 /* Make sure there is a valid L1 table */
1155 pmap_bootstrap_l0_table(&bs_state);
1156 MPASS((bs_state.pa & L1_OFFSET) == 0);
1158 &bs_state.l1[pmap_l1_index(bs_state.va)],
1159 bs_state.pa | ATTR_DEFAULT | ATTR_S1_XN |
1160 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) |
1163 MPASS(bs_state.pa <= physmap[i + 1]);
1165 /* Create L2 mappings at the end of the region */
1166 pmap_bootstrap_l2_block(&bs_state, i);
1168 while (bs_state.va < DMAP_MAX_ADDRESS &&
1169 (physmap[i + 1] - bs_state.pa) >= L2_SIZE) {
1170 pmap_bootstrap_l2_block(&bs_state, i);
1173 MPASS(bs_state.pa <= physmap[i + 1]);
1175 /* Create L3 mappings at the end of the region */
1176 pmap_bootstrap_l3_page(&bs_state, i);
1177 MPASS(bs_state.pa == physmap[i + 1]);
1179 if (bs_state.pa > dmap_phys_max) {
1180 dmap_phys_max = bs_state.pa;
1181 dmap_max_addr = bs_state.va;
1189 pmap_bootstrap_l2(vm_offset_t va)
1191 KASSERT((va & L1_OFFSET) == 0, ("Invalid virtual address"));
1193 /* Leave bs_state.pa as it's only needed to bootstrap blocks and pages*/
1196 for (; bs_state.va < VM_MAX_KERNEL_ADDRESS; bs_state.va += L1_SIZE)
1197 pmap_bootstrap_l1_table(&bs_state);
1201 pmap_bootstrap_l3(vm_offset_t va)
1203 KASSERT((va & L2_OFFSET) == 0, ("Invalid virtual address"));
1205 /* Leave bs_state.pa as it's only needed to bootstrap blocks and pages*/
1208 for (; bs_state.va < VM_MAX_KERNEL_ADDRESS; bs_state.va += L2_SIZE)
1209 pmap_bootstrap_l2_table(&bs_state);
1213 * Bootstrap the system enough to run with virtual memory.
1216 pmap_bootstrap(vm_paddr_t kernstart, vm_size_t kernlen)
1218 vm_offset_t dpcpu, msgbufpv;
1219 vm_paddr_t start_pa, pa, min_pa;
1220 uint64_t kern_delta;
1223 /* Verify that the ASID is set through TTBR0. */
1224 KASSERT((READ_SPECIALREG(tcr_el1) & TCR_A1) == 0,
1225 ("pmap_bootstrap: TCR_EL1.A1 != 0"));
1227 kern_delta = KERNBASE - kernstart;
1229 printf("pmap_bootstrap %lx %lx\n", kernstart, kernlen);
1230 printf("%lx\n", (KERNBASE >> L1_SHIFT) & Ln_ADDR_MASK);
1232 /* Set this early so we can use the pagetable walking functions */
1233 kernel_pmap_store.pm_l0 = pagetable_l0_ttbr1;
1234 PMAP_LOCK_INIT(kernel_pmap);
1235 kernel_pmap->pm_l0_paddr =
1236 pmap_early_vtophys((vm_offset_t)kernel_pmap_store.pm_l0);
1237 kernel_pmap->pm_cookie = COOKIE_FROM(-1, INT_MIN);
1238 kernel_pmap->pm_stage = PM_STAGE1;
1239 kernel_pmap->pm_levels = 4;
1240 kernel_pmap->pm_ttbr = kernel_pmap->pm_l0_paddr;
1241 kernel_pmap->pm_asid_set = &asids;
1243 /* Assume the address we were loaded to is a valid physical address */
1244 min_pa = KERNBASE - kern_delta;
1246 physmap_idx = physmem_avail(physmap, nitems(physmap));
1250 * Find the minimum physical address. physmap is sorted,
1251 * but may contain empty ranges.
1253 for (i = 0; i < physmap_idx * 2; i += 2) {
1254 if (physmap[i] == physmap[i + 1])
1256 if (physmap[i] <= min_pa)
1257 min_pa = physmap[i];
1260 bs_state.freemempos = KERNBASE + kernlen;
1261 bs_state.freemempos = roundup2(bs_state.freemempos, PAGE_SIZE);
1263 /* Create a direct map region early so we can use it for pa -> va */
1264 pmap_bootstrap_dmap(min_pa);
1265 bs_state.dmap_valid = true;
1267 * We only use PXN when we know nothing will be executed from it, e.g.
1270 bs_state.table_attrs &= ~TATTR_PXN_TABLE;
1272 start_pa = pa = KERNBASE - kern_delta;
1275 * Create the l2 tables up to VM_MAX_KERNEL_ADDRESS. We assume that the
1276 * loader allocated the first and only l2 page table page used to map
1277 * the kernel, preloaded files and module metadata.
1279 pmap_bootstrap_l2(KERNBASE + L1_SIZE);
1280 /* And the l3 tables for the early devmap */
1281 pmap_bootstrap_l3(VM_MAX_KERNEL_ADDRESS - (PMAP_MAPDEV_EARLY_SIZE));
1285 #define alloc_pages(var, np) \
1286 (var) = bs_state.freemempos; \
1287 bs_state.freemempos += (np * PAGE_SIZE); \
1288 memset((char *)(var), 0, ((np) * PAGE_SIZE));
1290 /* Allocate dynamic per-cpu area. */
1291 alloc_pages(dpcpu, DPCPU_SIZE / PAGE_SIZE);
1292 dpcpu_init((void *)dpcpu, 0);
1294 /* Allocate memory for the msgbuf, e.g. for /sbin/dmesg */
1295 alloc_pages(msgbufpv, round_page(msgbufsize) / PAGE_SIZE);
1296 msgbufp = (void *)msgbufpv;
1298 /* Reserve some VA space for early BIOS/ACPI mapping */
1299 preinit_map_va = roundup2(bs_state.freemempos, L2_SIZE);
1301 virtual_avail = preinit_map_va + PMAP_PREINIT_MAPPING_SIZE;
1302 virtual_avail = roundup2(virtual_avail, L1_SIZE);
1303 virtual_end = VM_MAX_KERNEL_ADDRESS - (PMAP_MAPDEV_EARLY_SIZE);
1304 kernel_vm_end = virtual_avail;
1306 pa = pmap_early_vtophys(bs_state.freemempos);
1308 physmem_exclude_region(start_pa, pa - start_pa, EXFLAG_NOALLOC);
1314 * Initialize a vm_page's machine-dependent fields.
1317 pmap_page_init(vm_page_t m)
1320 TAILQ_INIT(&m->md.pv_list);
1321 m->md.pv_memattr = VM_MEMATTR_WRITE_BACK;
1325 pmap_init_asids(struct asid_set *set, int bits)
1329 set->asid_bits = bits;
1332 * We may be too early in the overall initialization process to use
1335 set->asid_set_size = 1 << set->asid_bits;
1336 set->asid_set = kmem_malloc(bitstr_size(set->asid_set_size),
1338 for (i = 0; i < ASID_FIRST_AVAILABLE; i++)
1339 bit_set(set->asid_set, i);
1340 set->asid_next = ASID_FIRST_AVAILABLE;
1341 mtx_init(&set->asid_set_mutex, "asid set", NULL, MTX_SPIN);
1345 pmap_init_pv_table(void)
1347 struct vm_phys_seg *seg, *next_seg;
1348 struct pmap_large_md_page *pvd;
1350 int domain, i, j, pages;
1353 * We strongly depend on the size being a power of two, so the assert
1354 * is overzealous. However, should the struct be resized to a
1355 * different power of two, the code below needs to be revisited.
1357 CTASSERT((sizeof(*pvd) == 64));
1360 * Calculate the size of the array.
1363 for (i = 0; i < vm_phys_nsegs; i++) {
1364 seg = &vm_phys_segs[i];
1365 pages = pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) -
1366 pmap_l2_pindex(seg->start);
1367 s += round_page(pages * sizeof(*pvd));
1369 pv_table = (struct pmap_large_md_page *)kva_alloc(s);
1370 if (pv_table == NULL)
1371 panic("%s: kva_alloc failed\n", __func__);
1374 * Iterate physical segments to allocate domain-local memory for PV
1378 for (i = 0; i < vm_phys_nsegs; i++) {
1379 seg = &vm_phys_segs[i];
1380 pages = pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) -
1381 pmap_l2_pindex(seg->start);
1382 domain = seg->domain;
1384 s = round_page(pages * sizeof(*pvd));
1386 for (j = 0; j < s; j += PAGE_SIZE) {
1387 vm_page_t m = vm_page_alloc_noobj_domain(domain,
1390 panic("failed to allocate PV table page");
1391 pmap_qenter((vm_offset_t)pvd + j, &m, 1);
1394 for (j = 0; j < s / sizeof(*pvd); j++) {
1395 rw_init_flags(&pvd->pv_lock, "pmap pv list", RW_NEW);
1396 TAILQ_INIT(&pvd->pv_page.pv_list);
1400 pvd = &pv_dummy_large;
1401 memset(pvd, 0, sizeof(*pvd));
1402 rw_init_flags(&pvd->pv_lock, "pmap pv list dummy", RW_NEW);
1403 TAILQ_INIT(&pvd->pv_page.pv_list);
1406 * Set pointers from vm_phys_segs to pv_table.
1408 for (i = 0, pvd = pv_table; i < vm_phys_nsegs; i++) {
1409 seg = &vm_phys_segs[i];
1410 seg->md_first = pvd;
1411 pvd += pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) -
1412 pmap_l2_pindex(seg->start);
1415 * If there is a following segment, and the final
1416 * superpage of this segment and the initial superpage
1417 * of the next segment are the same then adjust the
1418 * pv_table entry for that next segment down by one so
1419 * that the pv_table entries will be shared.
1421 if (i + 1 < vm_phys_nsegs) {
1422 next_seg = &vm_phys_segs[i + 1];
1423 if (pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) - 1 ==
1424 pmap_l2_pindex(next_seg->start)) {
1432 * Initialize the pmap module.
1433 * Called by vm_init, to initialize any structures that the pmap
1434 * system needs to map virtual memory.
1443 * Are large page mappings enabled?
1445 TUNABLE_INT_FETCH("vm.pmap.superpages_enabled", &superpages_enabled);
1446 if (superpages_enabled) {
1447 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1448 ("pmap_init: can't assign to pagesizes[1]"));
1449 pagesizes[1] = L2_SIZE;
1450 if (L1_BLOCKS_SUPPORTED) {
1451 KASSERT(MAXPAGESIZES > 2 && pagesizes[2] == 0,
1452 ("pmap_init: can't assign to pagesizes[2]"));
1453 pagesizes[2] = L1_SIZE;
1458 * Initialize the ASID allocator.
1460 pmap_init_asids(&asids,
1461 (READ_SPECIALREG(tcr_el1) & TCR_ASID_16) != 0 ? 16 : 8);
1464 mmfr1 = READ_SPECIALREG(id_aa64mmfr1_el1);
1467 if (ID_AA64MMFR1_VMIDBits_VAL(mmfr1) ==
1468 ID_AA64MMFR1_VMIDBits_16)
1470 pmap_init_asids(&vmids, vmid_bits);
1474 * Initialize pv chunk lists.
1476 for (i = 0; i < PMAP_MEMDOM; i++) {
1477 mtx_init(&pv_chunks[i].pvc_lock, "pmap pv chunk list", NULL,
1479 TAILQ_INIT(&pv_chunks[i].pvc_list);
1481 pmap_init_pv_table();
1486 static SYSCTL_NODE(_vm_pmap, OID_AUTO, l2, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
1487 "2MB page mapping counters");
1489 static u_long pmap_l2_demotions;
1490 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, demotions, CTLFLAG_RD,
1491 &pmap_l2_demotions, 0, "2MB page demotions");
1493 static u_long pmap_l2_mappings;
1494 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, mappings, CTLFLAG_RD,
1495 &pmap_l2_mappings, 0, "2MB page mappings");
1497 static u_long pmap_l2_p_failures;
1498 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, p_failures, CTLFLAG_RD,
1499 &pmap_l2_p_failures, 0, "2MB page promotion failures");
1501 static u_long pmap_l2_promotions;
1502 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, promotions, CTLFLAG_RD,
1503 &pmap_l2_promotions, 0, "2MB page promotions");
1506 * If the given value for "final_only" is false, then any cached intermediate-
1507 * level entries, i.e., L{0,1,2}_TABLE entries, are invalidated in addition to
1508 * any cached final-level entry, i.e., either an L{1,2}_BLOCK or L3_PAGE entry.
1509 * Otherwise, just the cached final-level entry is invalidated.
1511 static __inline void
1512 pmap_s1_invalidate_kernel(uint64_t r, bool final_only)
1515 __asm __volatile("tlbi vaale1is, %0" : : "r" (r));
1517 __asm __volatile("tlbi vaae1is, %0" : : "r" (r));
1520 static __inline void
1521 pmap_s1_invalidate_user(uint64_t r, bool final_only)
1524 __asm __volatile("tlbi vale1is, %0" : : "r" (r));
1526 __asm __volatile("tlbi vae1is, %0" : : "r" (r));
1530 * Invalidates any cached final- and optionally intermediate-level TLB entries
1531 * for the specified virtual address in the given virtual address space.
1533 static __inline void
1534 pmap_s1_invalidate_page(pmap_t pmap, vm_offset_t va, bool final_only)
1538 PMAP_ASSERT_STAGE1(pmap);
1542 if (pmap == kernel_pmap) {
1543 pmap_s1_invalidate_kernel(r, final_only);
1545 r |= ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
1546 pmap_s1_invalidate_user(r, final_only);
1553 * Invalidates any cached final- and optionally intermediate-level TLB entries
1554 * for the specified virtual address range in the given virtual address space.
1556 static __inline void
1557 pmap_s1_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1560 uint64_t end, r, start;
1562 PMAP_ASSERT_STAGE1(pmap);
1565 if (pmap == kernel_pmap) {
1566 start = TLBI_VA(sva);
1568 for (r = start; r < end; r += TLBI_VA_L3_INCR)
1569 pmap_s1_invalidate_kernel(r, final_only);
1571 start = end = ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
1572 start |= TLBI_VA(sva);
1573 end |= TLBI_VA(eva);
1574 for (r = start; r < end; r += TLBI_VA_L3_INCR)
1575 pmap_s1_invalidate_user(r, final_only);
1582 * Invalidates all cached intermediate- and final-level TLB entries for the
1583 * given virtual address space.
1585 static __inline void
1586 pmap_s1_invalidate_all(pmap_t pmap)
1590 PMAP_ASSERT_STAGE1(pmap);
1593 if (pmap == kernel_pmap) {
1594 __asm __volatile("tlbi vmalle1is");
1596 r = ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
1597 __asm __volatile("tlbi aside1is, %0" : : "r" (r));
1604 * Routine: pmap_extract
1606 * Extract the physical page address associated
1607 * with the given map/virtual_address pair.
1610 pmap_extract(pmap_t pmap, vm_offset_t va)
1612 pt_entry_t *pte, tpte;
1619 * Find the block or page map for this virtual address. pmap_pte
1620 * will return either a valid block/page entry, or NULL.
1622 pte = pmap_pte(pmap, va, &lvl);
1624 tpte = pmap_load(pte);
1625 pa = tpte & ~ATTR_MASK;
1628 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
1629 KASSERT((tpte & ATTR_DESCR_MASK) == L1_BLOCK,
1630 ("pmap_extract: Invalid L1 pte found: %lx",
1631 tpte & ATTR_DESCR_MASK));
1632 pa |= (va & L1_OFFSET);
1635 KASSERT((tpte & ATTR_DESCR_MASK) == L2_BLOCK,
1636 ("pmap_extract: Invalid L2 pte found: %lx",
1637 tpte & ATTR_DESCR_MASK));
1638 pa |= (va & L2_OFFSET);
1641 KASSERT((tpte & ATTR_DESCR_MASK) == L3_PAGE,
1642 ("pmap_extract: Invalid L3 pte found: %lx",
1643 tpte & ATTR_DESCR_MASK));
1644 pa |= (va & L3_OFFSET);
1653 * Routine: pmap_extract_and_hold
1655 * Atomically extract and hold the physical page
1656 * with the given pmap and virtual address pair
1657 * if that mapping permits the given protection.
1660 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1662 pt_entry_t *pte, tpte;
1670 pte = pmap_pte(pmap, va, &lvl);
1672 tpte = pmap_load(pte);
1674 KASSERT(lvl > 0 && lvl <= 3,
1675 ("pmap_extract_and_hold: Invalid level %d", lvl));
1677 * Check that the pte is either a L3 page, or a L1 or L2 block
1678 * entry. We can assume L1_BLOCK == L2_BLOCK.
1680 KASSERT((lvl == 3 && (tpte & ATTR_DESCR_MASK) == L3_PAGE) ||
1681 (lvl < 3 && (tpte & ATTR_DESCR_MASK) == L1_BLOCK),
1682 ("pmap_extract_and_hold: Invalid pte at L%d: %lx", lvl,
1683 tpte & ATTR_DESCR_MASK));
1686 if ((prot & VM_PROT_WRITE) == 0)
1688 else if (pmap->pm_stage == PM_STAGE1 &&
1689 (tpte & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP(ATTR_S1_AP_RW))
1691 else if (pmap->pm_stage == PM_STAGE2 &&
1692 ((tpte & ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE)) ==
1693 ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE)))
1699 off = va & L1_OFFSET;
1702 off = va & L2_OFFSET;
1708 m = PHYS_TO_VM_PAGE((tpte & ~ATTR_MASK) | off);
1709 if (m != NULL && !vm_page_wire_mapped(m))
1718 * Walks the page tables to translate a kernel virtual address to a
1719 * physical address. Returns true if the kva is valid and stores the
1720 * physical address in pa if it is not NULL.
1722 * See the comment above data_abort() for the rationale for specifying
1723 * NO_PERTHREAD_SSP here.
1725 bool NO_PERTHREAD_SSP
1726 pmap_klookup(vm_offset_t va, vm_paddr_t *pa)
1728 pt_entry_t *pte, tpte;
1733 * Disable interrupts so we don't get interrupted between asking
1734 * for address translation, and getting the result back.
1736 intr = intr_disable();
1737 par = arm64_address_translate_s1e1r(va);
1740 if (PAR_SUCCESS(par)) {
1742 *pa = (par & PAR_PA_MASK) | (va & PAR_LOW_MASK);
1747 * Fall back to walking the page table. The address translation
1748 * instruction may fail when the page is in a break-before-make
1749 * sequence. As we only clear the valid bit in said sequence we
1750 * can walk the page table to find the physical address.
1753 pte = pmap_l1(kernel_pmap, va);
1758 * A concurrent pmap_update_entry() will clear the entry's valid bit
1759 * but leave the rest of the entry unchanged. Therefore, we treat a
1760 * non-zero entry as being valid, and we ignore the valid bit when
1761 * determining whether the entry maps a block, page, or table.
1763 tpte = pmap_load(pte);
1766 if ((tpte & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
1768 *pa = (tpte & ~ATTR_MASK) | (va & L1_OFFSET);
1771 pte = pmap_l1_to_l2(&tpte, va);
1772 tpte = pmap_load(pte);
1775 if ((tpte & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
1777 *pa = (tpte & ~ATTR_MASK) | (va & L2_OFFSET);
1780 pte = pmap_l2_to_l3(&tpte, va);
1781 tpte = pmap_load(pte);
1785 *pa = (tpte & ~ATTR_MASK) | (va & L3_OFFSET);
1790 pmap_kextract(vm_offset_t va)
1794 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
1795 return (DMAP_TO_PHYS(va));
1797 if (pmap_klookup(va, &pa) == false)
1802 /***************************************************
1803 * Low level mapping routines.....
1804 ***************************************************/
1807 pmap_kenter(vm_offset_t sva, vm_size_t size, vm_paddr_t pa, int mode)
1810 pt_entry_t *pte, attr;
1814 KASSERT((pa & L3_OFFSET) == 0,
1815 ("pmap_kenter: Invalid physical address"));
1816 KASSERT((sva & L3_OFFSET) == 0,
1817 ("pmap_kenter: Invalid virtual address"));
1818 KASSERT((size & PAGE_MASK) == 0,
1819 ("pmap_kenter: Mapping is not page-sized"));
1821 attr = ATTR_DEFAULT | ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_S1_XN |
1822 ATTR_S1_IDX(mode) | L3_PAGE;
1825 pde = pmap_pde(kernel_pmap, va, &lvl);
1826 KASSERT(pde != NULL,
1827 ("pmap_kenter: Invalid page entry, va: 0x%lx", va));
1828 KASSERT(lvl == 2, ("pmap_kenter: Invalid level %d", lvl));
1830 pte = pmap_l2_to_l3(pde, va);
1831 pmap_load_store(pte, (pa & ~L3_OFFSET) | attr);
1837 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
1841 pmap_kenter_device(vm_offset_t sva, vm_size_t size, vm_paddr_t pa)
1844 pmap_kenter(sva, size, pa, VM_MEMATTR_DEVICE);
1848 * Remove a page from the kernel pagetables.
1851 pmap_kremove(vm_offset_t va)
1855 pte = pmap_pte_exists(kernel_pmap, va, 3, __func__);
1857 pmap_s1_invalidate_page(kernel_pmap, va, true);
1861 pmap_kremove_device(vm_offset_t sva, vm_size_t size)
1866 KASSERT((sva & L3_OFFSET) == 0,
1867 ("pmap_kremove_device: Invalid virtual address"));
1868 KASSERT((size & PAGE_MASK) == 0,
1869 ("pmap_kremove_device: Mapping is not page-sized"));
1873 pte = pmap_pte_exists(kernel_pmap, va, 3, __func__);
1879 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
1883 * Used to map a range of physical addresses into kernel
1884 * virtual address space.
1886 * The value passed in '*virt' is a suggested virtual address for
1887 * the mapping. Architectures which can support a direct-mapped
1888 * physical to virtual region can return the appropriate address
1889 * within that region, leaving '*virt' unchanged. Other
1890 * architectures should map the pages starting at '*virt' and
1891 * update '*virt' with the first usable address after the mapped
1895 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
1897 return PHYS_TO_DMAP(start);
1901 * Add a list of wired pages to the kva
1902 * this routine is only used for temporary
1903 * kernel mappings that do not need to have
1904 * page modification or references recorded.
1905 * Note that old mappings are simply written
1906 * over. The page *must* be wired.
1907 * Note: SMP coherent. Uses a ranged shootdown IPI.
1910 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
1913 pt_entry_t *pte, pa;
1919 for (i = 0; i < count; i++) {
1920 pde = pmap_pde(kernel_pmap, va, &lvl);
1921 KASSERT(pde != NULL,
1922 ("pmap_qenter: Invalid page entry, va: 0x%lx", va));
1924 ("pmap_qenter: Invalid level %d", lvl));
1927 pa = VM_PAGE_TO_PHYS(m) | ATTR_DEFAULT |
1928 ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_S1_XN |
1929 ATTR_S1_IDX(m->md.pv_memattr) | L3_PAGE;
1930 pte = pmap_l2_to_l3(pde, va);
1931 pmap_load_store(pte, pa);
1935 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
1939 * This routine tears out page mappings from the
1940 * kernel -- it is meant only for temporary mappings.
1943 pmap_qremove(vm_offset_t sva, int count)
1948 KASSERT(ADDR_IS_CANONICAL(sva),
1949 ("%s: Address not in canonical form: %lx", __func__, sva));
1950 KASSERT(ADDR_IS_KERNEL(sva), ("usermode va %lx", sva));
1953 while (count-- > 0) {
1954 pte = pmap_pte_exists(kernel_pmap, va, 3, NULL);
1961 pmap_s1_invalidate_range(kernel_pmap, sva, va, true);
1964 /***************************************************
1965 * Page table page management routines.....
1966 ***************************************************/
1968 * Schedule the specified unused page table page to be freed. Specifically,
1969 * add the page to the specified list of pages that will be released to the
1970 * physical memory manager after the TLB has been updated.
1972 static __inline void
1973 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
1974 boolean_t set_PG_ZERO)
1978 m->flags |= PG_ZERO;
1980 m->flags &= ~PG_ZERO;
1981 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
1985 * Decrements a page table page's reference count, which is used to record the
1986 * number of valid page table entries within the page. If the reference count
1987 * drops to zero, then the page table page is unmapped. Returns TRUE if the
1988 * page table page was unmapped and FALSE otherwise.
1990 static inline boolean_t
1991 pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
1995 if (m->ref_count == 0) {
1996 _pmap_unwire_l3(pmap, va, m, free);
2003 _pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2006 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2008 * unmap the page table page
2010 if (m->pindex >= (NUL2E + NUL1E)) {
2014 l0 = pmap_l0(pmap, va);
2016 } else if (m->pindex >= NUL2E) {
2020 l1 = pmap_l1(pmap, va);
2026 l2 = pmap_l2(pmap, va);
2029 pmap_resident_count_dec(pmap, 1);
2030 if (m->pindex < NUL2E) {
2031 /* We just released an l3, unhold the matching l2 */
2032 pd_entry_t *l1, tl1;
2035 l1 = pmap_l1(pmap, va);
2036 tl1 = pmap_load(l1);
2037 l2pg = PHYS_TO_VM_PAGE(tl1 & ~ATTR_MASK);
2038 pmap_unwire_l3(pmap, va, l2pg, free);
2039 } else if (m->pindex < (NUL2E + NUL1E)) {
2040 /* We just released an l2, unhold the matching l1 */
2041 pd_entry_t *l0, tl0;
2044 l0 = pmap_l0(pmap, va);
2045 tl0 = pmap_load(l0);
2046 l1pg = PHYS_TO_VM_PAGE(tl0 & ~ATTR_MASK);
2047 pmap_unwire_l3(pmap, va, l1pg, free);
2049 pmap_s1_invalidate_page(pmap, va, false);
2052 * Put page on a list so that it is released after
2053 * *ALL* TLB shootdown is done
2055 pmap_add_delayed_free_list(m, free, TRUE);
2059 * After removing a page table entry, this routine is used to
2060 * conditionally free the page, and manage the reference count.
2063 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2064 struct spglist *free)
2068 KASSERT(ADDR_IS_CANONICAL(va),
2069 ("%s: Address not in canonical form: %lx", __func__, va));
2070 if (ADDR_IS_KERNEL(va))
2072 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2073 mpte = PHYS_TO_VM_PAGE(ptepde & ~ATTR_MASK);
2074 return (pmap_unwire_l3(pmap, va, mpte, free));
2078 * Release a page table page reference after a failed attempt to create a
2082 pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
2084 struct spglist free;
2087 if (pmap_unwire_l3(pmap, va, mpte, &free))
2088 vm_page_free_pages_toq(&free, true);
2092 pmap_pinit0(pmap_t pmap)
2095 PMAP_LOCK_INIT(pmap);
2096 bzero(&pmap->pm_stats, sizeof(pmap->pm_stats));
2097 pmap->pm_l0_paddr = READ_SPECIALREG(ttbr0_el1);
2098 pmap->pm_l0 = (pd_entry_t *)PHYS_TO_DMAP(pmap->pm_l0_paddr);
2099 vm_radix_init(&pmap->pm_root);
2100 pmap->pm_cookie = COOKIE_FROM(ASID_RESERVED_FOR_PID_0, INT_MIN);
2101 pmap->pm_stage = PM_STAGE1;
2102 pmap->pm_levels = 4;
2103 pmap->pm_ttbr = pmap->pm_l0_paddr;
2104 pmap->pm_asid_set = &asids;
2106 PCPU_SET(curpmap, pmap);
2110 pmap_pinit_stage(pmap_t pmap, enum pmap_stage stage, int levels)
2115 * allocate the l0 page
2117 m = vm_page_alloc_noobj(VM_ALLOC_WAITOK | VM_ALLOC_WIRED |
2119 pmap->pm_l0_paddr = VM_PAGE_TO_PHYS(m);
2120 pmap->pm_l0 = (pd_entry_t *)PHYS_TO_DMAP(pmap->pm_l0_paddr);
2122 vm_radix_init(&pmap->pm_root);
2123 bzero(&pmap->pm_stats, sizeof(pmap->pm_stats));
2124 pmap->pm_cookie = COOKIE_FROM(-1, INT_MAX);
2126 MPASS(levels == 3 || levels == 4);
2127 pmap->pm_levels = levels;
2128 pmap->pm_stage = stage;
2131 pmap->pm_asid_set = &asids;
2134 pmap->pm_asid_set = &vmids;
2137 panic("%s: Invalid pmap type %d", __func__, stage);
2141 /* XXX Temporarily disable deferred ASID allocation. */
2142 pmap_alloc_asid(pmap);
2145 * Allocate the level 1 entry to use as the root. This will increase
2146 * the refcount on the level 1 page so it won't be removed until
2147 * pmap_release() is called.
2149 if (pmap->pm_levels == 3) {
2151 m = _pmap_alloc_l3(pmap, NUL2E + NUL1E, NULL);
2154 pmap->pm_ttbr = VM_PAGE_TO_PHYS(m);
2160 pmap_pinit(pmap_t pmap)
2163 return (pmap_pinit_stage(pmap, PM_STAGE1, 4));
2167 * This routine is called if the desired page table page does not exist.
2169 * If page table page allocation fails, this routine may sleep before
2170 * returning NULL. It sleeps only if a lock pointer was given.
2172 * Note: If a page allocation fails at page table level two or three,
2173 * one or two pages may be held during the wait, only to be released
2174 * afterwards. This conservative approach is easily argued to avoid
2178 _pmap_alloc_l3(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2180 vm_page_t m, l1pg, l2pg;
2182 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2185 * Allocate a page table page.
2187 if ((m = vm_page_alloc_noobj(VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2188 if (lockp != NULL) {
2189 RELEASE_PV_LIST_LOCK(lockp);
2196 * Indicate the need to retry. While waiting, the page table
2197 * page may have been allocated.
2201 m->pindex = ptepindex;
2204 * Because of AArch64's weak memory consistency model, we must have a
2205 * barrier here to ensure that the stores for zeroing "m", whether by
2206 * pmap_zero_page() or an earlier function, are visible before adding
2207 * "m" to the page table. Otherwise, a page table walk by another
2208 * processor's MMU could see the mapping to "m" and a stale, non-zero
2214 * Map the pagetable page into the process address space, if
2215 * it isn't already there.
2218 if (ptepindex >= (NUL2E + NUL1E)) {
2219 pd_entry_t *l0p, l0e;
2220 vm_pindex_t l0index;
2222 l0index = ptepindex - (NUL2E + NUL1E);
2223 l0p = &pmap->pm_l0[l0index];
2224 KASSERT((pmap_load(l0p) & ATTR_DESCR_VALID) == 0,
2225 ("%s: L0 entry %#lx is valid", __func__, pmap_load(l0p)));
2226 l0e = VM_PAGE_TO_PHYS(m) | L0_TABLE;
2229 * Mark all kernel memory as not accessible from userspace
2230 * and userspace memory as not executable from the kernel.
2231 * This has been done for the bootstrap L0 entries in
2234 if (pmap == kernel_pmap)
2235 l0e |= TATTR_UXN_TABLE | TATTR_AP_TABLE_NO_EL0;
2237 l0e |= TATTR_PXN_TABLE;
2238 pmap_store(l0p, l0e);
2239 } else if (ptepindex >= NUL2E) {
2240 vm_pindex_t l0index, l1index;
2241 pd_entry_t *l0, *l1;
2244 l1index = ptepindex - NUL2E;
2245 l0index = l1index >> Ln_ENTRIES_SHIFT;
2247 l0 = &pmap->pm_l0[l0index];
2248 tl0 = pmap_load(l0);
2250 /* recurse for allocating page dir */
2251 if (_pmap_alloc_l3(pmap, NUL2E + NUL1E + l0index,
2253 vm_page_unwire_noq(m);
2254 vm_page_free_zero(m);
2258 l1pg = PHYS_TO_VM_PAGE(tl0 & ~ATTR_MASK);
2262 l1 = (pd_entry_t *)PHYS_TO_DMAP(pmap_load(l0) & ~ATTR_MASK);
2263 l1 = &l1[ptepindex & Ln_ADDR_MASK];
2264 KASSERT((pmap_load(l1) & ATTR_DESCR_VALID) == 0,
2265 ("%s: L1 entry %#lx is valid", __func__, pmap_load(l1)));
2266 pmap_store(l1, VM_PAGE_TO_PHYS(m) | L1_TABLE);
2268 vm_pindex_t l0index, l1index;
2269 pd_entry_t *l0, *l1, *l2;
2270 pd_entry_t tl0, tl1;
2272 l1index = ptepindex >> Ln_ENTRIES_SHIFT;
2273 l0index = l1index >> Ln_ENTRIES_SHIFT;
2275 l0 = &pmap->pm_l0[l0index];
2276 tl0 = pmap_load(l0);
2278 /* recurse for allocating page dir */
2279 if (_pmap_alloc_l3(pmap, NUL2E + l1index,
2281 vm_page_unwire_noq(m);
2282 vm_page_free_zero(m);
2285 tl0 = pmap_load(l0);
2286 l1 = (pd_entry_t *)PHYS_TO_DMAP(tl0 & ~ATTR_MASK);
2287 l1 = &l1[l1index & Ln_ADDR_MASK];
2289 l1 = (pd_entry_t *)PHYS_TO_DMAP(tl0 & ~ATTR_MASK);
2290 l1 = &l1[l1index & Ln_ADDR_MASK];
2291 tl1 = pmap_load(l1);
2293 /* recurse for allocating page dir */
2294 if (_pmap_alloc_l3(pmap, NUL2E + l1index,
2296 vm_page_unwire_noq(m);
2297 vm_page_free_zero(m);
2301 l2pg = PHYS_TO_VM_PAGE(tl1 & ~ATTR_MASK);
2306 l2 = (pd_entry_t *)PHYS_TO_DMAP(pmap_load(l1) & ~ATTR_MASK);
2307 l2 = &l2[ptepindex & Ln_ADDR_MASK];
2308 KASSERT((pmap_load(l2) & ATTR_DESCR_VALID) == 0,
2309 ("%s: L2 entry %#lx is valid", __func__, pmap_load(l2)));
2310 pmap_store(l2, VM_PAGE_TO_PHYS(m) | L2_TABLE);
2313 pmap_resident_count_inc(pmap, 1);
2319 pmap_alloc_l2(pmap_t pmap, vm_offset_t va, vm_page_t *l2pgp,
2320 struct rwlock **lockp)
2322 pd_entry_t *l1, *l2;
2324 vm_pindex_t l2pindex;
2326 KASSERT(ADDR_IS_CANONICAL(va),
2327 ("%s: Address not in canonical form: %lx", __func__, va));
2330 l1 = pmap_l1(pmap, va);
2331 if (l1 != NULL && (pmap_load(l1) & ATTR_DESCR_MASK) == L1_TABLE) {
2332 l2 = pmap_l1_to_l2(l1, va);
2333 if (!ADDR_IS_KERNEL(va)) {
2334 /* Add a reference to the L2 page. */
2335 l2pg = PHYS_TO_VM_PAGE(pmap_load(l1) & ~ATTR_MASK);
2339 } else if (!ADDR_IS_KERNEL(va)) {
2340 /* Allocate a L2 page. */
2341 l2pindex = pmap_l2_pindex(va) >> Ln_ENTRIES_SHIFT;
2342 l2pg = _pmap_alloc_l3(pmap, NUL2E + l2pindex, lockp);
2349 l2 = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(l2pg));
2350 l2 = &l2[pmap_l2_index(va)];
2352 panic("pmap_alloc_l2: missing page table page for va %#lx",
2359 pmap_alloc_l3(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2361 vm_pindex_t ptepindex;
2362 pd_entry_t *pde, tpde;
2370 * Calculate pagetable page index
2372 ptepindex = pmap_l2_pindex(va);
2375 * Get the page directory entry
2377 pde = pmap_pde(pmap, va, &lvl);
2380 * If the page table page is mapped, we just increment the hold count,
2381 * and activate it. If we get a level 2 pde it will point to a level 3
2389 pte = pmap_l0_to_l1(pde, va);
2390 KASSERT(pmap_load(pte) == 0,
2391 ("pmap_alloc_l3: TODO: l0 superpages"));
2396 pte = pmap_l1_to_l2(pde, va);
2397 KASSERT(pmap_load(pte) == 0,
2398 ("pmap_alloc_l3: TODO: l1 superpages"));
2402 tpde = pmap_load(pde);
2404 m = PHYS_TO_VM_PAGE(tpde & ~ATTR_MASK);
2410 panic("pmap_alloc_l3: Invalid level %d", lvl);
2414 * Here if the pte page isn't mapped, or if it has been deallocated.
2416 m = _pmap_alloc_l3(pmap, ptepindex, lockp);
2417 if (m == NULL && lockp != NULL)
2423 /***************************************************
2424 * Pmap allocation/deallocation routines.
2425 ***************************************************/
2428 * Release any resources held by the given physical map.
2429 * Called when a pmap initialized by pmap_pinit is being released.
2430 * Should only be called if the map contains no valid mappings.
2433 pmap_release(pmap_t pmap)
2435 boolean_t rv __diagused;
2436 struct spglist free;
2437 struct asid_set *set;
2441 if (pmap->pm_levels != 4) {
2442 PMAP_ASSERT_STAGE2(pmap);
2443 KASSERT(pmap->pm_stats.resident_count == 1,
2444 ("pmap_release: pmap resident count %ld != 0",
2445 pmap->pm_stats.resident_count));
2446 KASSERT((pmap->pm_l0[0] & ATTR_DESCR_VALID) == ATTR_DESCR_VALID,
2447 ("pmap_release: Invalid l0 entry: %lx", pmap->pm_l0[0]));
2450 m = PHYS_TO_VM_PAGE(pmap->pm_ttbr);
2452 rv = pmap_unwire_l3(pmap, 0, m, &free);
2455 vm_page_free_pages_toq(&free, true);
2458 KASSERT(pmap->pm_stats.resident_count == 0,
2459 ("pmap_release: pmap resident count %ld != 0",
2460 pmap->pm_stats.resident_count));
2461 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2462 ("pmap_release: pmap has reserved page table page(s)"));
2464 set = pmap->pm_asid_set;
2465 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
2468 * Allow the ASID to be reused. In stage 2 VMIDs we don't invalidate
2469 * the entries when removing them so rely on a later tlb invalidation.
2470 * this will happen when updating the VMID generation. Because of this
2471 * we don't reuse VMIDs within a generation.
2473 if (pmap->pm_stage == PM_STAGE1) {
2474 mtx_lock_spin(&set->asid_set_mutex);
2475 if (COOKIE_TO_EPOCH(pmap->pm_cookie) == set->asid_epoch) {
2476 asid = COOKIE_TO_ASID(pmap->pm_cookie);
2477 KASSERT(asid >= ASID_FIRST_AVAILABLE &&
2478 asid < set->asid_set_size,
2479 ("pmap_release: pmap cookie has out-of-range asid"));
2480 bit_clear(set->asid_set, asid);
2482 mtx_unlock_spin(&set->asid_set_mutex);
2485 m = PHYS_TO_VM_PAGE(pmap->pm_l0_paddr);
2486 vm_page_unwire_noq(m);
2487 vm_page_free_zero(m);
2491 kvm_size(SYSCTL_HANDLER_ARGS)
2493 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2495 return sysctl_handle_long(oidp, &ksize, 0, req);
2497 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
2498 0, 0, kvm_size, "LU",
2502 kvm_free(SYSCTL_HANDLER_ARGS)
2504 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2506 return sysctl_handle_long(oidp, &kfree, 0, req);
2508 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
2509 0, 0, kvm_free, "LU",
2510 "Amount of KVM free");
2513 * grow the number of kernel page table entries, if needed
2516 pmap_growkernel(vm_offset_t addr)
2520 pd_entry_t *l0, *l1, *l2;
2522 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2524 addr = roundup2(addr, L2_SIZE);
2525 if (addr - 1 >= vm_map_max(kernel_map))
2526 addr = vm_map_max(kernel_map);
2527 while (kernel_vm_end < addr) {
2528 l0 = pmap_l0(kernel_pmap, kernel_vm_end);
2529 KASSERT(pmap_load(l0) != 0,
2530 ("pmap_growkernel: No level 0 kernel entry"));
2532 l1 = pmap_l0_to_l1(l0, kernel_vm_end);
2533 if (pmap_load(l1) == 0) {
2534 /* We need a new PDP entry */
2535 nkpg = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT |
2536 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2538 panic("pmap_growkernel: no memory to grow kernel");
2539 nkpg->pindex = kernel_vm_end >> L1_SHIFT;
2540 /* See the dmb() in _pmap_alloc_l3(). */
2542 paddr = VM_PAGE_TO_PHYS(nkpg);
2543 pmap_store(l1, paddr | L1_TABLE);
2544 continue; /* try again */
2546 l2 = pmap_l1_to_l2(l1, kernel_vm_end);
2547 if (pmap_load(l2) != 0) {
2548 kernel_vm_end = (kernel_vm_end + L2_SIZE) & ~L2_OFFSET;
2549 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
2550 kernel_vm_end = vm_map_max(kernel_map);
2556 nkpg = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED |
2559 panic("pmap_growkernel: no memory to grow kernel");
2560 nkpg->pindex = kernel_vm_end >> L2_SHIFT;
2561 /* See the dmb() in _pmap_alloc_l3(). */
2563 paddr = VM_PAGE_TO_PHYS(nkpg);
2564 pmap_store(l2, paddr | L2_TABLE);
2566 kernel_vm_end = (kernel_vm_end + L2_SIZE) & ~L2_OFFSET;
2567 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
2568 kernel_vm_end = vm_map_max(kernel_map);
2574 /***************************************************
2575 * page management routines.
2576 ***************************************************/
2578 static const uint64_t pc_freemask[_NPCM] = {
2579 [0 ... _NPCM - 2] = PC_FREEN,
2580 [_NPCM - 1] = PC_FREEL
2584 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2586 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2587 "Current number of pv entry chunks");
2588 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2589 "Current number of pv entry chunks allocated");
2590 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2591 "Current number of pv entry chunks frees");
2592 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
2593 "Number of times tried to get a chunk page but failed.");
2595 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
2596 static int pv_entry_spare;
2598 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2599 "Current number of pv entry frees");
2600 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
2601 "Current number of pv entry allocs");
2602 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2603 "Current number of pv entries");
2604 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2605 "Current number of spare pv entries");
2609 * We are in a serious low memory condition. Resort to
2610 * drastic measures to free some pages so we can allocate
2611 * another pv entry chunk.
2613 * Returns NULL if PV entries were reclaimed from the specified pmap.
2615 * We do not, however, unmap 2mpages because subsequent accesses will
2616 * allocate per-page pv entries until repromotion occurs, thereby
2617 * exacerbating the shortage of free pv entries.
2620 reclaim_pv_chunk_domain(pmap_t locked_pmap, struct rwlock **lockp, int domain)
2622 struct pv_chunks_list *pvc;
2623 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
2624 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
2625 struct md_page *pvh;
2627 pmap_t next_pmap, pmap;
2628 pt_entry_t *pte, tpte;
2632 struct spglist free;
2634 int bit, field, freed, lvl;
2636 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2637 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
2642 bzero(&pc_marker_b, sizeof(pc_marker_b));
2643 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
2644 pc_marker = (struct pv_chunk *)&pc_marker_b;
2645 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
2647 pvc = &pv_chunks[domain];
2648 mtx_lock(&pvc->pvc_lock);
2649 pvc->active_reclaims++;
2650 TAILQ_INSERT_HEAD(&pvc->pvc_list, pc_marker, pc_lru);
2651 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc_marker_end, pc_lru);
2652 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
2653 SLIST_EMPTY(&free)) {
2654 next_pmap = pc->pc_pmap;
2655 if (next_pmap == NULL) {
2657 * The next chunk is a marker. However, it is
2658 * not our marker, so active_reclaims must be
2659 * > 1. Consequently, the next_chunk code
2660 * will not rotate the pv_chunks list.
2664 mtx_unlock(&pvc->pvc_lock);
2667 * A pv_chunk can only be removed from the pc_lru list
2668 * when both pvc->pvc_lock is owned and the
2669 * corresponding pmap is locked.
2671 if (pmap != next_pmap) {
2672 if (pmap != NULL && pmap != locked_pmap)
2675 /* Avoid deadlock and lock recursion. */
2676 if (pmap > locked_pmap) {
2677 RELEASE_PV_LIST_LOCK(lockp);
2679 mtx_lock(&pvc->pvc_lock);
2681 } else if (pmap != locked_pmap) {
2682 if (PMAP_TRYLOCK(pmap)) {
2683 mtx_lock(&pvc->pvc_lock);
2686 pmap = NULL; /* pmap is not locked */
2687 mtx_lock(&pvc->pvc_lock);
2688 pc = TAILQ_NEXT(pc_marker, pc_lru);
2690 pc->pc_pmap != next_pmap)
2698 * Destroy every non-wired, 4 KB page mapping in the chunk.
2701 for (field = 0; field < _NPCM; field++) {
2702 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2703 inuse != 0; inuse &= ~(1UL << bit)) {
2704 bit = ffsl(inuse) - 1;
2705 pv = &pc->pc_pventry[field * 64 + bit];
2707 pde = pmap_pde(pmap, va, &lvl);
2710 pte = pmap_l2_to_l3(pde, va);
2711 tpte = pmap_load(pte);
2712 if ((tpte & ATTR_SW_WIRED) != 0)
2714 tpte = pmap_load_clear(pte);
2715 m = PHYS_TO_VM_PAGE(tpte & ~ATTR_MASK);
2716 if (pmap_pte_dirty(pmap, tpte))
2718 if ((tpte & ATTR_AF) != 0) {
2719 pmap_s1_invalidate_page(pmap, va, true);
2720 vm_page_aflag_set(m, PGA_REFERENCED);
2722 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
2723 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
2725 if (TAILQ_EMPTY(&m->md.pv_list) &&
2726 (m->flags & PG_FICTITIOUS) == 0) {
2727 pvh = page_to_pvh(m);
2728 if (TAILQ_EMPTY(&pvh->pv_list)) {
2729 vm_page_aflag_clear(m,
2733 pc->pc_map[field] |= 1UL << bit;
2734 pmap_unuse_pt(pmap, va, pmap_load(pde), &free);
2739 mtx_lock(&pvc->pvc_lock);
2742 /* Every freed mapping is for a 4 KB page. */
2743 pmap_resident_count_dec(pmap, freed);
2744 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
2745 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
2746 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
2747 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2748 if (pc_is_free(pc)) {
2749 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
2750 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
2751 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
2752 /* Entire chunk is free; return it. */
2753 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
2754 dump_drop_page(m_pc->phys_addr);
2755 mtx_lock(&pvc->pvc_lock);
2756 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
2759 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2760 mtx_lock(&pvc->pvc_lock);
2761 /* One freed pv entry in locked_pmap is sufficient. */
2762 if (pmap == locked_pmap)
2766 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
2767 TAILQ_INSERT_AFTER(&pvc->pvc_list, pc, pc_marker, pc_lru);
2768 if (pvc->active_reclaims == 1 && pmap != NULL) {
2770 * Rotate the pv chunks list so that we do not
2771 * scan the same pv chunks that could not be
2772 * freed (because they contained a wired
2773 * and/or superpage mapping) on every
2774 * invocation of reclaim_pv_chunk().
2776 while ((pc = TAILQ_FIRST(&pvc->pvc_list)) != pc_marker){
2777 MPASS(pc->pc_pmap != NULL);
2778 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
2779 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
2783 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
2784 TAILQ_REMOVE(&pvc->pvc_list, pc_marker_end, pc_lru);
2785 pvc->active_reclaims--;
2786 mtx_unlock(&pvc->pvc_lock);
2787 if (pmap != NULL && pmap != locked_pmap)
2789 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
2790 m_pc = SLIST_FIRST(&free);
2791 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2792 /* Recycle a freed page table page. */
2793 m_pc->ref_count = 1;
2795 vm_page_free_pages_toq(&free, true);
2800 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
2805 domain = PCPU_GET(domain);
2806 for (i = 0; i < vm_ndomains; i++) {
2807 m = reclaim_pv_chunk_domain(locked_pmap, lockp, domain);
2810 domain = (domain + 1) % vm_ndomains;
2817 * free the pv_entry back to the free list
2820 free_pv_entry(pmap_t pmap, pv_entry_t pv)
2822 struct pv_chunk *pc;
2823 int idx, field, bit;
2825 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2826 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
2827 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
2828 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
2829 pc = pv_to_chunk(pv);
2830 idx = pv - &pc->pc_pventry[0];
2833 pc->pc_map[field] |= 1ul << bit;
2834 if (!pc_is_free(pc)) {
2835 /* 98% of the time, pc is already at the head of the list. */
2836 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
2837 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2838 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2842 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2847 free_pv_chunk_dequeued(struct pv_chunk *pc)
2851 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
2852 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
2853 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
2854 /* entire chunk is free, return it */
2855 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
2856 dump_drop_page(m->phys_addr);
2857 vm_page_unwire_noq(m);
2862 free_pv_chunk(struct pv_chunk *pc)
2864 struct pv_chunks_list *pvc;
2866 pvc = &pv_chunks[pc_to_domain(pc)];
2867 mtx_lock(&pvc->pvc_lock);
2868 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
2869 mtx_unlock(&pvc->pvc_lock);
2870 free_pv_chunk_dequeued(pc);
2874 free_pv_chunk_batch(struct pv_chunklist *batch)
2876 struct pv_chunks_list *pvc;
2877 struct pv_chunk *pc, *npc;
2880 for (i = 0; i < vm_ndomains; i++) {
2881 if (TAILQ_EMPTY(&batch[i]))
2883 pvc = &pv_chunks[i];
2884 mtx_lock(&pvc->pvc_lock);
2885 TAILQ_FOREACH(pc, &batch[i], pc_list) {
2886 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
2888 mtx_unlock(&pvc->pvc_lock);
2891 for (i = 0; i < vm_ndomains; i++) {
2892 TAILQ_FOREACH_SAFE(pc, &batch[i], pc_list, npc) {
2893 free_pv_chunk_dequeued(pc);
2899 * Returns a new PV entry, allocating a new PV chunk from the system when
2900 * needed. If this PV chunk allocation fails and a PV list lock pointer was
2901 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
2904 * The given PV list lock may be released.
2907 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
2909 struct pv_chunks_list *pvc;
2912 struct pv_chunk *pc;
2915 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2916 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
2918 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
2920 for (field = 0; field < _NPCM; field++) {
2921 if (pc->pc_map[field]) {
2922 bit = ffsl(pc->pc_map[field]) - 1;
2926 if (field < _NPCM) {
2927 pv = &pc->pc_pventry[field * 64 + bit];
2928 pc->pc_map[field] &= ~(1ul << bit);
2929 /* If this was the last item, move it to tail */
2930 if (pc_is_full(pc)) {
2931 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2932 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
2935 PV_STAT(atomic_add_long(&pv_entry_count, 1));
2936 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
2940 /* No free items, allocate another chunk */
2941 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
2943 if (lockp == NULL) {
2944 PV_STAT(pc_chunk_tryfail++);
2947 m = reclaim_pv_chunk(pmap, lockp);
2951 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
2952 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
2953 dump_add_page(m->phys_addr);
2954 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
2956 memcpy(pc->pc_map, pc_freemask, sizeof(pc_freemask));
2957 pc->pc_map[0] &= ~1ul; /* preallocated bit 0 */
2958 pvc = &pv_chunks[vm_page_domain(m)];
2959 mtx_lock(&pvc->pvc_lock);
2960 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
2961 mtx_unlock(&pvc->pvc_lock);
2962 pv = &pc->pc_pventry[0];
2963 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2964 PV_STAT(atomic_add_long(&pv_entry_count, 1));
2965 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
2970 * Ensure that the number of spare PV entries in the specified pmap meets or
2971 * exceeds the given count, "needed".
2973 * The given PV list lock may be released.
2976 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
2978 struct pv_chunks_list *pvc;
2979 struct pch new_tail[PMAP_MEMDOM];
2980 struct pv_chunk *pc;
2985 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2986 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
2989 * Newly allocated PV chunks must be stored in a private list until
2990 * the required number of PV chunks have been allocated. Otherwise,
2991 * reclaim_pv_chunk() could recycle one of these chunks. In
2992 * contrast, these chunks must be added to the pmap upon allocation.
2994 for (i = 0; i < PMAP_MEMDOM; i++)
2995 TAILQ_INIT(&new_tail[i]);
2998 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
2999 bit_count((bitstr_t *)pc->pc_map, 0,
3000 sizeof(pc->pc_map) * NBBY, &free);
3004 if (avail >= needed)
3007 for (reclaimed = false; avail < needed; avail += _NPCPV) {
3008 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
3010 m = reclaim_pv_chunk(pmap, lockp);
3015 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3016 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3017 dump_add_page(m->phys_addr);
3018 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3020 memcpy(pc->pc_map, pc_freemask, sizeof(pc_freemask));
3021 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3022 TAILQ_INSERT_TAIL(&new_tail[vm_page_domain(m)], pc, pc_lru);
3023 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3026 * The reclaim might have freed a chunk from the current pmap.
3027 * If that chunk contained available entries, we need to
3028 * re-count the number of available entries.
3033 for (i = 0; i < vm_ndomains; i++) {
3034 if (TAILQ_EMPTY(&new_tail[i]))
3036 pvc = &pv_chunks[i];
3037 mtx_lock(&pvc->pvc_lock);
3038 TAILQ_CONCAT(&pvc->pvc_list, &new_tail[i], pc_lru);
3039 mtx_unlock(&pvc->pvc_lock);
3044 * First find and then remove the pv entry for the specified pmap and virtual
3045 * address from the specified pv list. Returns the pv entry if found and NULL
3046 * otherwise. This operation can be performed on pv lists for either 4KB or
3047 * 2MB page mappings.
3049 static __inline pv_entry_t
3050 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3054 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3055 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3056 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3065 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3066 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3067 * entries for each of the 4KB page mappings.
3070 pmap_pv_demote_l2(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3071 struct rwlock **lockp)
3073 struct md_page *pvh;
3074 struct pv_chunk *pc;
3076 vm_offset_t va_last;
3080 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3081 KASSERT((va & L2_OFFSET) == 0,
3082 ("pmap_pv_demote_l2: va is not 2mpage aligned"));
3083 KASSERT((pa & L2_OFFSET) == 0,
3084 ("pmap_pv_demote_l2: pa is not 2mpage aligned"));
3085 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3088 * Transfer the 2mpage's pv entry for this mapping to the first
3089 * page's pv list. Once this transfer begins, the pv list lock
3090 * must not be released until the last pv entry is reinstantiated.
3092 pvh = pa_to_pvh(pa);
3093 pv = pmap_pvh_remove(pvh, pmap, va);
3094 KASSERT(pv != NULL, ("pmap_pv_demote_l2: pv not found"));
3095 m = PHYS_TO_VM_PAGE(pa);
3096 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3098 /* Instantiate the remaining Ln_ENTRIES - 1 pv entries. */
3099 PV_STAT(atomic_add_long(&pv_entry_allocs, Ln_ENTRIES - 1));
3100 va_last = va + L2_SIZE - PAGE_SIZE;
3102 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3103 KASSERT(!pc_is_full(pc), ("pmap_pv_demote_l2: missing spare"));
3104 for (field = 0; field < _NPCM; field++) {
3105 while (pc->pc_map[field]) {
3106 bit = ffsl(pc->pc_map[field]) - 1;
3107 pc->pc_map[field] &= ~(1ul << bit);
3108 pv = &pc->pc_pventry[field * 64 + bit];
3112 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3113 ("pmap_pv_demote_l2: page %p is not managed", m));
3114 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3120 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3121 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3124 if (pc_is_full(pc)) {
3125 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3126 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3128 PV_STAT(atomic_add_long(&pv_entry_count, Ln_ENTRIES - 1));
3129 PV_STAT(atomic_subtract_int(&pv_entry_spare, Ln_ENTRIES - 1));
3133 * First find and then destroy the pv entry for the specified pmap and virtual
3134 * address. This operation can be performed on pv lists for either 4KB or 2MB
3138 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3142 pv = pmap_pvh_remove(pvh, pmap, va);
3143 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3144 free_pv_entry(pmap, pv);
3148 * Conditionally create the PV entry for a 4KB page mapping if the required
3149 * memory can be allocated without resorting to reclamation.
3152 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3153 struct rwlock **lockp)
3157 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3158 /* Pass NULL instead of the lock pointer to disable reclamation. */
3159 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3161 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3162 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3170 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3171 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3172 * false if the PV entry cannot be allocated without resorting to reclamation.
3175 pmap_pv_insert_l2(pmap_t pmap, vm_offset_t va, pd_entry_t l2e, u_int flags,
3176 struct rwlock **lockp)
3178 struct md_page *pvh;
3182 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3183 /* Pass NULL instead of the lock pointer to disable reclamation. */
3184 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3185 NULL : lockp)) == NULL)
3188 pa = l2e & ~ATTR_MASK;
3189 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3190 pvh = pa_to_pvh(pa);
3191 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3197 pmap_remove_kernel_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va)
3199 pt_entry_t newl2, oldl2 __diagused;
3203 KASSERT(!VIRT_IN_DMAP(va), ("removing direct mapping of %#lx", va));
3204 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3205 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3207 ml3 = pmap_remove_pt_page(pmap, va);
3209 panic("pmap_remove_kernel_l2: Missing pt page");
3211 ml3pa = VM_PAGE_TO_PHYS(ml3);
3212 newl2 = ml3pa | L2_TABLE;
3215 * If this page table page was unmapped by a promotion, then it
3216 * contains valid mappings. Zero it to invalidate those mappings.
3218 if (ml3->valid != 0)
3219 pagezero((void *)PHYS_TO_DMAP(ml3pa));
3222 * Demote the mapping. The caller must have already invalidated the
3223 * mapping (i.e., the "break" in break-before-make).
3225 oldl2 = pmap_load_store(l2, newl2);
3226 KASSERT(oldl2 == 0, ("%s: found existing mapping at %p: %#lx",
3227 __func__, l2, oldl2));
3231 * pmap_remove_l2: Do the things to unmap a level 2 superpage.
3234 pmap_remove_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva,
3235 pd_entry_t l1e, struct spglist *free, struct rwlock **lockp)
3237 struct md_page *pvh;
3239 vm_page_t m, ml3, mt;
3241 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3242 KASSERT((sva & L2_OFFSET) == 0, ("pmap_remove_l2: sva is not aligned"));
3243 old_l2 = pmap_load_clear(l2);
3244 KASSERT((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK,
3245 ("pmap_remove_l2: L2e %lx is not a block mapping", old_l2));
3248 * Since a promotion must break the 4KB page mappings before making
3249 * the 2MB page mapping, a pmap_s1_invalidate_page() suffices.
3251 pmap_s1_invalidate_page(pmap, sva, true);
3253 if (old_l2 & ATTR_SW_WIRED)
3254 pmap->pm_stats.wired_count -= L2_SIZE / PAGE_SIZE;
3255 pmap_resident_count_dec(pmap, L2_SIZE / PAGE_SIZE);
3256 if (old_l2 & ATTR_SW_MANAGED) {
3257 m = PHYS_TO_VM_PAGE(old_l2 & ~ATTR_MASK);
3258 pvh = page_to_pvh(m);
3259 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, old_l2 & ~ATTR_MASK);
3260 pmap_pvh_free(pvh, pmap, sva);
3261 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++) {
3262 if (pmap_pte_dirty(pmap, old_l2))
3264 if (old_l2 & ATTR_AF)
3265 vm_page_aflag_set(mt, PGA_REFERENCED);
3266 if (TAILQ_EMPTY(&mt->md.pv_list) &&
3267 TAILQ_EMPTY(&pvh->pv_list))
3268 vm_page_aflag_clear(mt, PGA_WRITEABLE);
3271 if (pmap == kernel_pmap) {
3272 pmap_remove_kernel_l2(pmap, l2, sva);
3274 ml3 = pmap_remove_pt_page(pmap, sva);
3276 KASSERT(ml3->valid == VM_PAGE_BITS_ALL,
3277 ("pmap_remove_l2: l3 page not promoted"));
3278 pmap_resident_count_dec(pmap, 1);
3279 KASSERT(ml3->ref_count == NL3PG,
3280 ("pmap_remove_l2: l3 page ref count error"));
3282 pmap_add_delayed_free_list(ml3, free, FALSE);
3285 return (pmap_unuse_pt(pmap, sva, l1e, free));
3289 * pmap_remove_l3: do the things to unmap a page in a process
3292 pmap_remove_l3(pmap_t pmap, pt_entry_t *l3, vm_offset_t va,
3293 pd_entry_t l2e, struct spglist *free, struct rwlock **lockp)
3295 struct md_page *pvh;
3299 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3300 old_l3 = pmap_load_clear(l3);
3301 pmap_s1_invalidate_page(pmap, va, true);
3302 if (old_l3 & ATTR_SW_WIRED)
3303 pmap->pm_stats.wired_count -= 1;
3304 pmap_resident_count_dec(pmap, 1);
3305 if (old_l3 & ATTR_SW_MANAGED) {
3306 m = PHYS_TO_VM_PAGE(old_l3 & ~ATTR_MASK);
3307 if (pmap_pte_dirty(pmap, old_l3))
3309 if (old_l3 & ATTR_AF)
3310 vm_page_aflag_set(m, PGA_REFERENCED);
3311 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3312 pmap_pvh_free(&m->md, pmap, va);
3313 if (TAILQ_EMPTY(&m->md.pv_list) &&
3314 (m->flags & PG_FICTITIOUS) == 0) {
3315 pvh = page_to_pvh(m);
3316 if (TAILQ_EMPTY(&pvh->pv_list))
3317 vm_page_aflag_clear(m, PGA_WRITEABLE);
3320 return (pmap_unuse_pt(pmap, va, l2e, free));
3324 * Remove the specified range of addresses from the L3 page table that is
3325 * identified by the given L2 entry.
3328 pmap_remove_l3_range(pmap_t pmap, pd_entry_t l2e, vm_offset_t sva,
3329 vm_offset_t eva, struct spglist *free, struct rwlock **lockp)
3331 struct md_page *pvh;
3332 struct rwlock *new_lock;
3333 pt_entry_t *l3, old_l3;
3337 KASSERT(ADDR_IS_CANONICAL(sva),
3338 ("%s: Start address not in canonical form: %lx", __func__, sva));
3339 KASSERT(ADDR_IS_CANONICAL(eva) || eva == VM_MAX_USER_ADDRESS,
3340 ("%s: End address not in canonical form: %lx", __func__, eva));
3342 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3343 KASSERT(rounddown2(sva, L2_SIZE) + L2_SIZE == roundup2(eva, L2_SIZE),
3344 ("pmap_remove_l3_range: range crosses an L3 page table boundary"));
3345 l3pg = !ADDR_IS_KERNEL(sva) ? PHYS_TO_VM_PAGE(l2e & ~ATTR_MASK) : NULL;
3347 for (l3 = pmap_l2_to_l3(&l2e, sva); sva != eva; l3++, sva += L3_SIZE) {
3348 if (!pmap_l3_valid(pmap_load(l3))) {
3350 pmap_s1_invalidate_range(pmap, va, sva, true);
3355 old_l3 = pmap_load_clear(l3);
3356 if ((old_l3 & ATTR_SW_WIRED) != 0)
3357 pmap->pm_stats.wired_count--;
3358 pmap_resident_count_dec(pmap, 1);
3359 if ((old_l3 & ATTR_SW_MANAGED) != 0) {
3360 m = PHYS_TO_VM_PAGE(old_l3 & ~ATTR_MASK);
3361 if (pmap_pte_dirty(pmap, old_l3))
3363 if ((old_l3 & ATTR_AF) != 0)
3364 vm_page_aflag_set(m, PGA_REFERENCED);
3365 new_lock = PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m));
3366 if (new_lock != *lockp) {
3367 if (*lockp != NULL) {
3369 * Pending TLB invalidations must be
3370 * performed before the PV list lock is
3371 * released. Otherwise, a concurrent
3372 * pmap_remove_all() on a physical page
3373 * could return while a stale TLB entry
3374 * still provides access to that page.
3377 pmap_s1_invalidate_range(pmap, va,
3386 pmap_pvh_free(&m->md, pmap, sva);
3387 if (TAILQ_EMPTY(&m->md.pv_list) &&
3388 (m->flags & PG_FICTITIOUS) == 0) {
3389 pvh = page_to_pvh(m);
3390 if (TAILQ_EMPTY(&pvh->pv_list))
3391 vm_page_aflag_clear(m, PGA_WRITEABLE);
3394 if (l3pg != NULL && pmap_unwire_l3(pmap, sva, l3pg, free)) {
3396 * _pmap_unwire_l3() has already invalidated the TLB
3397 * entries at all levels for "sva". So, we need not
3398 * perform "sva += L3_SIZE;" here. Moreover, we need
3399 * not perform "va = sva;" if "sva" is at the start
3400 * of a new valid range consisting of a single page.
3408 pmap_s1_invalidate_range(pmap, va, sva, true);
3412 * Remove the given range of addresses from the specified map.
3414 * It is assumed that the start and end are properly
3415 * rounded to the page size.
3418 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3420 struct rwlock *lock;
3421 vm_offset_t va_next;
3422 pd_entry_t *l0, *l1, *l2;
3423 pt_entry_t l3_paddr;
3424 struct spglist free;
3427 * Perform an unsynchronized read. This is, however, safe.
3429 if (pmap->pm_stats.resident_count == 0)
3437 for (; sva < eva; sva = va_next) {
3438 if (pmap->pm_stats.resident_count == 0)
3441 l0 = pmap_l0(pmap, sva);
3442 if (pmap_load(l0) == 0) {
3443 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
3449 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
3452 l1 = pmap_l0_to_l1(l0, sva);
3453 if (pmap_load(l1) == 0)
3455 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
3456 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
3457 KASSERT(va_next <= eva,
3458 ("partial update of non-transparent 1G page "
3459 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
3460 pmap_load(l1), sva, eva, va_next));
3461 MPASS(pmap != kernel_pmap);
3462 MPASS((pmap_load(l1) & ATTR_SW_MANAGED) == 0);
3464 pmap_s1_invalidate_page(pmap, sva, true);
3465 pmap_resident_count_dec(pmap, L1_SIZE / PAGE_SIZE);
3466 pmap_unuse_pt(pmap, sva, pmap_load(l0), &free);
3471 * Calculate index for next page table.
3473 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
3477 l2 = pmap_l1_to_l2(l1, sva);
3481 l3_paddr = pmap_load(l2);
3483 if ((l3_paddr & ATTR_DESCR_MASK) == L2_BLOCK) {
3484 if (sva + L2_SIZE == va_next && eva >= va_next) {
3485 pmap_remove_l2(pmap, l2, sva, pmap_load(l1),
3488 } else if (pmap_demote_l2_locked(pmap, l2, sva,
3491 l3_paddr = pmap_load(l2);
3495 * Weed out invalid mappings.
3497 if ((l3_paddr & ATTR_DESCR_MASK) != L2_TABLE)
3501 * Limit our scan to either the end of the va represented
3502 * by the current page table page, or to the end of the
3503 * range being removed.
3508 pmap_remove_l3_range(pmap, l3_paddr, sva, va_next, &free,
3514 vm_page_free_pages_toq(&free, true);
3518 * Routine: pmap_remove_all
3520 * Removes this physical page from
3521 * all physical maps in which it resides.
3522 * Reflects back modify bits to the pager.
3525 * Original versions of this routine were very
3526 * inefficient because they iteratively called
3527 * pmap_remove (slow...)
3531 pmap_remove_all(vm_page_t m)
3533 struct md_page *pvh;
3536 struct rwlock *lock;
3537 pd_entry_t *pde, tpde;
3538 pt_entry_t *pte, tpte;
3540 struct spglist free;
3541 int lvl, pvh_gen, md_gen;
3543 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3544 ("pmap_remove_all: page %p is not managed", m));
3546 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3547 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
3550 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
3552 if (!PMAP_TRYLOCK(pmap)) {
3553 pvh_gen = pvh->pv_gen;
3557 if (pvh_gen != pvh->pv_gen) {
3563 pte = pmap_pte_exists(pmap, va, 2, __func__);
3564 pmap_demote_l2_locked(pmap, pte, va, &lock);
3567 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3569 PMAP_ASSERT_STAGE1(pmap);
3570 if (!PMAP_TRYLOCK(pmap)) {
3571 pvh_gen = pvh->pv_gen;
3572 md_gen = m->md.pv_gen;
3576 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
3581 pmap_resident_count_dec(pmap, 1);
3583 pde = pmap_pde(pmap, pv->pv_va, &lvl);
3584 KASSERT(pde != NULL,
3585 ("pmap_remove_all: no page directory entry found"));
3587 ("pmap_remove_all: invalid pde level %d", lvl));
3588 tpde = pmap_load(pde);
3590 pte = pmap_l2_to_l3(pde, pv->pv_va);
3591 tpte = pmap_load_clear(pte);
3592 if (tpte & ATTR_SW_WIRED)
3593 pmap->pm_stats.wired_count--;
3594 if ((tpte & ATTR_AF) != 0) {
3595 pmap_s1_invalidate_page(pmap, pv->pv_va, true);
3596 vm_page_aflag_set(m, PGA_REFERENCED);
3600 * Update the vm_page_t clean and reference bits.
3602 if (pmap_pte_dirty(pmap, tpte))
3604 pmap_unuse_pt(pmap, pv->pv_va, tpde, &free);
3605 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3607 free_pv_entry(pmap, pv);
3610 vm_page_aflag_clear(m, PGA_WRITEABLE);
3612 vm_page_free_pages_toq(&free, true);
3616 * Masks and sets bits in a level 2 page table entries in the specified pmap
3619 pmap_protect_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva, pt_entry_t mask,
3625 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3626 PMAP_ASSERT_STAGE1(pmap);
3627 KASSERT((sva & L2_OFFSET) == 0,
3628 ("pmap_protect_l2: sva is not 2mpage aligned"));
3629 old_l2 = pmap_load(l2);
3630 KASSERT((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK,
3631 ("pmap_protect_l2: L2e %lx is not a block mapping", old_l2));
3634 * Return if the L2 entry already has the desired access restrictions
3637 if ((old_l2 & mask) == nbits)
3640 while (!atomic_fcmpset_64(l2, &old_l2, (old_l2 & ~mask) | nbits))
3644 * When a dirty read/write superpage mapping is write protected,
3645 * update the dirty field of each of the superpage's constituent 4KB
3648 if ((old_l2 & ATTR_SW_MANAGED) != 0 &&
3649 (nbits & ATTR_S1_AP(ATTR_S1_AP_RO)) != 0 &&
3650 pmap_pte_dirty(pmap, old_l2)) {
3651 m = PHYS_TO_VM_PAGE(old_l2 & ~ATTR_MASK);
3652 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
3657 * Since a promotion must break the 4KB page mappings before making
3658 * the 2MB page mapping, a pmap_s1_invalidate_page() suffices.
3660 pmap_s1_invalidate_page(pmap, sva, true);
3664 * Masks and sets bits in last level page table entries in the specified
3668 pmap_mask_set(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, pt_entry_t mask,
3669 pt_entry_t nbits, bool invalidate)
3671 vm_offset_t va, va_next;
3672 pd_entry_t *l0, *l1, *l2;
3673 pt_entry_t *l3p, l3;
3676 for (; sva < eva; sva = va_next) {
3677 l0 = pmap_l0(pmap, sva);
3678 if (pmap_load(l0) == 0) {
3679 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
3685 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
3688 l1 = pmap_l0_to_l1(l0, sva);
3689 if (pmap_load(l1) == 0)
3691 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
3692 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
3693 KASSERT(va_next <= eva,
3694 ("partial update of non-transparent 1G page "
3695 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
3696 pmap_load(l1), sva, eva, va_next));
3697 MPASS((pmap_load(l1) & ATTR_SW_MANAGED) == 0);
3698 if ((pmap_load(l1) & mask) != nbits) {
3699 pmap_store(l1, (pmap_load(l1) & ~mask) | nbits);
3701 pmap_s1_invalidate_page(pmap, sva, true);
3706 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
3710 l2 = pmap_l1_to_l2(l1, sva);
3711 if (pmap_load(l2) == 0)
3714 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK) {
3715 if (sva + L2_SIZE == va_next && eva >= va_next) {
3716 pmap_protect_l2(pmap, l2, sva, mask, nbits);
3718 } else if (pmap_demote_l2(pmap, l2, sva) == NULL)
3721 KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
3722 ("pmap_protect: Invalid L2 entry after demotion"));
3728 for (l3p = pmap_l2_to_l3(l2, sva); sva != va_next; l3p++,
3730 l3 = pmap_load(l3p);
3733 * Go to the next L3 entry if the current one is
3734 * invalid or already has the desired access
3735 * restrictions in place. (The latter case occurs
3736 * frequently. For example, in a "buildworld"
3737 * workload, almost 1 out of 4 L3 entries already
3738 * have the desired restrictions.)
3740 if (!pmap_l3_valid(l3) || (l3 & mask) == nbits) {
3741 if (va != va_next) {
3743 pmap_s1_invalidate_range(pmap,
3750 while (!atomic_fcmpset_64(l3p, &l3, (l3 & ~mask) |
3755 * When a dirty read/write mapping is write protected,
3756 * update the page's dirty field.
3758 if ((l3 & ATTR_SW_MANAGED) != 0 &&
3759 (nbits & ATTR_S1_AP(ATTR_S1_AP_RO)) != 0 &&
3760 pmap_pte_dirty(pmap, l3))
3761 vm_page_dirty(PHYS_TO_VM_PAGE(l3 & ~ATTR_MASK));
3766 if (va != va_next && invalidate)
3767 pmap_s1_invalidate_range(pmap, va, sva, true);
3773 * Set the physical protection on the
3774 * specified range of this map as requested.
3777 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
3779 pt_entry_t mask, nbits;
3781 PMAP_ASSERT_STAGE1(pmap);
3782 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
3783 if (prot == VM_PROT_NONE) {
3784 pmap_remove(pmap, sva, eva);
3789 if ((prot & VM_PROT_WRITE) == 0) {
3790 mask |= ATTR_S1_AP_RW_BIT | ATTR_SW_DBM;
3791 nbits |= ATTR_S1_AP(ATTR_S1_AP_RO);
3793 if ((prot & VM_PROT_EXECUTE) == 0) {
3795 nbits |= ATTR_S1_XN;
3800 pmap_mask_set(pmap, sva, eva, mask, nbits, true);
3804 pmap_disable_promotion(vm_offset_t sva, vm_size_t size)
3807 MPASS((sva & L3_OFFSET) == 0);
3808 MPASS(((sva + size) & L3_OFFSET) == 0);
3810 pmap_mask_set(kernel_pmap, sva, sva + size, ATTR_SW_NO_PROMOTE,
3811 ATTR_SW_NO_PROMOTE, false);
3815 * Inserts the specified page table page into the specified pmap's collection
3816 * of idle page table pages. Each of a pmap's page table pages is responsible
3817 * for mapping a distinct range of virtual addresses. The pmap's collection is
3818 * ordered by this virtual address range.
3820 * If "promoted" is false, then the page table page "mpte" must be zero filled.
3823 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted)
3826 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3827 mpte->valid = promoted ? VM_PAGE_BITS_ALL : 0;
3828 return (vm_radix_insert(&pmap->pm_root, mpte));
3832 * Removes the page table page mapping the specified virtual address from the
3833 * specified pmap's collection of idle page table pages, and returns it.
3834 * Otherwise, returns NULL if there is no page table page corresponding to the
3835 * specified virtual address.
3837 static __inline vm_page_t
3838 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
3841 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3842 return (vm_radix_remove(&pmap->pm_root, pmap_l2_pindex(va)));
3846 * Performs a break-before-make update of a pmap entry. This is needed when
3847 * either promoting or demoting pages to ensure the TLB doesn't get into an
3848 * inconsistent state.
3851 pmap_update_entry(pmap_t pmap, pd_entry_t *pte, pd_entry_t newpte,
3852 vm_offset_t va, vm_size_t size)
3856 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3858 if ((newpte & ATTR_SW_NO_PROMOTE) != 0)
3859 panic("%s: Updating non-promote pte", __func__);
3862 * Ensure we don't get switched out with the page table in an
3863 * inconsistent state. We also need to ensure no interrupts fire
3864 * as they may make use of an address we are about to invalidate.
3866 intr = intr_disable();
3869 * Clear the old mapping's valid bit, but leave the rest of the entry
3870 * unchanged, so that a lockless, concurrent pmap_kextract() can still
3871 * lookup the physical address.
3873 pmap_clear_bits(pte, ATTR_DESCR_VALID);
3876 * When promoting, the L{1,2}_TABLE entry that is being replaced might
3877 * be cached, so we invalidate intermediate entries as well as final
3880 pmap_s1_invalidate_range(pmap, va, va + size, false);
3882 /* Create the new mapping */
3883 pmap_store(pte, newpte);
3889 #if VM_NRESERVLEVEL > 0
3891 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3892 * replace the many pv entries for the 4KB page mappings by a single pv entry
3893 * for the 2MB page mapping.
3896 pmap_pv_promote_l2(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3897 struct rwlock **lockp)
3899 struct md_page *pvh;
3901 vm_offset_t va_last;
3904 KASSERT((pa & L2_OFFSET) == 0,
3905 ("pmap_pv_promote_l2: pa is not 2mpage aligned"));
3906 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3909 * Transfer the first page's pv entry for this mapping to the 2mpage's
3910 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3911 * a transfer avoids the possibility that get_pv_entry() calls
3912 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3913 * mappings that is being promoted.
3915 m = PHYS_TO_VM_PAGE(pa);
3916 va = va & ~L2_OFFSET;
3917 pv = pmap_pvh_remove(&m->md, pmap, va);
3918 KASSERT(pv != NULL, ("pmap_pv_promote_l2: pv not found"));
3919 pvh = page_to_pvh(m);
3920 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3922 /* Free the remaining NPTEPG - 1 pv entries. */
3923 va_last = va + L2_SIZE - PAGE_SIZE;
3927 pmap_pvh_free(&m->md, pmap, va);
3928 } while (va < va_last);
3932 * Tries to promote the 512, contiguous 4KB page mappings that are within a
3933 * single level 2 table entry to a single 2MB page mapping. For promotion
3934 * to occur, two conditions must be met: (1) the 4KB page mappings must map
3935 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
3936 * identical characteristics.
3939 pmap_promote_l2(pmap_t pmap, pd_entry_t *l2, vm_offset_t va, vm_page_t mpte,
3940 struct rwlock **lockp)
3942 pt_entry_t *firstl3, *l3, newl2, oldl3, pa;
3944 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3945 PMAP_ASSERT_STAGE1(pmap);
3948 * Examine the first L3E in the specified PTP. Abort if this L3E is
3949 * ineligible for promotion, invalid, or does not map the first 4KB
3950 * physical page within a 2MB page.
3952 firstl3 = (pt_entry_t *)PHYS_TO_DMAP(pmap_load(l2) & ~ATTR_MASK);
3953 newl2 = pmap_load(firstl3);
3954 if ((newl2 & ATTR_SW_NO_PROMOTE) != 0)
3956 if ((newl2 & ((~ATTR_MASK & L2_OFFSET) | ATTR_DESCR_MASK)) != L3_PAGE) {
3957 atomic_add_long(&pmap_l2_p_failures, 1);
3958 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
3959 " in pmap %p", va, pmap);
3964 * Both here and in the below "for" loop, to allow for repromotion
3965 * after MADV_FREE, conditionally write protect a clean L3E before
3966 * possibly aborting the promotion due to other L3E attributes. Why?
3967 * Suppose that MADV_FREE is applied to a part of a superpage, the
3968 * address range [S, E). pmap_advise() will demote the superpage
3969 * mapping, destroy the 4KB page mapping at the end of [S, E), and
3970 * set AP_RO and clear AF in the L3Es for the rest of [S, E). Later,
3971 * imagine that the memory in [S, E) is recycled, but the last 4KB
3972 * page in [S, E) is not the last to be rewritten, or simply accessed.
3973 * In other words, there is still a 4KB page in [S, E), call it P,
3974 * that is writeable but AP_RO is set and AF is clear in P's L3E.
3975 * Unless we write protect P before aborting the promotion, if and
3976 * when P is finally rewritten, there won't be a page fault to trigger
3980 if ((newl2 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
3981 (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM)) {
3983 * When the mapping is clean, i.e., ATTR_S1_AP_RO is set,
3984 * ATTR_SW_DBM can be cleared without a TLB invalidation.
3986 if (!atomic_fcmpset_64(firstl3, &newl2, newl2 & ~ATTR_SW_DBM))
3988 newl2 &= ~ATTR_SW_DBM;
3990 if ((newl2 & ATTR_AF) == 0) {
3991 atomic_add_long(&pmap_l2_p_failures, 1);
3992 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
3993 " in pmap %p", va, pmap);
3998 * Examine each of the other L3Es in the specified PTP. Abort if this
3999 * L3E maps an unexpected 4KB physical page or does not have identical
4000 * characteristics to the first L3E.
4002 pa = (newl2 & (~ATTR_MASK | ATTR_DESCR_MASK)) + L2_SIZE - PAGE_SIZE;
4003 for (l3 = firstl3 + NL3PG - 1; l3 > firstl3; l3--) {
4004 oldl3 = pmap_load(l3);
4005 if ((oldl3 & (~ATTR_MASK | ATTR_DESCR_MASK)) != pa) {
4006 atomic_add_long(&pmap_l2_p_failures, 1);
4007 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
4008 " in pmap %p", va, pmap);
4012 if ((oldl3 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
4013 (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM)) {
4015 * When the mapping is clean, i.e., ATTR_S1_AP_RO is
4016 * set, ATTR_SW_DBM can be cleared without a TLB
4019 if (!atomic_fcmpset_64(l3, &oldl3, oldl3 &
4022 oldl3 &= ~ATTR_SW_DBM;
4024 if ((oldl3 & ATTR_MASK) != (newl2 & ATTR_MASK)) {
4025 atomic_add_long(&pmap_l2_p_failures, 1);
4026 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
4027 " in pmap %p", va, pmap);
4034 * Save the page table page in its current state until the L2
4035 * mapping the superpage is demoted by pmap_demote_l2() or
4036 * destroyed by pmap_remove_l3().
4039 mpte = PHYS_TO_VM_PAGE(pmap_load(l2) & ~ATTR_MASK);
4040 KASSERT(mpte >= vm_page_array &&
4041 mpte < &vm_page_array[vm_page_array_size],
4042 ("pmap_promote_l2: page table page is out of range"));
4043 KASSERT(mpte->pindex == pmap_l2_pindex(va),
4044 ("pmap_promote_l2: page table page's pindex is wrong"));
4045 if (pmap_insert_pt_page(pmap, mpte, true)) {
4046 atomic_add_long(&pmap_l2_p_failures, 1);
4048 "pmap_promote_l2: failure for va %#lx in pmap %p", va,
4053 if ((newl2 & ATTR_SW_MANAGED) != 0)
4054 pmap_pv_promote_l2(pmap, va, newl2 & ~ATTR_MASK, lockp);
4056 newl2 &= ~ATTR_DESCR_MASK;
4059 pmap_update_entry(pmap, l2, newl2, va & ~L2_OFFSET, L2_SIZE);
4061 atomic_add_long(&pmap_l2_promotions, 1);
4062 CTR2(KTR_PMAP, "pmap_promote_l2: success for va %#lx in pmap %p", va,
4065 #endif /* VM_NRESERVLEVEL > 0 */
4068 pmap_enter_largepage(pmap_t pmap, vm_offset_t va, pt_entry_t newpte, int flags,
4071 pd_entry_t *l0p, *l1p, *l2p, origpte;
4074 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4075 KASSERT(psind > 0 && psind < MAXPAGESIZES,
4076 ("psind %d unexpected", psind));
4077 KASSERT(((newpte & ~ATTR_MASK) & (pagesizes[psind] - 1)) == 0,
4078 ("unaligned phys address %#lx newpte %#lx psind %d",
4079 (newpte & ~ATTR_MASK), newpte, psind));
4083 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
4085 l0p = pmap_l0(pmap, va);
4086 if ((pmap_load(l0p) & ATTR_DESCR_VALID) == 0) {
4087 mp = _pmap_alloc_l3(pmap, pmap_l0_pindex(va), NULL);
4089 if ((flags & PMAP_ENTER_NOSLEEP) != 0)
4090 return (KERN_RESOURCE_SHORTAGE);
4096 l1p = pmap_l0_to_l1(l0p, va);
4097 KASSERT(l1p != NULL, ("va %#lx lost l1 entry", va));
4098 origpte = pmap_load(l1p);
4100 l1p = pmap_l0_to_l1(l0p, va);
4101 KASSERT(l1p != NULL, ("va %#lx lost l1 entry", va));
4102 origpte = pmap_load(l1p);
4103 if ((origpte & ATTR_DESCR_VALID) == 0) {
4104 mp = PHYS_TO_VM_PAGE(pmap_load(l0p) &
4109 KASSERT(((origpte & ~ATTR_MASK) == (newpte & ~ATTR_MASK) &&
4110 (origpte & ATTR_DESCR_MASK) == L1_BLOCK) ||
4111 (origpte & ATTR_DESCR_VALID) == 0,
4112 ("va %#lx changing 1G phys page l1 %#lx newpte %#lx",
4113 va, origpte, newpte));
4114 pmap_store(l1p, newpte);
4115 } else /* (psind == 1) */ {
4116 l2p = pmap_l2(pmap, va);
4118 mp = _pmap_alloc_l3(pmap, pmap_l1_pindex(va), NULL);
4120 if ((flags & PMAP_ENTER_NOSLEEP) != 0)
4121 return (KERN_RESOURCE_SHORTAGE);
4127 l2p = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
4128 l2p = &l2p[pmap_l2_index(va)];
4129 origpte = pmap_load(l2p);
4131 l1p = pmap_l1(pmap, va);
4132 origpte = pmap_load(l2p);
4133 if ((origpte & ATTR_DESCR_VALID) == 0) {
4134 mp = PHYS_TO_VM_PAGE(pmap_load(l1p) &
4139 KASSERT((origpte & ATTR_DESCR_VALID) == 0 ||
4140 ((origpte & ATTR_DESCR_MASK) == L2_BLOCK &&
4141 (origpte & ~ATTR_MASK) == (newpte & ~ATTR_MASK)),
4142 ("va %#lx changing 2M phys page l2 %#lx newpte %#lx",
4143 va, origpte, newpte));
4144 pmap_store(l2p, newpte);
4148 if ((origpte & ATTR_DESCR_VALID) == 0)
4149 pmap_resident_count_inc(pmap, pagesizes[psind] / PAGE_SIZE);
4150 if ((newpte & ATTR_SW_WIRED) != 0 && (origpte & ATTR_SW_WIRED) == 0)
4151 pmap->pm_stats.wired_count += pagesizes[psind] / PAGE_SIZE;
4152 else if ((newpte & ATTR_SW_WIRED) == 0 &&
4153 (origpte & ATTR_SW_WIRED) != 0)
4154 pmap->pm_stats.wired_count -= pagesizes[psind] / PAGE_SIZE;
4156 return (KERN_SUCCESS);
4160 * Insert the given physical page (p) at
4161 * the specified virtual address (v) in the
4162 * target physical map with the protection requested.
4164 * If specified, the page will be wired down, meaning
4165 * that the related pte can not be reclaimed.
4167 * NB: This is the only routine which MAY NOT lazy-evaluate
4168 * or lose information. That is, this routine must actually
4169 * insert this page into the given map NOW.
4172 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4173 u_int flags, int8_t psind)
4175 struct rwlock *lock;
4177 pt_entry_t new_l3, orig_l3;
4178 pt_entry_t *l2, *l3;
4185 KASSERT(ADDR_IS_CANONICAL(va),
4186 ("%s: Address not in canonical form: %lx", __func__, va));
4188 va = trunc_page(va);
4189 if ((m->oflags & VPO_UNMANAGED) == 0)
4190 VM_PAGE_OBJECT_BUSY_ASSERT(m);
4191 pa = VM_PAGE_TO_PHYS(m);
4192 new_l3 = (pt_entry_t)(pa | ATTR_DEFAULT | L3_PAGE);
4193 new_l3 |= pmap_pte_memattr(pmap, m->md.pv_memattr);
4194 new_l3 |= pmap_pte_prot(pmap, prot);
4196 if ((flags & PMAP_ENTER_WIRED) != 0)
4197 new_l3 |= ATTR_SW_WIRED;
4198 if (pmap->pm_stage == PM_STAGE1) {
4199 if (!ADDR_IS_KERNEL(va))
4200 new_l3 |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
4202 new_l3 |= ATTR_S1_UXN;
4203 if (pmap != kernel_pmap)
4204 new_l3 |= ATTR_S1_nG;
4207 * Clear the access flag on executable mappings, this will be
4208 * set later when the page is accessed. The fault handler is
4209 * required to invalidate the I-cache.
4211 * TODO: Switch to the valid flag to allow hardware management
4212 * of the access flag. Much of the pmap code assumes the
4213 * valid flag is set and fails to destroy the old page tables
4214 * correctly if it is clear.
4216 if (prot & VM_PROT_EXECUTE)
4219 if ((m->oflags & VPO_UNMANAGED) == 0) {
4220 new_l3 |= ATTR_SW_MANAGED;
4221 if ((prot & VM_PROT_WRITE) != 0) {
4222 new_l3 |= ATTR_SW_DBM;
4223 if ((flags & VM_PROT_WRITE) == 0) {
4224 if (pmap->pm_stage == PM_STAGE1)
4225 new_l3 |= ATTR_S1_AP(ATTR_S1_AP_RO);
4228 ~ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
4233 CTR2(KTR_PMAP, "pmap_enter: %.16lx -> %.16lx", va, pa);
4237 if ((flags & PMAP_ENTER_LARGEPAGE) != 0) {
4238 KASSERT((m->oflags & VPO_UNMANAGED) != 0,
4239 ("managed largepage va %#lx flags %#x", va, flags));
4242 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
4244 } else /* (psind == 1) */
4246 rv = pmap_enter_largepage(pmap, va, new_l3, flags, psind);
4250 /* Assert the required virtual and physical alignment. */
4251 KASSERT((va & L2_OFFSET) == 0, ("pmap_enter: va unaligned"));
4252 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4253 rv = pmap_enter_l2(pmap, va, (new_l3 & ~L3_PAGE) | L2_BLOCK,
4260 * In the case that a page table page is not
4261 * resident, we are creating it here.
4264 pde = pmap_pde(pmap, va, &lvl);
4265 if (pde != NULL && lvl == 2) {
4266 l3 = pmap_l2_to_l3(pde, va);
4267 if (!ADDR_IS_KERNEL(va) && mpte == NULL) {
4268 mpte = PHYS_TO_VM_PAGE(pmap_load(pde) & ~ATTR_MASK);
4272 } else if (pde != NULL && lvl == 1) {
4273 l2 = pmap_l1_to_l2(pde, va);
4274 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK &&
4275 (l3 = pmap_demote_l2_locked(pmap, l2, va, &lock)) != NULL) {
4276 l3 = &l3[pmap_l3_index(va)];
4277 if (!ADDR_IS_KERNEL(va)) {
4278 mpte = PHYS_TO_VM_PAGE(
4279 pmap_load(l2) & ~ATTR_MASK);
4284 /* We need to allocate an L3 table. */
4286 if (!ADDR_IS_KERNEL(va)) {
4287 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4290 * We use _pmap_alloc_l3() instead of pmap_alloc_l3() in order
4291 * to handle the possibility that a superpage mapping for "va"
4292 * was created while we slept.
4294 mpte = _pmap_alloc_l3(pmap, pmap_l2_pindex(va),
4295 nosleep ? NULL : &lock);
4296 if (mpte == NULL && nosleep) {
4297 CTR0(KTR_PMAP, "pmap_enter: mpte == NULL");
4298 rv = KERN_RESOURCE_SHORTAGE;
4303 panic("pmap_enter: missing L3 table for kernel va %#lx", va);
4306 orig_l3 = pmap_load(l3);
4307 opa = orig_l3 & ~ATTR_MASK;
4311 * Is the specified virtual address already mapped?
4313 if (pmap_l3_valid(orig_l3)) {
4315 * Only allow adding new entries on stage 2 tables for now.
4316 * This simplifies cache invalidation as we may need to call
4317 * into EL2 to perform such actions.
4319 PMAP_ASSERT_STAGE1(pmap);
4321 * Wiring change, just update stats. We don't worry about
4322 * wiring PT pages as they remain resident as long as there
4323 * are valid mappings in them. Hence, if a user page is wired,
4324 * the PT page will be also.
4326 if ((flags & PMAP_ENTER_WIRED) != 0 &&
4327 (orig_l3 & ATTR_SW_WIRED) == 0)
4328 pmap->pm_stats.wired_count++;
4329 else if ((flags & PMAP_ENTER_WIRED) == 0 &&
4330 (orig_l3 & ATTR_SW_WIRED) != 0)
4331 pmap->pm_stats.wired_count--;
4334 * Remove the extra PT page reference.
4338 KASSERT(mpte->ref_count > 0,
4339 ("pmap_enter: missing reference to page table page,"
4344 * Has the physical page changed?
4348 * No, might be a protection or wiring change.
4350 if ((orig_l3 & ATTR_SW_MANAGED) != 0 &&
4351 (new_l3 & ATTR_SW_DBM) != 0)
4352 vm_page_aflag_set(m, PGA_WRITEABLE);
4357 * The physical page has changed. Temporarily invalidate
4360 orig_l3 = pmap_load_clear(l3);
4361 KASSERT((orig_l3 & ~ATTR_MASK) == opa,
4362 ("pmap_enter: unexpected pa update for %#lx", va));
4363 if ((orig_l3 & ATTR_SW_MANAGED) != 0) {
4364 om = PHYS_TO_VM_PAGE(opa);
4367 * The pmap lock is sufficient to synchronize with
4368 * concurrent calls to pmap_page_test_mappings() and
4369 * pmap_ts_referenced().
4371 if (pmap_pte_dirty(pmap, orig_l3))
4373 if ((orig_l3 & ATTR_AF) != 0) {
4374 pmap_s1_invalidate_page(pmap, va, true);
4375 vm_page_aflag_set(om, PGA_REFERENCED);
4377 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4378 pv = pmap_pvh_remove(&om->md, pmap, va);
4379 if ((m->oflags & VPO_UNMANAGED) != 0)
4380 free_pv_entry(pmap, pv);
4381 if ((om->a.flags & PGA_WRITEABLE) != 0 &&
4382 TAILQ_EMPTY(&om->md.pv_list) &&
4383 ((om->flags & PG_FICTITIOUS) != 0 ||
4384 TAILQ_EMPTY(&page_to_pvh(om)->pv_list)))
4385 vm_page_aflag_clear(om, PGA_WRITEABLE);
4387 KASSERT((orig_l3 & ATTR_AF) != 0,
4388 ("pmap_enter: unmanaged mapping lacks ATTR_AF"));
4389 pmap_s1_invalidate_page(pmap, va, true);
4394 * Increment the counters.
4396 if ((new_l3 & ATTR_SW_WIRED) != 0)
4397 pmap->pm_stats.wired_count++;
4398 pmap_resident_count_inc(pmap, 1);
4401 * Enter on the PV list if part of our managed memory.
4403 if ((m->oflags & VPO_UNMANAGED) == 0) {
4405 pv = get_pv_entry(pmap, &lock);
4408 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4409 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4411 if ((new_l3 & ATTR_SW_DBM) != 0)
4412 vm_page_aflag_set(m, PGA_WRITEABLE);
4416 if (pmap->pm_stage == PM_STAGE1) {
4418 * Sync icache if exec permission and attribute
4419 * VM_MEMATTR_WRITE_BACK is set. Do it now, before the mapping
4420 * is stored and made valid for hardware table walk. If done
4421 * later, then other can access this page before caches are
4422 * properly synced. Don't do it for kernel memory which is
4423 * mapped with exec permission even if the memory isn't going
4424 * to hold executable code. The only time when icache sync is
4425 * needed is after kernel module is loaded and the relocation
4426 * info is processed. And it's done in elf_cpu_load_file().
4428 if ((prot & VM_PROT_EXECUTE) && pmap != kernel_pmap &&
4429 m->md.pv_memattr == VM_MEMATTR_WRITE_BACK &&
4430 (opa != pa || (orig_l3 & ATTR_S1_XN))) {
4431 PMAP_ASSERT_STAGE1(pmap);
4432 cpu_icache_sync_range(PHYS_TO_DMAP(pa), PAGE_SIZE);
4435 cpu_dcache_wb_range(PHYS_TO_DMAP(pa), PAGE_SIZE);
4439 * Update the L3 entry
4441 if (pmap_l3_valid(orig_l3)) {
4442 PMAP_ASSERT_STAGE1(pmap);
4443 KASSERT(opa == pa, ("pmap_enter: invalid update"));
4444 if ((orig_l3 & ~ATTR_AF) != (new_l3 & ~ATTR_AF)) {
4445 /* same PA, different attributes */
4446 orig_l3 = pmap_load_store(l3, new_l3);
4447 pmap_s1_invalidate_page(pmap, va, true);
4448 if ((orig_l3 & ATTR_SW_MANAGED) != 0 &&
4449 pmap_pte_dirty(pmap, orig_l3))
4454 * This can happens if multiple threads simultaneously
4455 * access not yet mapped page. This bad for performance
4456 * since this can cause full demotion-NOP-promotion
4458 * Another possible reasons are:
4459 * - VM and pmap memory layout are diverged
4460 * - tlb flush is missing somewhere and CPU doesn't see
4463 CTR4(KTR_PMAP, "%s: already mapped page - "
4464 "pmap %p va 0x%#lx pte 0x%lx",
4465 __func__, pmap, va, new_l3);
4469 pmap_store(l3, new_l3);
4473 #if VM_NRESERVLEVEL > 0
4475 * Try to promote from level 3 pages to a level 2 superpage. This
4476 * currently only works on stage 1 pmaps as pmap_promote_l2 looks at
4477 * stage 1 specific fields and performs a break-before-make sequence
4478 * that is incorrect a stage 2 pmap.
4480 if ((mpte == NULL || mpte->ref_count == NL3PG) &&
4481 pmap_ps_enabled(pmap) && pmap->pm_stage == PM_STAGE1 &&
4482 (m->flags & PG_FICTITIOUS) == 0 &&
4483 vm_reserv_level_iffullpop(m) == 0) {
4484 pmap_promote_l2(pmap, pde, va, mpte, &lock);
4497 * Tries to create a read- and/or execute-only 2MB page mapping. Returns
4498 * KERN_SUCCESS if the mapping was created. Otherwise, returns an error
4499 * value. See pmap_enter_l2() for the possible error values when "no sleep",
4500 * "no replace", and "no reclaim" are specified.
4503 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4504 struct rwlock **lockp)
4508 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4509 PMAP_ASSERT_STAGE1(pmap);
4510 KASSERT(ADDR_IS_CANONICAL(va),
4511 ("%s: Address not in canonical form: %lx", __func__, va));
4513 new_l2 = (pd_entry_t)(VM_PAGE_TO_PHYS(m) | ATTR_DEFAULT |
4514 ATTR_S1_IDX(m->md.pv_memattr) | ATTR_S1_AP(ATTR_S1_AP_RO) |
4516 if ((m->oflags & VPO_UNMANAGED) == 0) {
4517 new_l2 |= ATTR_SW_MANAGED;
4520 if ((prot & VM_PROT_EXECUTE) == 0 ||
4521 m->md.pv_memattr == VM_MEMATTR_DEVICE)
4522 new_l2 |= ATTR_S1_XN;
4523 if (!ADDR_IS_KERNEL(va))
4524 new_l2 |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
4526 new_l2 |= ATTR_S1_UXN;
4527 if (pmap != kernel_pmap)
4528 new_l2 |= ATTR_S1_nG;
4529 return (pmap_enter_l2(pmap, va, new_l2, PMAP_ENTER_NOSLEEP |
4530 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, m, lockp));
4534 * Returns true if every page table entry in the specified page table is
4538 pmap_every_pte_zero(vm_paddr_t pa)
4540 pt_entry_t *pt_end, *pte;
4542 KASSERT((pa & PAGE_MASK) == 0, ("pa is misaligned"));
4543 pte = (pt_entry_t *)PHYS_TO_DMAP(pa);
4544 for (pt_end = pte + Ln_ENTRIES; pte < pt_end; pte++) {
4552 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
4553 * the mapping was created, and one of KERN_FAILURE, KERN_NO_SPACE, or
4554 * KERN_RESOURCE_SHORTAGE otherwise. Returns KERN_FAILURE if
4555 * PMAP_ENTER_NOREPLACE was specified and a 4KB page mapping already exists
4556 * within the 2MB virtual address range starting at the specified virtual
4557 * address. Returns KERN_NO_SPACE if PMAP_ENTER_NOREPLACE was specified and a
4558 * 2MB page mapping already exists at the specified virtual address. Returns
4559 * KERN_RESOURCE_SHORTAGE if either (1) PMAP_ENTER_NOSLEEP was specified and a
4560 * page table page allocation failed or (2) PMAP_ENTER_NORECLAIM was specified
4561 * and a PV entry allocation failed.
4564 pmap_enter_l2(pmap_t pmap, vm_offset_t va, pd_entry_t new_l2, u_int flags,
4565 vm_page_t m, struct rwlock **lockp)
4567 struct spglist free;
4568 pd_entry_t *l2, old_l2;
4571 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4572 KASSERT(ADDR_IS_CANONICAL(va),
4573 ("%s: Address not in canonical form: %lx", __func__, va));
4575 if ((l2 = pmap_alloc_l2(pmap, va, &l2pg, (flags &
4576 PMAP_ENTER_NOSLEEP) != 0 ? NULL : lockp)) == NULL) {
4577 CTR2(KTR_PMAP, "pmap_enter_l2: failure for va %#lx in pmap %p",
4579 return (KERN_RESOURCE_SHORTAGE);
4583 * If there are existing mappings, either abort or remove them.
4585 if ((old_l2 = pmap_load(l2)) != 0) {
4586 KASSERT(l2pg == NULL || l2pg->ref_count > 1,
4587 ("pmap_enter_l2: l2pg's ref count is too low"));
4588 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
4589 if ((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK) {
4593 "pmap_enter_l2: no space for va %#lx"
4594 " in pmap %p", va, pmap);
4595 return (KERN_NO_SPACE);
4596 } else if (!ADDR_IS_KERNEL(va) ||
4597 !pmap_every_pte_zero(old_l2 & ~ATTR_MASK)) {
4601 "pmap_enter_l2: failure for va %#lx"
4602 " in pmap %p", va, pmap);
4603 return (KERN_FAILURE);
4607 if ((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK)
4608 (void)pmap_remove_l2(pmap, l2, va,
4609 pmap_load(pmap_l1(pmap, va)), &free, lockp);
4611 pmap_remove_l3_range(pmap, old_l2, va, va + L2_SIZE,
4613 if (!ADDR_IS_KERNEL(va)) {
4614 vm_page_free_pages_toq(&free, true);
4615 KASSERT(pmap_load(l2) == 0,
4616 ("pmap_enter_l2: non-zero L2 entry %p", l2));
4618 KASSERT(SLIST_EMPTY(&free),
4619 ("pmap_enter_l2: freed kernel page table page"));
4622 * Both pmap_remove_l2() and pmap_remove_l3_range()
4623 * will leave the kernel page table page zero filled.
4624 * Nonetheless, the TLB could have an intermediate
4625 * entry for the kernel page table page, so request
4626 * an invalidation at all levels after clearing
4627 * the L2_TABLE entry.
4629 mt = PHYS_TO_VM_PAGE(pmap_load(l2) & ~ATTR_MASK);
4630 if (pmap_insert_pt_page(pmap, mt, false))
4631 panic("pmap_enter_l2: trie insert failed");
4633 pmap_s1_invalidate_page(pmap, va, false);
4637 if ((new_l2 & ATTR_SW_MANAGED) != 0) {
4639 * Abort this mapping if its PV entry could not be created.
4641 if (!pmap_pv_insert_l2(pmap, va, new_l2, flags, lockp)) {
4643 pmap_abort_ptp(pmap, va, l2pg);
4645 "pmap_enter_l2: failure for va %#lx in pmap %p",
4647 return (KERN_RESOURCE_SHORTAGE);
4649 if ((new_l2 & ATTR_SW_DBM) != 0)
4650 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
4651 vm_page_aflag_set(mt, PGA_WRITEABLE);
4655 * Increment counters.
4657 if ((new_l2 & ATTR_SW_WIRED) != 0)
4658 pmap->pm_stats.wired_count += L2_SIZE / PAGE_SIZE;
4659 pmap->pm_stats.resident_count += L2_SIZE / PAGE_SIZE;
4662 * Conditionally sync the icache. See pmap_enter() for details.
4664 if ((new_l2 & ATTR_S1_XN) == 0 && ((new_l2 & ~ATTR_MASK) !=
4665 (old_l2 & ~ATTR_MASK) || (old_l2 & ATTR_S1_XN) != 0) &&
4666 pmap != kernel_pmap && m->md.pv_memattr == VM_MEMATTR_WRITE_BACK) {
4667 cpu_icache_sync_range(PHYS_TO_DMAP(new_l2 & ~ATTR_MASK),
4672 * Map the superpage.
4674 pmap_store(l2, new_l2);
4677 atomic_add_long(&pmap_l2_mappings, 1);
4678 CTR2(KTR_PMAP, "pmap_enter_l2: success for va %#lx in pmap %p",
4681 return (KERN_SUCCESS);
4685 * Maps a sequence of resident pages belonging to the same object.
4686 * The sequence begins with the given page m_start. This page is
4687 * mapped at the given virtual address start. Each subsequent page is
4688 * mapped at a virtual address that is offset from start by the same
4689 * amount as the page is offset from m_start within the object. The
4690 * last page in the sequence is the page with the largest offset from
4691 * m_start that can be mapped at a virtual address less than the given
4692 * virtual address end. Not every virtual page between start and end
4693 * is mapped; only those for which a resident page exists with the
4694 * corresponding offset from m_start are mapped.
4697 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
4698 vm_page_t m_start, vm_prot_t prot)
4700 struct rwlock *lock;
4703 vm_pindex_t diff, psize;
4706 VM_OBJECT_ASSERT_LOCKED(m_start->object);
4708 psize = atop(end - start);
4713 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
4714 va = start + ptoa(diff);
4715 if ((va & L2_OFFSET) == 0 && va + L2_SIZE <= end &&
4716 m->psind == 1 && pmap_ps_enabled(pmap) &&
4717 ((rv = pmap_enter_2mpage(pmap, va, m, prot, &lock)) ==
4718 KERN_SUCCESS || rv == KERN_NO_SPACE))
4719 m = &m[L2_SIZE / PAGE_SIZE - 1];
4721 mpte = pmap_enter_quick_locked(pmap, va, m, prot, mpte,
4723 m = TAILQ_NEXT(m, listq);
4731 * this code makes some *MAJOR* assumptions:
4732 * 1. Current pmap & pmap exists.
4735 * 4. No page table pages.
4736 * but is *MUCH* faster than pmap_enter...
4740 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
4742 struct rwlock *lock;
4746 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
4753 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
4754 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
4757 pt_entry_t *l1, *l2, *l3, l3_val;
4761 KASSERT(!VA_IS_CLEANMAP(va) ||
4762 (m->oflags & VPO_UNMANAGED) != 0,
4763 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
4764 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4765 PMAP_ASSERT_STAGE1(pmap);
4766 KASSERT(ADDR_IS_CANONICAL(va),
4767 ("%s: Address not in canonical form: %lx", __func__, va));
4769 CTR2(KTR_PMAP, "pmap_enter_quick_locked: %p %lx", pmap, va);
4771 * In the case that a page table page is not
4772 * resident, we are creating it here.
4774 if (!ADDR_IS_KERNEL(va)) {
4775 vm_pindex_t l2pindex;
4778 * Calculate pagetable page index
4780 l2pindex = pmap_l2_pindex(va);
4781 if (mpte && (mpte->pindex == l2pindex)) {
4785 * If the page table page is mapped, we just increment
4786 * the hold count, and activate it. Otherwise, we
4787 * attempt to allocate a page table page, passing NULL
4788 * instead of the PV list lock pointer because we don't
4789 * intend to sleep. If this attempt fails, we don't
4790 * retry. Instead, we give up.
4792 l1 = pmap_l1(pmap, va);
4793 if (l1 != NULL && pmap_load(l1) != 0) {
4794 if ((pmap_load(l1) & ATTR_DESCR_MASK) ==
4797 l2 = pmap_l1_to_l2(l1, va);
4798 if (pmap_load(l2) != 0) {
4799 if ((pmap_load(l2) & ATTR_DESCR_MASK) ==
4802 mpte = PHYS_TO_VM_PAGE(pmap_load(l2) &
4806 mpte = _pmap_alloc_l3(pmap, l2pindex,
4812 mpte = _pmap_alloc_l3(pmap, l2pindex, NULL);
4817 l3 = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
4818 l3 = &l3[pmap_l3_index(va)];
4821 pde = pmap_pde(kernel_pmap, va, &lvl);
4822 KASSERT(pde != NULL,
4823 ("pmap_enter_quick_locked: Invalid page entry, va: 0x%lx",
4826 ("pmap_enter_quick_locked: Invalid level %d", lvl));
4827 l3 = pmap_l2_to_l3(pde, va);
4831 * Abort if a mapping already exists.
4833 if (pmap_load(l3) != 0) {
4840 * Enter on the PV list if part of our managed memory.
4842 if ((m->oflags & VPO_UNMANAGED) == 0 &&
4843 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
4845 pmap_abort_ptp(pmap, va, mpte);
4850 * Increment counters
4852 pmap_resident_count_inc(pmap, 1);
4854 pa = VM_PAGE_TO_PHYS(m);
4855 l3_val = pa | ATTR_DEFAULT | ATTR_S1_IDX(m->md.pv_memattr) |
4856 ATTR_S1_AP(ATTR_S1_AP_RO) | L3_PAGE;
4857 if ((prot & VM_PROT_EXECUTE) == 0 ||
4858 m->md.pv_memattr == VM_MEMATTR_DEVICE)
4859 l3_val |= ATTR_S1_XN;
4860 if (!ADDR_IS_KERNEL(va))
4861 l3_val |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
4863 l3_val |= ATTR_S1_UXN;
4864 if (pmap != kernel_pmap)
4865 l3_val |= ATTR_S1_nG;
4868 * Now validate mapping with RO protection
4870 if ((m->oflags & VPO_UNMANAGED) == 0) {
4871 l3_val |= ATTR_SW_MANAGED;
4875 /* Sync icache before the mapping is stored to PTE */
4876 if ((prot & VM_PROT_EXECUTE) && pmap != kernel_pmap &&
4877 m->md.pv_memattr == VM_MEMATTR_WRITE_BACK)
4878 cpu_icache_sync_range(PHYS_TO_DMAP(pa), PAGE_SIZE);
4880 pmap_store(l3, l3_val);
4887 * This code maps large physical mmap regions into the
4888 * processor address space. Note that some shortcuts
4889 * are taken, but the code works.
4892 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
4893 vm_pindex_t pindex, vm_size_t size)
4896 VM_OBJECT_ASSERT_WLOCKED(object);
4897 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
4898 ("pmap_object_init_pt: non-device object"));
4902 * Clear the wired attribute from the mappings for the specified range of
4903 * addresses in the given pmap. Every valid mapping within that range
4904 * must have the wired attribute set. In contrast, invalid mappings
4905 * cannot have the wired attribute set, so they are ignored.
4907 * The wired attribute of the page table entry is not a hardware feature,
4908 * so there is no need to invalidate any TLB entries.
4911 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4913 vm_offset_t va_next;
4914 pd_entry_t *l0, *l1, *l2;
4918 for (; sva < eva; sva = va_next) {
4919 l0 = pmap_l0(pmap, sva);
4920 if (pmap_load(l0) == 0) {
4921 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
4927 l1 = pmap_l0_to_l1(l0, sva);
4928 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
4931 if (pmap_load(l1) == 0)
4934 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
4935 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
4936 KASSERT(va_next <= eva,
4937 ("partial update of non-transparent 1G page "
4938 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
4939 pmap_load(l1), sva, eva, va_next));
4940 MPASS(pmap != kernel_pmap);
4941 MPASS((pmap_load(l1) & (ATTR_SW_MANAGED |
4942 ATTR_SW_WIRED)) == ATTR_SW_WIRED);
4943 pmap_clear_bits(l1, ATTR_SW_WIRED);
4944 pmap->pm_stats.wired_count -= L1_SIZE / PAGE_SIZE;
4948 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
4952 l2 = pmap_l1_to_l2(l1, sva);
4953 if (pmap_load(l2) == 0)
4956 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK) {
4957 if ((pmap_load(l2) & ATTR_SW_WIRED) == 0)
4958 panic("pmap_unwire: l2 %#jx is missing "
4959 "ATTR_SW_WIRED", (uintmax_t)pmap_load(l2));
4962 * Are we unwiring the entire large page? If not,
4963 * demote the mapping and fall through.
4965 if (sva + L2_SIZE == va_next && eva >= va_next) {
4966 pmap_clear_bits(l2, ATTR_SW_WIRED);
4967 pmap->pm_stats.wired_count -= L2_SIZE /
4970 } else if (pmap_demote_l2(pmap, l2, sva) == NULL)
4971 panic("pmap_unwire: demotion failed");
4973 KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
4974 ("pmap_unwire: Invalid l2 entry after demotion"));
4978 for (l3 = pmap_l2_to_l3(l2, sva); sva != va_next; l3++,
4980 if (pmap_load(l3) == 0)
4982 if ((pmap_load(l3) & ATTR_SW_WIRED) == 0)
4983 panic("pmap_unwire: l3 %#jx is missing "
4984 "ATTR_SW_WIRED", (uintmax_t)pmap_load(l3));
4987 * ATTR_SW_WIRED must be cleared atomically. Although
4988 * the pmap lock synchronizes access to ATTR_SW_WIRED,
4989 * the System MMU may write to the entry concurrently.
4991 pmap_clear_bits(l3, ATTR_SW_WIRED);
4992 pmap->pm_stats.wired_count--;
4999 * Copy the range specified by src_addr/len
5000 * from the source map to the range dst_addr/len
5001 * in the destination map.
5003 * This routine is only advisory and need not do anything.
5005 * Because the executable mappings created by this routine are copied,
5006 * it should not have to flush the instruction cache.
5009 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5010 vm_offset_t src_addr)
5012 struct rwlock *lock;
5013 pd_entry_t *l0, *l1, *l2, srcptepaddr;
5014 pt_entry_t *dst_pte, mask, nbits, ptetemp, *src_pte;
5015 vm_offset_t addr, end_addr, va_next;
5016 vm_page_t dst_m, dstmpte, srcmpte;
5018 PMAP_ASSERT_STAGE1(dst_pmap);
5019 PMAP_ASSERT_STAGE1(src_pmap);
5021 if (dst_addr != src_addr)
5023 end_addr = src_addr + len;
5025 if (dst_pmap < src_pmap) {
5026 PMAP_LOCK(dst_pmap);
5027 PMAP_LOCK(src_pmap);
5029 PMAP_LOCK(src_pmap);
5030 PMAP_LOCK(dst_pmap);
5032 for (addr = src_addr; addr < end_addr; addr = va_next) {
5033 l0 = pmap_l0(src_pmap, addr);
5034 if (pmap_load(l0) == 0) {
5035 va_next = (addr + L0_SIZE) & ~L0_OFFSET;
5041 va_next = (addr + L1_SIZE) & ~L1_OFFSET;
5044 l1 = pmap_l0_to_l1(l0, addr);
5045 if (pmap_load(l1) == 0)
5047 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
5048 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
5049 KASSERT(va_next <= end_addr,
5050 ("partial update of non-transparent 1G page "
5051 "l1 %#lx addr %#lx end_addr %#lx va_next %#lx",
5052 pmap_load(l1), addr, end_addr, va_next));
5053 srcptepaddr = pmap_load(l1);
5054 l1 = pmap_l1(dst_pmap, addr);
5056 if (_pmap_alloc_l3(dst_pmap,
5057 pmap_l0_pindex(addr), NULL) == NULL)
5059 l1 = pmap_l1(dst_pmap, addr);
5061 l0 = pmap_l0(dst_pmap, addr);
5062 dst_m = PHYS_TO_VM_PAGE(pmap_load(l0) &
5066 KASSERT(pmap_load(l1) == 0,
5067 ("1G mapping present in dst pmap "
5068 "l1 %#lx addr %#lx end_addr %#lx va_next %#lx",
5069 pmap_load(l1), addr, end_addr, va_next));
5070 pmap_store(l1, srcptepaddr & ~ATTR_SW_WIRED);
5071 pmap_resident_count_inc(dst_pmap, L1_SIZE / PAGE_SIZE);
5075 va_next = (addr + L2_SIZE) & ~L2_OFFSET;
5078 l2 = pmap_l1_to_l2(l1, addr);
5079 srcptepaddr = pmap_load(l2);
5080 if (srcptepaddr == 0)
5082 if ((srcptepaddr & ATTR_DESCR_MASK) == L2_BLOCK) {
5084 * We can only virtual copy whole superpages.
5086 if ((addr & L2_OFFSET) != 0 ||
5087 addr + L2_SIZE > end_addr)
5089 l2 = pmap_alloc_l2(dst_pmap, addr, &dst_m, NULL);
5092 if (pmap_load(l2) == 0 &&
5093 ((srcptepaddr & ATTR_SW_MANAGED) == 0 ||
5094 pmap_pv_insert_l2(dst_pmap, addr, srcptepaddr,
5095 PMAP_ENTER_NORECLAIM, &lock))) {
5097 * We leave the dirty bit unchanged because
5098 * managed read/write superpage mappings are
5099 * required to be dirty. However, managed
5100 * superpage mappings are not required to
5101 * have their accessed bit set, so we clear
5102 * it because we don't know if this mapping
5105 srcptepaddr &= ~ATTR_SW_WIRED;
5106 if ((srcptepaddr & ATTR_SW_MANAGED) != 0)
5107 srcptepaddr &= ~ATTR_AF;
5108 pmap_store(l2, srcptepaddr);
5109 pmap_resident_count_inc(dst_pmap, L2_SIZE /
5111 atomic_add_long(&pmap_l2_mappings, 1);
5113 pmap_abort_ptp(dst_pmap, addr, dst_m);
5116 KASSERT((srcptepaddr & ATTR_DESCR_MASK) == L2_TABLE,
5117 ("pmap_copy: invalid L2 entry"));
5118 srcptepaddr &= ~ATTR_MASK;
5119 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5120 KASSERT(srcmpte->ref_count > 0,
5121 ("pmap_copy: source page table page is unused"));
5122 if (va_next > end_addr)
5124 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5125 src_pte = &src_pte[pmap_l3_index(addr)];
5127 for (; addr < va_next; addr += PAGE_SIZE, src_pte++) {
5128 ptetemp = pmap_load(src_pte);
5131 * We only virtual copy managed pages.
5133 if ((ptetemp & ATTR_SW_MANAGED) == 0)
5136 if (dstmpte != NULL) {
5137 KASSERT(dstmpte->pindex == pmap_l2_pindex(addr),
5138 ("dstmpte pindex/addr mismatch"));
5139 dstmpte->ref_count++;
5140 } else if ((dstmpte = pmap_alloc_l3(dst_pmap, addr,
5143 dst_pte = (pt_entry_t *)
5144 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5145 dst_pte = &dst_pte[pmap_l3_index(addr)];
5146 if (pmap_load(dst_pte) == 0 &&
5147 pmap_try_insert_pv_entry(dst_pmap, addr,
5148 PHYS_TO_VM_PAGE(ptetemp & ~ATTR_MASK), &lock)) {
5150 * Clear the wired, modified, and accessed
5151 * (referenced) bits during the copy.
5153 mask = ATTR_AF | ATTR_SW_WIRED;
5155 if ((ptetemp & ATTR_SW_DBM) != 0)
5156 nbits |= ATTR_S1_AP_RW_BIT;
5157 pmap_store(dst_pte, (ptetemp & ~mask) | nbits);
5158 pmap_resident_count_inc(dst_pmap, 1);
5160 pmap_abort_ptp(dst_pmap, addr, dstmpte);
5163 /* Have we copied all of the valid mappings? */
5164 if (dstmpte->ref_count >= srcmpte->ref_count)
5170 * XXX This barrier may not be needed because the destination pmap is
5177 PMAP_UNLOCK(src_pmap);
5178 PMAP_UNLOCK(dst_pmap);
5182 * pmap_zero_page zeros the specified hardware page by mapping
5183 * the page into KVM and using bzero to clear its contents.
5186 pmap_zero_page(vm_page_t m)
5188 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5190 pagezero((void *)va);
5194 * pmap_zero_page_area zeros the specified hardware page by mapping
5195 * the page into KVM and using bzero to clear its contents.
5197 * off and size may not cover an area beyond a single hardware page.
5200 pmap_zero_page_area(vm_page_t m, int off, int size)
5202 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5204 if (off == 0 && size == PAGE_SIZE)
5205 pagezero((void *)va);
5207 bzero((char *)va + off, size);
5211 * pmap_copy_page copies the specified (machine independent)
5212 * page by mapping the page into virtual memory and using
5213 * bcopy to copy the page, one machine dependent page at a
5217 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5219 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5220 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5222 pagecopy((void *)src, (void *)dst);
5225 int unmapped_buf_allowed = 1;
5228 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5229 vm_offset_t b_offset, int xfersize)
5233 vm_paddr_t p_a, p_b;
5234 vm_offset_t a_pg_offset, b_pg_offset;
5237 while (xfersize > 0) {
5238 a_pg_offset = a_offset & PAGE_MASK;
5239 m_a = ma[a_offset >> PAGE_SHIFT];
5240 p_a = m_a->phys_addr;
5241 b_pg_offset = b_offset & PAGE_MASK;
5242 m_b = mb[b_offset >> PAGE_SHIFT];
5243 p_b = m_b->phys_addr;
5244 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5245 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5246 if (__predict_false(!PHYS_IN_DMAP(p_a))) {
5247 panic("!DMAP a %lx", p_a);
5249 a_cp = (char *)PHYS_TO_DMAP(p_a) + a_pg_offset;
5251 if (__predict_false(!PHYS_IN_DMAP(p_b))) {
5252 panic("!DMAP b %lx", p_b);
5254 b_cp = (char *)PHYS_TO_DMAP(p_b) + b_pg_offset;
5256 bcopy(a_cp, b_cp, cnt);
5264 pmap_quick_enter_page(vm_page_t m)
5267 return (PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)));
5271 pmap_quick_remove_page(vm_offset_t addr)
5276 * Returns true if the pmap's pv is one of the first
5277 * 16 pvs linked to from this page. This count may
5278 * be changed upwards or downwards in the future; it
5279 * is only necessary that true be returned for a small
5280 * subset of pmaps for proper page aging.
5283 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5285 struct md_page *pvh;
5286 struct rwlock *lock;
5291 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5292 ("pmap_page_exists_quick: page %p is not managed", m));
5294 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5296 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5297 if (PV_PMAP(pv) == pmap) {
5305 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5306 pvh = page_to_pvh(m);
5307 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5308 if (PV_PMAP(pv) == pmap) {
5322 * pmap_page_wired_mappings:
5324 * Return the number of managed mappings to the given physical page
5328 pmap_page_wired_mappings(vm_page_t m)
5330 struct rwlock *lock;
5331 struct md_page *pvh;
5335 int count, md_gen, pvh_gen;
5337 if ((m->oflags & VPO_UNMANAGED) != 0)
5339 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5343 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5345 if (!PMAP_TRYLOCK(pmap)) {
5346 md_gen = m->md.pv_gen;
5350 if (md_gen != m->md.pv_gen) {
5355 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
5356 if ((pmap_load(pte) & ATTR_SW_WIRED) != 0)
5360 if ((m->flags & PG_FICTITIOUS) == 0) {
5361 pvh = page_to_pvh(m);
5362 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5364 if (!PMAP_TRYLOCK(pmap)) {
5365 md_gen = m->md.pv_gen;
5366 pvh_gen = pvh->pv_gen;
5370 if (md_gen != m->md.pv_gen ||
5371 pvh_gen != pvh->pv_gen) {
5376 pte = pmap_pte_exists(pmap, pv->pv_va, 2, __func__);
5377 if ((pmap_load(pte) & ATTR_SW_WIRED) != 0)
5387 * Returns true if the given page is mapped individually or as part of
5388 * a 2mpage. Otherwise, returns false.
5391 pmap_page_is_mapped(vm_page_t m)
5393 struct rwlock *lock;
5396 if ((m->oflags & VPO_UNMANAGED) != 0)
5398 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5400 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5401 ((m->flags & PG_FICTITIOUS) == 0 &&
5402 !TAILQ_EMPTY(&page_to_pvh(m)->pv_list));
5408 * Destroy all managed, non-wired mappings in the given user-space
5409 * pmap. This pmap cannot be active on any processor besides the
5412 * This function cannot be applied to the kernel pmap. Moreover, it
5413 * is not intended for general use. It is only to be used during
5414 * process termination. Consequently, it can be implemented in ways
5415 * that make it faster than pmap_remove(). First, it can more quickly
5416 * destroy mappings by iterating over the pmap's collection of PV
5417 * entries, rather than searching the page table. Second, it doesn't
5418 * have to test and clear the page table entries atomically, because
5419 * no processor is currently accessing the user address space. In
5420 * particular, a page table entry's dirty bit won't change state once
5421 * this function starts.
5424 pmap_remove_pages(pmap_t pmap)
5427 pt_entry_t *pte, tpte;
5428 struct spglist free;
5429 struct pv_chunklist free_chunks[PMAP_MEMDOM];
5430 vm_page_t m, ml3, mt;
5432 struct md_page *pvh;
5433 struct pv_chunk *pc, *npc;
5434 struct rwlock *lock;
5436 uint64_t inuse, bitmask;
5437 int allfree, field, i, idx, lvl;
5443 for (i = 0; i < PMAP_MEMDOM; i++)
5444 TAILQ_INIT(&free_chunks[i]);
5447 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5450 for (field = 0; field < _NPCM; field++) {
5451 inuse = ~pc->pc_map[field] & pc_freemask[field];
5452 while (inuse != 0) {
5453 bit = ffsl(inuse) - 1;
5454 bitmask = 1UL << bit;
5455 idx = field * 64 + bit;
5456 pv = &pc->pc_pventry[idx];
5459 pde = pmap_pde(pmap, pv->pv_va, &lvl);
5460 KASSERT(pde != NULL,
5461 ("Attempting to remove an unmapped page"));
5465 pte = pmap_l1_to_l2(pde, pv->pv_va);
5466 tpte = pmap_load(pte);
5467 KASSERT((tpte & ATTR_DESCR_MASK) ==
5469 ("Attempting to remove an invalid "
5470 "block: %lx", tpte));
5473 pte = pmap_l2_to_l3(pde, pv->pv_va);
5474 tpte = pmap_load(pte);
5475 KASSERT((tpte & ATTR_DESCR_MASK) ==
5477 ("Attempting to remove an invalid "
5478 "page: %lx", tpte));
5482 "Invalid page directory level: %d",
5487 * We cannot remove wired pages from a process' mapping at this time
5489 if (tpte & ATTR_SW_WIRED) {
5495 pc->pc_map[field] |= bitmask;
5498 * Because this pmap is not active on other
5499 * processors, the dirty bit cannot have
5500 * changed state since we last loaded pte.
5504 pa = tpte & ~ATTR_MASK;
5506 m = PHYS_TO_VM_PAGE(pa);
5507 KASSERT(m->phys_addr == pa,
5508 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5509 m, (uintmax_t)m->phys_addr,
5512 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5513 m < &vm_page_array[vm_page_array_size],
5514 ("pmap_remove_pages: bad pte %#jx",
5518 * Update the vm_page_t clean/reference bits.
5520 if (pmap_pte_dirty(pmap, tpte)) {
5523 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
5532 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5536 pmap_resident_count_dec(pmap,
5537 L2_SIZE / PAGE_SIZE);
5538 pvh = page_to_pvh(m);
5539 TAILQ_REMOVE(&pvh->pv_list, pv,pv_next);
5541 if (TAILQ_EMPTY(&pvh->pv_list)) {
5542 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
5543 if ((mt->a.flags & PGA_WRITEABLE) != 0 &&
5544 TAILQ_EMPTY(&mt->md.pv_list))
5545 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5547 ml3 = pmap_remove_pt_page(pmap,
5550 KASSERT(ml3->valid == VM_PAGE_BITS_ALL,
5551 ("pmap_remove_pages: l3 page not promoted"));
5552 pmap_resident_count_dec(pmap,1);
5553 KASSERT(ml3->ref_count == NL3PG,
5554 ("pmap_remove_pages: l3 page ref count error"));
5556 pmap_add_delayed_free_list(ml3,
5561 pmap_resident_count_dec(pmap, 1);
5562 TAILQ_REMOVE(&m->md.pv_list, pv,
5565 if ((m->a.flags & PGA_WRITEABLE) != 0 &&
5566 TAILQ_EMPTY(&m->md.pv_list) &&
5567 (m->flags & PG_FICTITIOUS) == 0) {
5568 pvh = page_to_pvh(m);
5569 if (TAILQ_EMPTY(&pvh->pv_list))
5570 vm_page_aflag_clear(m,
5575 pmap_unuse_pt(pmap, pv->pv_va, pmap_load(pde),
5580 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5581 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5582 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5584 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5585 TAILQ_INSERT_TAIL(&free_chunks[pc_to_domain(pc)], pc,
5591 pmap_s1_invalidate_all(pmap);
5592 free_pv_chunk_batch(free_chunks);
5594 vm_page_free_pages_toq(&free, true);
5598 * This is used to check if a page has been accessed or modified.
5601 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
5603 struct rwlock *lock;
5605 struct md_page *pvh;
5606 pt_entry_t *pte, mask, value;
5608 int md_gen, pvh_gen;
5612 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5615 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5617 PMAP_ASSERT_STAGE1(pmap);
5618 if (!PMAP_TRYLOCK(pmap)) {
5619 md_gen = m->md.pv_gen;
5623 if (md_gen != m->md.pv_gen) {
5628 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
5632 mask |= ATTR_S1_AP_RW_BIT;
5633 value |= ATTR_S1_AP(ATTR_S1_AP_RW);
5636 mask |= ATTR_AF | ATTR_DESCR_MASK;
5637 value |= ATTR_AF | L3_PAGE;
5639 rv = (pmap_load(pte) & mask) == value;
5644 if ((m->flags & PG_FICTITIOUS) == 0) {
5645 pvh = page_to_pvh(m);
5646 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5648 PMAP_ASSERT_STAGE1(pmap);
5649 if (!PMAP_TRYLOCK(pmap)) {
5650 md_gen = m->md.pv_gen;
5651 pvh_gen = pvh->pv_gen;
5655 if (md_gen != m->md.pv_gen ||
5656 pvh_gen != pvh->pv_gen) {
5661 pte = pmap_pte_exists(pmap, pv->pv_va, 2, __func__);
5665 mask |= ATTR_S1_AP_RW_BIT;
5666 value |= ATTR_S1_AP(ATTR_S1_AP_RW);
5669 mask |= ATTR_AF | ATTR_DESCR_MASK;
5670 value |= ATTR_AF | L2_BLOCK;
5672 rv = (pmap_load(pte) & mask) == value;
5686 * Return whether or not the specified physical page was modified
5687 * in any physical maps.
5690 pmap_is_modified(vm_page_t m)
5693 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5694 ("pmap_is_modified: page %p is not managed", m));
5697 * If the page is not busied then this check is racy.
5699 if (!pmap_page_is_write_mapped(m))
5701 return (pmap_page_test_mappings(m, FALSE, TRUE));
5705 * pmap_is_prefaultable:
5707 * Return whether or not the specified virtual address is eligible
5711 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
5719 * Return TRUE if and only if the L3 entry for the specified virtual
5720 * address is allocated but invalid.
5724 pde = pmap_pde(pmap, addr, &lvl);
5725 if (pde != NULL && lvl == 2) {
5726 pte = pmap_l2_to_l3(pde, addr);
5727 rv = pmap_load(pte) == 0;
5734 * pmap_is_referenced:
5736 * Return whether or not the specified physical page was referenced
5737 * in any physical maps.
5740 pmap_is_referenced(vm_page_t m)
5743 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5744 ("pmap_is_referenced: page %p is not managed", m));
5745 return (pmap_page_test_mappings(m, TRUE, FALSE));
5749 * Clear the write and modified bits in each of the given page's mappings.
5752 pmap_remove_write(vm_page_t m)
5754 struct md_page *pvh;
5756 struct rwlock *lock;
5757 pv_entry_t next_pv, pv;
5758 pt_entry_t oldpte, *pte;
5760 int md_gen, pvh_gen;
5762 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5763 ("pmap_remove_write: page %p is not managed", m));
5764 vm_page_assert_busied(m);
5766 if (!pmap_page_is_write_mapped(m))
5768 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5769 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
5772 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
5774 PMAP_ASSERT_STAGE1(pmap);
5775 if (!PMAP_TRYLOCK(pmap)) {
5776 pvh_gen = pvh->pv_gen;
5780 if (pvh_gen != pvh->pv_gen) {
5786 pte = pmap_pte_exists(pmap, va, 2, __func__);
5787 if ((pmap_load(pte) & ATTR_SW_DBM) != 0)
5788 (void)pmap_demote_l2_locked(pmap, pte, va, &lock);
5789 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
5790 ("inconsistent pv lock %p %p for page %p",
5791 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
5794 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5796 PMAP_ASSERT_STAGE1(pmap);
5797 if (!PMAP_TRYLOCK(pmap)) {
5798 pvh_gen = pvh->pv_gen;
5799 md_gen = m->md.pv_gen;
5803 if (pvh_gen != pvh->pv_gen ||
5804 md_gen != m->md.pv_gen) {
5809 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
5810 oldpte = pmap_load(pte);
5811 if ((oldpte & ATTR_SW_DBM) != 0) {
5812 while (!atomic_fcmpset_64(pte, &oldpte,
5813 (oldpte | ATTR_S1_AP_RW_BIT) & ~ATTR_SW_DBM))
5815 if ((oldpte & ATTR_S1_AP_RW_BIT) ==
5816 ATTR_S1_AP(ATTR_S1_AP_RW))
5818 pmap_s1_invalidate_page(pmap, pv->pv_va, true);
5823 vm_page_aflag_clear(m, PGA_WRITEABLE);
5827 * pmap_ts_referenced:
5829 * Return a count of reference bits for a page, clearing those bits.
5830 * It is not necessary for every reference bit to be cleared, but it
5831 * is necessary that 0 only be returned when there are truly no
5832 * reference bits set.
5834 * As an optimization, update the page's dirty field if a modified bit is
5835 * found while counting reference bits. This opportunistic update can be
5836 * performed at low cost and can eliminate the need for some future calls
5837 * to pmap_is_modified(). However, since this function stops after
5838 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
5839 * dirty pages. Those dirty pages will only be detected by a future call
5840 * to pmap_is_modified().
5843 pmap_ts_referenced(vm_page_t m)
5845 struct md_page *pvh;
5848 struct rwlock *lock;
5849 pt_entry_t *pte, tpte;
5852 int cleared, md_gen, not_cleared, pvh_gen;
5853 struct spglist free;
5855 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5856 ("pmap_ts_referenced: page %p is not managed", m));
5859 pa = VM_PAGE_TO_PHYS(m);
5860 lock = PHYS_TO_PV_LIST_LOCK(pa);
5861 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
5865 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
5866 goto small_mappings;
5872 if (!PMAP_TRYLOCK(pmap)) {
5873 pvh_gen = pvh->pv_gen;
5877 if (pvh_gen != pvh->pv_gen) {
5883 pte = pmap_pte_exists(pmap, va, 2, __func__);
5884 tpte = pmap_load(pte);
5885 if (pmap_pte_dirty(pmap, tpte)) {
5887 * Although "tpte" is mapping a 2MB page, because
5888 * this function is called at a 4KB page granularity,
5889 * we only update the 4KB page under test.
5893 if ((tpte & ATTR_AF) != 0) {
5895 * Since this reference bit is shared by 512 4KB pages,
5896 * it should not be cleared every time it is tested.
5897 * Apply a simple "hash" function on the physical page
5898 * number, the virtual superpage number, and the pmap
5899 * address to select one 4KB page out of the 512 on
5900 * which testing the reference bit will result in
5901 * clearing that reference bit. This function is
5902 * designed to avoid the selection of the same 4KB page
5903 * for every 2MB page mapping.
5905 * On demotion, a mapping that hasn't been referenced
5906 * is simply destroyed. To avoid the possibility of a
5907 * subsequent page fault on a demoted wired mapping,
5908 * always leave its reference bit set. Moreover,
5909 * since the superpage is wired, the current state of
5910 * its reference bit won't affect page replacement.
5912 if ((((pa >> PAGE_SHIFT) ^ (va >> L2_SHIFT) ^
5913 (uintptr_t)pmap) & (Ln_ENTRIES - 1)) == 0 &&
5914 (tpte & ATTR_SW_WIRED) == 0) {
5915 pmap_clear_bits(pte, ATTR_AF);
5916 pmap_s1_invalidate_page(pmap, va, true);
5922 /* Rotate the PV list if it has more than one entry. */
5923 if (TAILQ_NEXT(pv, pv_next) != NULL) {
5924 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5925 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5928 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
5930 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
5932 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
5939 if (!PMAP_TRYLOCK(pmap)) {
5940 pvh_gen = pvh->pv_gen;
5941 md_gen = m->md.pv_gen;
5945 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
5950 pte = pmap_pte_exists(pmap, pv->pv_va, 3, __func__);
5951 tpte = pmap_load(pte);
5952 if (pmap_pte_dirty(pmap, tpte))
5954 if ((tpte & ATTR_AF) != 0) {
5955 if ((tpte & ATTR_SW_WIRED) == 0) {
5956 pmap_clear_bits(pte, ATTR_AF);
5957 pmap_s1_invalidate_page(pmap, pv->pv_va, true);
5963 /* Rotate the PV list if it has more than one entry. */
5964 if (TAILQ_NEXT(pv, pv_next) != NULL) {
5965 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5966 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5969 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
5970 not_cleared < PMAP_TS_REFERENCED_MAX);
5973 vm_page_free_pages_toq(&free, true);
5974 return (cleared + not_cleared);
5978 * Apply the given advice to the specified range of addresses within the
5979 * given pmap. Depending on the advice, clear the referenced and/or
5980 * modified flags in each mapping and set the mapped page's dirty field.
5983 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
5985 struct rwlock *lock;
5986 vm_offset_t va, va_next;
5988 pd_entry_t *l0, *l1, *l2, oldl2;
5989 pt_entry_t *l3, oldl3;
5991 PMAP_ASSERT_STAGE1(pmap);
5993 if (advice != MADV_DONTNEED && advice != MADV_FREE)
5997 for (; sva < eva; sva = va_next) {
5998 l0 = pmap_l0(pmap, sva);
5999 if (pmap_load(l0) == 0) {
6000 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
6006 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
6009 l1 = pmap_l0_to_l1(l0, sva);
6010 if (pmap_load(l1) == 0)
6012 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
6013 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
6017 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
6020 l2 = pmap_l1_to_l2(l1, sva);
6021 oldl2 = pmap_load(l2);
6024 if ((oldl2 & ATTR_DESCR_MASK) == L2_BLOCK) {
6025 if ((oldl2 & ATTR_SW_MANAGED) == 0)
6028 if (!pmap_demote_l2_locked(pmap, l2, sva, &lock)) {
6033 * The 2MB page mapping was destroyed.
6039 * Unless the page mappings are wired, remove the
6040 * mapping to a single page so that a subsequent
6041 * access may repromote. Choosing the last page
6042 * within the address range [sva, min(va_next, eva))
6043 * generally results in more repromotions. Since the
6044 * underlying page table page is fully populated, this
6045 * removal never frees a page table page.
6047 if ((oldl2 & ATTR_SW_WIRED) == 0) {
6053 ("pmap_advise: no address gap"));
6054 l3 = pmap_l2_to_l3(l2, va);
6055 KASSERT(pmap_load(l3) != 0,
6056 ("pmap_advise: invalid PTE"));
6057 pmap_remove_l3(pmap, l3, va, pmap_load(l2),
6063 KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
6064 ("pmap_advise: invalid L2 entry after demotion"));
6068 for (l3 = pmap_l2_to_l3(l2, sva); sva != va_next; l3++,
6070 oldl3 = pmap_load(l3);
6071 if ((oldl3 & (ATTR_SW_MANAGED | ATTR_DESCR_MASK)) !=
6072 (ATTR_SW_MANAGED | L3_PAGE))
6074 else if (pmap_pte_dirty(pmap, oldl3)) {
6075 if (advice == MADV_DONTNEED) {
6077 * Future calls to pmap_is_modified()
6078 * can be avoided by making the page
6081 m = PHYS_TO_VM_PAGE(oldl3 & ~ATTR_MASK);
6084 while (!atomic_fcmpset_long(l3, &oldl3,
6085 (oldl3 & ~ATTR_AF) |
6086 ATTR_S1_AP(ATTR_S1_AP_RO)))
6088 } else if ((oldl3 & ATTR_AF) != 0)
6089 pmap_clear_bits(l3, ATTR_AF);
6096 if (va != va_next) {
6097 pmap_s1_invalidate_range(pmap, va, sva, true);
6102 pmap_s1_invalidate_range(pmap, va, sva, true);
6108 * Clear the modify bits on the specified physical page.
6111 pmap_clear_modify(vm_page_t m)
6113 struct md_page *pvh;
6114 struct rwlock *lock;
6116 pv_entry_t next_pv, pv;
6117 pd_entry_t *l2, oldl2;
6118 pt_entry_t *l3, oldl3;
6120 int md_gen, pvh_gen;
6122 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6123 ("pmap_clear_modify: page %p is not managed", m));
6124 vm_page_assert_busied(m);
6126 if (!pmap_page_is_write_mapped(m))
6128 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
6129 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6132 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6134 PMAP_ASSERT_STAGE1(pmap);
6135 if (!PMAP_TRYLOCK(pmap)) {
6136 pvh_gen = pvh->pv_gen;
6140 if (pvh_gen != pvh->pv_gen) {
6146 l2 = pmap_l2(pmap, va);
6147 oldl2 = pmap_load(l2);
6148 /* If oldl2 has ATTR_SW_DBM set, then it is also dirty. */
6149 if ((oldl2 & ATTR_SW_DBM) != 0 &&
6150 pmap_demote_l2_locked(pmap, l2, va, &lock) &&
6151 (oldl2 & ATTR_SW_WIRED) == 0) {
6153 * Write protect the mapping to a single page so that
6154 * a subsequent write access may repromote.
6156 va += VM_PAGE_TO_PHYS(m) - (oldl2 & ~ATTR_MASK);
6157 l3 = pmap_l2_to_l3(l2, va);
6158 oldl3 = pmap_load(l3);
6159 while (!atomic_fcmpset_long(l3, &oldl3,
6160 (oldl3 & ~ATTR_SW_DBM) | ATTR_S1_AP(ATTR_S1_AP_RO)))
6163 pmap_s1_invalidate_page(pmap, va, true);
6167 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6169 PMAP_ASSERT_STAGE1(pmap);
6170 if (!PMAP_TRYLOCK(pmap)) {
6171 md_gen = m->md.pv_gen;
6172 pvh_gen = pvh->pv_gen;
6176 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6181 l2 = pmap_l2(pmap, pv->pv_va);
6182 l3 = pmap_l2_to_l3(l2, pv->pv_va);
6183 oldl3 = pmap_load(l3);
6184 if ((oldl3 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) == ATTR_SW_DBM){
6185 pmap_set_bits(l3, ATTR_S1_AP(ATTR_S1_AP_RO));
6186 pmap_s1_invalidate_page(pmap, pv->pv_va, true);
6194 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6196 struct pmap_preinit_mapping *ppim;
6197 vm_offset_t va, offset;
6200 int i, lvl, l2_blocks, free_l2_count, start_idx;
6202 if (!vm_initialized) {
6204 * No L3 ptables so map entire L2 blocks where start VA is:
6205 * preinit_map_va + start_idx * L2_SIZE
6206 * There may be duplicate mappings (multiple VA -> same PA) but
6207 * ARM64 dcache is always PIPT so that's acceptable.
6212 /* Calculate how many L2 blocks are needed for the mapping */
6213 l2_blocks = (roundup2(pa + size, L2_SIZE) -
6214 rounddown2(pa, L2_SIZE)) >> L2_SHIFT;
6216 offset = pa & L2_OFFSET;
6218 if (preinit_map_va == 0)
6221 /* Map 2MiB L2 blocks from reserved VA space */
6225 /* Find enough free contiguous VA space */
6226 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6227 ppim = pmap_preinit_mapping + i;
6228 if (free_l2_count > 0 && ppim->pa != 0) {
6229 /* Not enough space here */
6235 if (ppim->pa == 0) {
6237 if (start_idx == -1)
6240 if (free_l2_count == l2_blocks)
6244 if (free_l2_count != l2_blocks)
6245 panic("%s: too many preinit mappings", __func__);
6247 va = preinit_map_va + (start_idx * L2_SIZE);
6248 for (i = start_idx; i < start_idx + l2_blocks; i++) {
6249 /* Mark entries as allocated */
6250 ppim = pmap_preinit_mapping + i;
6252 ppim->va = va + offset;
6257 pa = rounddown2(pa, L2_SIZE);
6258 for (i = 0; i < l2_blocks; i++) {
6259 pde = pmap_pde(kernel_pmap, va, &lvl);
6260 KASSERT(pde != NULL,
6261 ("pmap_mapbios: Invalid page entry, va: 0x%lx",
6264 ("pmap_mapbios: Invalid level %d", lvl));
6266 /* Insert L2_BLOCK */
6267 l2 = pmap_l1_to_l2(pde, va);
6269 pa | ATTR_DEFAULT | ATTR_S1_XN |
6270 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) | L2_BLOCK);
6275 pmap_s1_invalidate_all(kernel_pmap);
6277 va = preinit_map_va + (start_idx * L2_SIZE);
6280 /* kva_alloc may be used to map the pages */
6281 offset = pa & PAGE_MASK;
6282 size = round_page(offset + size);
6284 va = kva_alloc(size);
6286 panic("%s: Couldn't allocate KVA", __func__);
6288 pde = pmap_pde(kernel_pmap, va, &lvl);
6289 KASSERT(lvl == 2, ("pmap_mapbios: Invalid level %d", lvl));
6291 /* L3 table is linked */
6292 va = trunc_page(va);
6293 pa = trunc_page(pa);
6294 pmap_kenter(va, size, pa, memory_mapping_mode(pa));
6297 return ((void *)(va + offset));
6301 pmap_unmapbios(void *p, vm_size_t size)
6303 struct pmap_preinit_mapping *ppim;
6304 vm_offset_t offset, tmpsize, va, va_trunc;
6307 int i, lvl, l2_blocks, block;
6310 va = (vm_offset_t)p;
6312 (roundup2(va + size, L2_SIZE) - rounddown2(va, L2_SIZE)) >> L2_SHIFT;
6313 KASSERT(l2_blocks > 0, ("pmap_unmapbios: invalid size %lx", size));
6315 /* Remove preinit mapping */
6316 preinit_map = false;
6318 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6319 ppim = pmap_preinit_mapping + i;
6320 if (ppim->va == va) {
6321 KASSERT(ppim->size == size,
6322 ("pmap_unmapbios: size mismatch"));
6327 offset = block * L2_SIZE;
6328 va_trunc = rounddown2(va, L2_SIZE) + offset;
6330 /* Remove L2_BLOCK */
6331 pde = pmap_pde(kernel_pmap, va_trunc, &lvl);
6332 KASSERT(pde != NULL,
6333 ("pmap_unmapbios: Invalid page entry, va: 0x%lx",
6335 l2 = pmap_l1_to_l2(pde, va_trunc);
6338 if (block == (l2_blocks - 1))
6344 pmap_s1_invalidate_all(kernel_pmap);
6348 /* Unmap the pages reserved with kva_alloc. */
6349 if (vm_initialized) {
6350 offset = va & PAGE_MASK;
6351 size = round_page(offset + size);
6352 va = trunc_page(va);
6354 pde = pmap_pde(kernel_pmap, va, &lvl);
6355 KASSERT(pde != NULL,
6356 ("pmap_unmapbios: Invalid page entry, va: 0x%lx", va));
6357 KASSERT(lvl == 2, ("pmap_unmapbios: Invalid level %d", lvl));
6359 /* Unmap and invalidate the pages */
6360 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6361 pmap_kremove(va + tmpsize);
6368 * Sets the memory attribute for the specified page.
6371 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6374 m->md.pv_memattr = ma;
6377 * If "m" is a normal page, update its direct mapping. This update
6378 * can be relied upon to perform any cache operations that are
6379 * required for data coherence.
6381 if ((m->flags & PG_FICTITIOUS) == 0 &&
6382 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6383 m->md.pv_memattr) != 0)
6384 panic("memory attribute change on the direct map failed");
6388 * Changes the specified virtual address range's memory type to that given by
6389 * the parameter "mode". The specified virtual address range must be
6390 * completely contained within either the direct map or the kernel map. If
6391 * the virtual address range is contained within the kernel map, then the
6392 * memory type for each of the corresponding ranges of the direct map is also
6393 * changed. (The corresponding ranges of the direct map are those ranges that
6394 * map the same physical pages as the specified virtual address range.) These
6395 * changes to the direct map are necessary because Intel describes the
6396 * behavior of their processors as "undefined" if two or more mappings to the
6397 * same physical page have different memory types.
6399 * Returns zero if the change completed successfully, and either EINVAL or
6400 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6401 * of the virtual address range was not mapped, and ENOMEM is returned if
6402 * there was insufficient memory available to complete the change. In the
6403 * latter case, the memory type may have been changed on some part of the
6404 * virtual address range or the direct map.
6407 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6411 PMAP_LOCK(kernel_pmap);
6412 error = pmap_change_props_locked(va, size, PROT_NONE, mode, false);
6413 PMAP_UNLOCK(kernel_pmap);
6418 * Changes the specified virtual address range's protections to those
6419 * specified by "prot". Like pmap_change_attr(), protections for aliases
6420 * in the direct map are updated as well. Protections on aliasing mappings may
6421 * be a subset of the requested protections; for example, mappings in the direct
6422 * map are never executable.
6425 pmap_change_prot(vm_offset_t va, vm_size_t size, vm_prot_t prot)
6429 /* Only supported within the kernel map. */
6430 if (va < VM_MIN_KERNEL_ADDRESS)
6433 PMAP_LOCK(kernel_pmap);
6434 error = pmap_change_props_locked(va, size, prot, -1, false);
6435 PMAP_UNLOCK(kernel_pmap);
6440 pmap_change_props_locked(vm_offset_t va, vm_size_t size, vm_prot_t prot,
6441 int mode, bool skip_unmapped)
6443 vm_offset_t base, offset, tmpva;
6446 pt_entry_t pte, *ptep, *newpte;
6447 pt_entry_t bits, mask;
6450 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6451 base = trunc_page(va);
6452 offset = va & PAGE_MASK;
6453 size = round_page(offset + size);
6455 if (!VIRT_IN_DMAP(base) &&
6456 !(base >= VM_MIN_KERNEL_ADDRESS && base < VM_MAX_KERNEL_ADDRESS))
6462 bits = ATTR_S1_IDX(mode);
6463 mask = ATTR_S1_IDX_MASK;
6464 if (mode == VM_MEMATTR_DEVICE) {
6469 if (prot != VM_PROT_NONE) {
6470 /* Don't mark the DMAP as executable. It never is on arm64. */
6471 if (VIRT_IN_DMAP(base)) {
6472 prot &= ~VM_PROT_EXECUTE;
6474 * XXX Mark the DMAP as writable for now. We rely
6475 * on this in ddb & dtrace to insert breakpoint
6478 prot |= VM_PROT_WRITE;
6481 if ((prot & VM_PROT_WRITE) == 0) {
6482 bits |= ATTR_S1_AP(ATTR_S1_AP_RO);
6484 if ((prot & VM_PROT_EXECUTE) == 0) {
6485 bits |= ATTR_S1_PXN;
6487 bits |= ATTR_S1_UXN;
6488 mask |= ATTR_S1_AP_MASK | ATTR_S1_XN;
6491 for (tmpva = base; tmpva < base + size; ) {
6492 ptep = pmap_pte(kernel_pmap, tmpva, &lvl);
6493 if (ptep == NULL && !skip_unmapped) {
6495 } else if ((ptep == NULL && skip_unmapped) ||
6496 (pmap_load(ptep) & mask) == bits) {
6498 * We already have the correct attribute or there
6499 * is no memory mapped at this address and we are
6500 * skipping unmapped memory.
6504 panic("Invalid DMAP table level: %d\n", lvl);
6506 tmpva = (tmpva & ~L1_OFFSET) + L1_SIZE;
6509 tmpva = (tmpva & ~L2_OFFSET) + L2_SIZE;
6516 /* We can't demote/promote this entry */
6517 MPASS((pmap_load(ptep) & ATTR_SW_NO_PROMOTE) == 0);
6520 * Split the entry to an level 3 table, then
6521 * set the new attribute.
6525 panic("Invalid DMAP table level: %d\n", lvl);
6527 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
6528 if ((tmpva & L1_OFFSET) == 0 &&
6529 (base + size - tmpva) >= L1_SIZE) {
6533 newpte = pmap_demote_l1(kernel_pmap, ptep,
6534 tmpva & ~L1_OFFSET);
6537 ptep = pmap_l1_to_l2(ptep, tmpva);
6540 if ((tmpva & L2_OFFSET) == 0 &&
6541 (base + size - tmpva) >= L2_SIZE) {
6545 newpte = pmap_demote_l2(kernel_pmap, ptep,
6549 ptep = pmap_l2_to_l3(ptep, tmpva);
6552 pte_size = PAGE_SIZE;
6556 /* Update the entry */
6557 pte = pmap_load(ptep);
6561 pmap_update_entry(kernel_pmap, ptep, pte, tmpva,
6564 pa = pte & ~ATTR_MASK;
6565 if (!VIRT_IN_DMAP(tmpva) && PHYS_IN_DMAP(pa)) {
6567 * Keep the DMAP memory in sync.
6569 rv = pmap_change_props_locked(
6570 PHYS_TO_DMAP(pa), pte_size,
6577 * If moving to a non-cacheable entry flush
6580 if (mode == VM_MEMATTR_UNCACHEABLE)
6581 cpu_dcache_wbinv_range(tmpva, pte_size);
6590 * Create an L2 table to map all addresses within an L1 mapping.
6593 pmap_demote_l1(pmap_t pmap, pt_entry_t *l1, vm_offset_t va)
6595 pt_entry_t *l2, newl2, oldl1;
6597 vm_paddr_t l2phys, phys;
6601 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6602 oldl1 = pmap_load(l1);
6603 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
6604 KASSERT((oldl1 & ATTR_DESCR_MASK) == L1_BLOCK,
6605 ("pmap_demote_l1: Demoting a non-block entry"));
6606 KASSERT((va & L1_OFFSET) == 0,
6607 ("pmap_demote_l1: Invalid virtual address %#lx", va));
6608 KASSERT((oldl1 & ATTR_SW_MANAGED) == 0,
6609 ("pmap_demote_l1: Level 1 table shouldn't be managed"));
6610 KASSERT((oldl1 & ATTR_SW_NO_PROMOTE) == 0,
6611 ("pmap_demote_l1: Demoting entry with no-demote flag set"));
6614 if (va <= (vm_offset_t)l1 && va + L1_SIZE > (vm_offset_t)l1) {
6615 tmpl1 = kva_alloc(PAGE_SIZE);
6620 if ((ml2 = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED)) ==
6622 CTR2(KTR_PMAP, "pmap_demote_l1: failure for va %#lx"
6623 " in pmap %p", va, pmap);
6628 l2phys = VM_PAGE_TO_PHYS(ml2);
6629 l2 = (pt_entry_t *)PHYS_TO_DMAP(l2phys);
6631 /* Address the range points at */
6632 phys = oldl1 & ~ATTR_MASK;
6633 /* The attributed from the old l1 table to be copied */
6634 newl2 = oldl1 & ATTR_MASK;
6636 /* Create the new entries */
6637 for (i = 0; i < Ln_ENTRIES; i++) {
6638 l2[i] = newl2 | phys;
6641 KASSERT(l2[0] == ((oldl1 & ~ATTR_DESCR_MASK) | L2_BLOCK),
6642 ("Invalid l2 page (%lx != %lx)", l2[0],
6643 (oldl1 & ~ATTR_DESCR_MASK) | L2_BLOCK));
6646 pmap_kenter(tmpl1, PAGE_SIZE,
6647 DMAP_TO_PHYS((vm_offset_t)l1) & ~L3_OFFSET,
6648 VM_MEMATTR_WRITE_BACK);
6649 l1 = (pt_entry_t *)(tmpl1 + ((vm_offset_t)l1 & PAGE_MASK));
6652 pmap_update_entry(pmap, l1, l2phys | L1_TABLE, va, PAGE_SIZE);
6656 pmap_kremove(tmpl1);
6657 kva_free(tmpl1, PAGE_SIZE);
6664 pmap_fill_l3(pt_entry_t *firstl3, pt_entry_t newl3)
6668 for (l3 = firstl3; l3 - firstl3 < Ln_ENTRIES; l3++) {
6675 pmap_demote_l2_abort(pmap_t pmap, vm_offset_t va, pt_entry_t *l2,
6676 struct rwlock **lockp)
6678 struct spglist free;
6681 (void)pmap_remove_l2(pmap, l2, va, pmap_load(pmap_l1(pmap, va)), &free,
6683 vm_page_free_pages_toq(&free, true);
6687 * Create an L3 table to map all addresses within an L2 mapping.
6690 pmap_demote_l2_locked(pmap_t pmap, pt_entry_t *l2, vm_offset_t va,
6691 struct rwlock **lockp)
6693 pt_entry_t *l3, newl3, oldl2;
6698 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6699 PMAP_ASSERT_STAGE1(pmap);
6700 KASSERT(ADDR_IS_CANONICAL(va),
6701 ("%s: Address not in canonical form: %lx", __func__, va));
6704 oldl2 = pmap_load(l2);
6705 KASSERT((oldl2 & ATTR_DESCR_MASK) == L2_BLOCK,
6706 ("pmap_demote_l2: Demoting a non-block entry"));
6707 KASSERT((oldl2 & ATTR_SW_NO_PROMOTE) == 0,
6708 ("pmap_demote_l2: Demoting entry with no-demote flag set"));
6712 if (va <= (vm_offset_t)l2 && va + L2_SIZE > (vm_offset_t)l2) {
6713 tmpl2 = kva_alloc(PAGE_SIZE);
6719 * Invalidate the 2MB page mapping and return "failure" if the
6720 * mapping was never accessed.
6722 if ((oldl2 & ATTR_AF) == 0) {
6723 KASSERT((oldl2 & ATTR_SW_WIRED) == 0,
6724 ("pmap_demote_l2: a wired mapping is missing ATTR_AF"));
6725 pmap_demote_l2_abort(pmap, va, l2, lockp);
6726 CTR2(KTR_PMAP, "pmap_demote_l2: failure for va %#lx in pmap %p",
6731 if ((ml3 = pmap_remove_pt_page(pmap, va)) == NULL) {
6732 KASSERT((oldl2 & ATTR_SW_WIRED) == 0,
6733 ("pmap_demote_l2: page table page for a wired mapping"
6737 * If the page table page is missing and the mapping
6738 * is for a kernel address, the mapping must belong to
6739 * either the direct map or the early kernel memory.
6740 * Page table pages are preallocated for every other
6741 * part of the kernel address space, so the direct map
6742 * region and early kernel memory are the only parts of the
6743 * kernel address space that must be handled here.
6745 KASSERT(!ADDR_IS_KERNEL(va) || VIRT_IN_DMAP(va) ||
6746 (va >= VM_MIN_KERNEL_ADDRESS && va < kernel_vm_end),
6747 ("pmap_demote_l2: No saved mpte for va %#lx", va));
6750 * If the 2MB page mapping belongs to the direct map
6751 * region of the kernel's address space, then the page
6752 * allocation request specifies the highest possible
6753 * priority (VM_ALLOC_INTERRUPT). Otherwise, the
6754 * priority is normal.
6756 ml3 = vm_page_alloc_noobj(
6757 (VIRT_IN_DMAP(va) ? VM_ALLOC_INTERRUPT : 0) |
6761 * If the allocation of the new page table page fails,
6762 * invalidate the 2MB page mapping and return "failure".
6765 pmap_demote_l2_abort(pmap, va, l2, lockp);
6766 CTR2(KTR_PMAP, "pmap_demote_l2: failure for va %#lx"
6767 " in pmap %p", va, pmap);
6770 ml3->pindex = pmap_l2_pindex(va);
6772 if (!ADDR_IS_KERNEL(va)) {
6773 ml3->ref_count = NL3PG;
6774 pmap_resident_count_inc(pmap, 1);
6777 l3phys = VM_PAGE_TO_PHYS(ml3);
6778 l3 = (pt_entry_t *)PHYS_TO_DMAP(l3phys);
6779 newl3 = (oldl2 & ~ATTR_DESCR_MASK) | L3_PAGE;
6780 KASSERT((oldl2 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) !=
6781 (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM),
6782 ("pmap_demote_l2: L2 entry is writeable but not dirty"));
6785 * If the page table page is not leftover from an earlier promotion,
6786 * or the mapping attributes have changed, (re)initialize the L3 table.
6788 * When pmap_update_entry() clears the old L2 mapping, it (indirectly)
6789 * performs a dsb(). That dsb() ensures that the stores for filling
6790 * "l3" are visible before "l3" is added to the page table.
6792 if (ml3->valid == 0 || (l3[0] & ATTR_MASK) != (newl3 & ATTR_MASK))
6793 pmap_fill_l3(l3, newl3);
6796 * Map the temporary page so we don't lose access to the l2 table.
6799 pmap_kenter(tmpl2, PAGE_SIZE,
6800 DMAP_TO_PHYS((vm_offset_t)l2) & ~L3_OFFSET,
6801 VM_MEMATTR_WRITE_BACK);
6802 l2 = (pt_entry_t *)(tmpl2 + ((vm_offset_t)l2 & PAGE_MASK));
6806 * The spare PV entries must be reserved prior to demoting the
6807 * mapping, that is, prior to changing the PDE. Otherwise, the state
6808 * of the L2 and the PV lists will be inconsistent, which can result
6809 * in reclaim_pv_chunk() attempting to remove a PV entry from the
6810 * wrong PV list and pmap_pv_demote_l2() failing to find the expected
6811 * PV entry for the 2MB page mapping that is being demoted.
6813 if ((oldl2 & ATTR_SW_MANAGED) != 0)
6814 reserve_pv_entries(pmap, Ln_ENTRIES - 1, lockp);
6817 * Pass PAGE_SIZE so that a single TLB invalidation is performed on
6818 * the 2MB page mapping.
6820 pmap_update_entry(pmap, l2, l3phys | L2_TABLE, va, PAGE_SIZE);
6823 * Demote the PV entry.
6825 if ((oldl2 & ATTR_SW_MANAGED) != 0)
6826 pmap_pv_demote_l2(pmap, va, oldl2 & ~ATTR_MASK, lockp);
6828 atomic_add_long(&pmap_l2_demotions, 1);
6829 CTR3(KTR_PMAP, "pmap_demote_l2: success for va %#lx"
6830 " in pmap %p %lx", va, pmap, l3[0]);
6834 pmap_kremove(tmpl2);
6835 kva_free(tmpl2, PAGE_SIZE);
6843 pmap_demote_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va)
6845 struct rwlock *lock;
6849 l3 = pmap_demote_l2_locked(pmap, l2, va, &lock);
6856 * Perform the pmap work for mincore(2). If the page is not both referenced and
6857 * modified by this pmap, returns its physical address so that the caller can
6858 * find other mappings.
6861 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
6863 pt_entry_t *pte, tpte;
6864 vm_paddr_t mask, pa;
6868 PMAP_ASSERT_STAGE1(pmap);
6870 pte = pmap_pte(pmap, addr, &lvl);
6872 tpte = pmap_load(pte);
6885 panic("pmap_mincore: invalid level %d", lvl);
6888 managed = (tpte & ATTR_SW_MANAGED) != 0;
6889 val = MINCORE_INCORE;
6891 val |= MINCORE_PSIND(3 - lvl);
6892 if ((managed && pmap_pte_dirty(pmap, tpte)) || (!managed &&
6893 (tpte & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP(ATTR_S1_AP_RW)))
6894 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
6895 if ((tpte & ATTR_AF) == ATTR_AF)
6896 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
6898 pa = (tpte & ~ATTR_MASK) | (addr & mask);
6904 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
6905 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) && managed) {
6913 * Garbage collect every ASID that is neither active on a processor nor
6917 pmap_reset_asid_set(pmap_t pmap)
6920 int asid, cpuid, epoch;
6921 struct asid_set *set;
6922 enum pmap_stage stage;
6924 set = pmap->pm_asid_set;
6925 stage = pmap->pm_stage;
6927 set = pmap->pm_asid_set;
6928 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
6929 mtx_assert(&set->asid_set_mutex, MA_OWNED);
6932 * Ensure that the store to asid_epoch is globally visible before the
6933 * loads from pc_curpmap are performed.
6935 epoch = set->asid_epoch + 1;
6936 if (epoch == INT_MAX)
6938 set->asid_epoch = epoch;
6940 if (stage == PM_STAGE1) {
6941 __asm __volatile("tlbi vmalle1is");
6943 KASSERT(pmap_clean_stage2_tlbi != NULL,
6944 ("%s: Unset stage 2 tlb invalidation callback\n",
6946 pmap_clean_stage2_tlbi();
6949 bit_nclear(set->asid_set, ASID_FIRST_AVAILABLE,
6950 set->asid_set_size - 1);
6951 CPU_FOREACH(cpuid) {
6952 if (cpuid == curcpu)
6954 if (stage == PM_STAGE1) {
6955 curpmap = pcpu_find(cpuid)->pc_curpmap;
6956 PMAP_ASSERT_STAGE1(pmap);
6958 curpmap = pcpu_find(cpuid)->pc_curvmpmap;
6959 if (curpmap == NULL)
6961 PMAP_ASSERT_STAGE2(pmap);
6963 KASSERT(curpmap->pm_asid_set == set, ("Incorrect set"));
6964 asid = COOKIE_TO_ASID(curpmap->pm_cookie);
6967 bit_set(set->asid_set, asid);
6968 curpmap->pm_cookie = COOKIE_FROM(asid, epoch);
6973 * Allocate a new ASID for the specified pmap.
6976 pmap_alloc_asid(pmap_t pmap)
6978 struct asid_set *set;
6981 set = pmap->pm_asid_set;
6982 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
6984 mtx_lock_spin(&set->asid_set_mutex);
6987 * While this processor was waiting to acquire the asid set mutex,
6988 * pmap_reset_asid_set() running on another processor might have
6989 * updated this pmap's cookie to the current epoch. In which case, we
6990 * don't need to allocate a new ASID.
6992 if (COOKIE_TO_EPOCH(pmap->pm_cookie) == set->asid_epoch)
6995 bit_ffc_at(set->asid_set, set->asid_next, set->asid_set_size,
6997 if (new_asid == -1) {
6998 bit_ffc_at(set->asid_set, ASID_FIRST_AVAILABLE,
6999 set->asid_next, &new_asid);
7000 if (new_asid == -1) {
7001 pmap_reset_asid_set(pmap);
7002 bit_ffc_at(set->asid_set, ASID_FIRST_AVAILABLE,
7003 set->asid_set_size, &new_asid);
7004 KASSERT(new_asid != -1, ("ASID allocation failure"));
7007 bit_set(set->asid_set, new_asid);
7008 set->asid_next = new_asid + 1;
7009 pmap->pm_cookie = COOKIE_FROM(new_asid, set->asid_epoch);
7011 mtx_unlock_spin(&set->asid_set_mutex);
7014 static uint64_t __read_mostly ttbr_flags;
7017 * Compute the value that should be stored in ttbr0 to activate the specified
7018 * pmap. This value may change from time to time.
7021 pmap_to_ttbr0(pmap_t pmap)
7025 ttbr = pmap->pm_ttbr;
7026 ttbr |= ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
7033 pmap_set_cnp(void *arg)
7035 uint64_t ttbr0, ttbr1;
7038 cpuid = *(u_int *)arg;
7039 if (cpuid == curcpu) {
7041 * Set the flags while all CPUs are handling the
7042 * smp_rendezvous so will not call pmap_to_ttbr0. Any calls
7043 * to pmap_to_ttbr0 after this will have the CnP flag set.
7044 * The dsb after invalidating the TLB will act as a barrier
7045 * to ensure all CPUs can observe this change.
7047 ttbr_flags |= TTBR_CnP;
7050 ttbr0 = READ_SPECIALREG(ttbr0_el1);
7053 ttbr1 = READ_SPECIALREG(ttbr1_el1);
7056 /* Update ttbr{0,1}_el1 with the CnP flag */
7057 WRITE_SPECIALREG(ttbr0_el1, ttbr0);
7058 WRITE_SPECIALREG(ttbr1_el1, ttbr1);
7060 __asm __volatile("tlbi vmalle1is");
7066 * Defer enabling CnP until we have read the ID registers to know if it's
7067 * supported on all CPUs.
7070 pmap_init_cnp(void *dummy __unused)
7075 if (!get_kernel_reg(ID_AA64MMFR2_EL1, ®))
7078 if (ID_AA64MMFR2_CnP_VAL(reg) != ID_AA64MMFR2_CnP_NONE) {
7080 printf("Enabling CnP\n");
7082 smp_rendezvous(NULL, pmap_set_cnp, NULL, &cpuid);
7086 SYSINIT(pmap_init_cnp, SI_SUB_SMP, SI_ORDER_ANY, pmap_init_cnp, NULL);
7089 pmap_activate_int(pmap_t pmap)
7091 struct asid_set *set;
7094 KASSERT(PCPU_GET(curpmap) != NULL, ("no active pmap"));
7095 KASSERT(pmap != kernel_pmap, ("kernel pmap activation"));
7097 if ((pmap->pm_stage == PM_STAGE1 && pmap == PCPU_GET(curpmap)) ||
7098 (pmap->pm_stage == PM_STAGE2 && pmap == PCPU_GET(curvmpmap))) {
7100 * Handle the possibility that the old thread was preempted
7101 * after an "ic" or "tlbi" instruction but before it performed
7102 * a "dsb" instruction. If the old thread migrates to a new
7103 * processor, its completion of a "dsb" instruction on that
7104 * new processor does not guarantee that the "ic" or "tlbi"
7105 * instructions performed on the old processor have completed.
7111 set = pmap->pm_asid_set;
7112 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
7115 * Ensure that the store to curpmap is globally visible before the
7116 * load from asid_epoch is performed.
7118 if (pmap->pm_stage == PM_STAGE1)
7119 PCPU_SET(curpmap, pmap);
7121 PCPU_SET(curvmpmap, pmap);
7123 epoch = COOKIE_TO_EPOCH(pmap->pm_cookie);
7124 if (epoch >= 0 && epoch != set->asid_epoch)
7125 pmap_alloc_asid(pmap);
7127 if (pmap->pm_stage == PM_STAGE1) {
7128 set_ttbr0(pmap_to_ttbr0(pmap));
7129 if (PCPU_GET(bcast_tlbi_workaround) != 0)
7130 invalidate_local_icache();
7136 pmap_activate_vm(pmap_t pmap)
7139 PMAP_ASSERT_STAGE2(pmap);
7141 (void)pmap_activate_int(pmap);
7145 pmap_activate(struct thread *td)
7149 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7150 PMAP_ASSERT_STAGE1(pmap);
7152 (void)pmap_activate_int(pmap);
7157 * Activate the thread we are switching to.
7158 * To simplify the assembly in cpu_throw return the new threads pcb.
7161 pmap_switch(struct thread *new)
7163 pcpu_bp_harden bp_harden;
7166 /* Store the new curthread */
7167 PCPU_SET(curthread, new);
7169 /* And the new pcb */
7171 PCPU_SET(curpcb, pcb);
7174 * TODO: We may need to flush the cache here if switching
7175 * to a user process.
7178 if (pmap_activate_int(vmspace_pmap(new->td_proc->p_vmspace))) {
7180 * Stop userspace from training the branch predictor against
7181 * other processes. This will call into a CPU specific
7182 * function that clears the branch predictor state.
7184 bp_harden = PCPU_GET(bp_harden);
7185 if (bp_harden != NULL)
7193 pmap_sync_icache(pmap_t pmap, vm_offset_t va, vm_size_t sz)
7196 PMAP_ASSERT_STAGE1(pmap);
7197 KASSERT(ADDR_IS_CANONICAL(va),
7198 ("%s: Address not in canonical form: %lx", __func__, va));
7200 if (ADDR_IS_KERNEL(va)) {
7201 cpu_icache_sync_range(va, sz);
7206 /* Find the length of data in this page to flush */
7207 offset = va & PAGE_MASK;
7208 len = imin(PAGE_SIZE - offset, sz);
7211 /* Extract the physical address & find it in the DMAP */
7212 pa = pmap_extract(pmap, va);
7214 cpu_icache_sync_range(PHYS_TO_DMAP(pa), len);
7216 /* Move to the next page */
7219 /* Set the length for the next iteration */
7220 len = imin(PAGE_SIZE, sz);
7226 pmap_stage2_fault(pmap_t pmap, uint64_t esr, uint64_t far)
7229 pt_entry_t *ptep, pte;
7232 PMAP_ASSERT_STAGE2(pmap);
7235 /* Data and insn aborts use same encoding for FSC field. */
7236 dfsc = esr & ISS_DATA_DFSC_MASK;
7238 case ISS_DATA_DFSC_TF_L0:
7239 case ISS_DATA_DFSC_TF_L1:
7240 case ISS_DATA_DFSC_TF_L2:
7241 case ISS_DATA_DFSC_TF_L3:
7243 pdep = pmap_pde(pmap, far, &lvl);
7244 if (pdep == NULL || lvl != (dfsc - ISS_DATA_DFSC_TF_L1)) {
7251 ptep = pmap_l0_to_l1(pdep, far);
7254 ptep = pmap_l1_to_l2(pdep, far);
7257 ptep = pmap_l2_to_l3(pdep, far);
7260 panic("%s: Invalid pde level %d", __func__,lvl);
7264 case ISS_DATA_DFSC_AFF_L1:
7265 case ISS_DATA_DFSC_AFF_L2:
7266 case ISS_DATA_DFSC_AFF_L3:
7268 ptep = pmap_pte(pmap, far, &lvl);
7270 if (ptep != NULL && (pte = pmap_load(ptep)) != 0) {
7272 pmap_invalidate_vpipt_icache();
7275 * If accessing an executable page invalidate
7276 * the I-cache so it will be valid when we
7277 * continue execution in the guest. The D-cache
7278 * is assumed to already be clean to the Point
7281 if ((pte & ATTR_S2_XN_MASK) !=
7282 ATTR_S2_XN(ATTR_S2_XN_NONE)) {
7283 invalidate_icache();
7286 pmap_set_bits(ptep, ATTR_AF | ATTR_DESCR_VALID);
7297 pmap_fault(pmap_t pmap, uint64_t esr, uint64_t far)
7299 pt_entry_t pte, *ptep;
7306 ec = ESR_ELx_EXCEPTION(esr);
7308 case EXCP_INSN_ABORT_L:
7309 case EXCP_INSN_ABORT:
7310 case EXCP_DATA_ABORT_L:
7311 case EXCP_DATA_ABORT:
7317 if (pmap->pm_stage == PM_STAGE2)
7318 return (pmap_stage2_fault(pmap, esr, far));
7320 /* Data and insn aborts use same encoding for FSC field. */
7321 switch (esr & ISS_DATA_DFSC_MASK) {
7322 case ISS_DATA_DFSC_AFF_L1:
7323 case ISS_DATA_DFSC_AFF_L2:
7324 case ISS_DATA_DFSC_AFF_L3:
7326 ptep = pmap_pte(pmap, far, &lvl);
7328 pmap_set_bits(ptep, ATTR_AF);
7331 * XXXMJ as an optimization we could mark the entry
7332 * dirty if this is a write fault.
7337 case ISS_DATA_DFSC_PF_L1:
7338 case ISS_DATA_DFSC_PF_L2:
7339 case ISS_DATA_DFSC_PF_L3:
7340 if ((ec != EXCP_DATA_ABORT_L && ec != EXCP_DATA_ABORT) ||
7341 (esr & ISS_DATA_WnR) == 0)
7344 ptep = pmap_pte(pmap, far, &lvl);
7346 ((pte = pmap_load(ptep)) & ATTR_SW_DBM) != 0) {
7347 if ((pte & ATTR_S1_AP_RW_BIT) ==
7348 ATTR_S1_AP(ATTR_S1_AP_RO)) {
7349 pmap_clear_bits(ptep, ATTR_S1_AP_RW_BIT);
7350 pmap_s1_invalidate_page(pmap, far, true);
7356 case ISS_DATA_DFSC_TF_L0:
7357 case ISS_DATA_DFSC_TF_L1:
7358 case ISS_DATA_DFSC_TF_L2:
7359 case ISS_DATA_DFSC_TF_L3:
7361 * Retry the translation. A break-before-make sequence can
7362 * produce a transient fault.
7364 if (pmap == kernel_pmap) {
7366 * The translation fault may have occurred within a
7367 * critical section. Therefore, we must check the
7368 * address without acquiring the kernel pmap's lock.
7370 if (pmap_klookup(far, NULL))
7374 /* Ask the MMU to check the address. */
7375 intr = intr_disable();
7376 par = arm64_address_translate_s1e0r(far);
7381 * If the translation was successful, then we can
7382 * return success to the trap handler.
7384 if (PAR_SUCCESS(par))
7394 * Increase the starting virtual address of the given mapping if a
7395 * different alignment might result in more superpage mappings.
7398 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7399 vm_offset_t *addr, vm_size_t size)
7401 vm_offset_t superpage_offset;
7405 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7406 offset += ptoa(object->pg_color);
7407 superpage_offset = offset & L2_OFFSET;
7408 if (size - ((L2_SIZE - superpage_offset) & L2_OFFSET) < L2_SIZE ||
7409 (*addr & L2_OFFSET) == superpage_offset)
7411 if ((*addr & L2_OFFSET) < superpage_offset)
7412 *addr = (*addr & ~L2_OFFSET) + superpage_offset;
7414 *addr = ((*addr + L2_OFFSET) & ~L2_OFFSET) + superpage_offset;
7418 * Get the kernel virtual address of a set of physical pages. If there are
7419 * physical addresses not covered by the DMAP perform a transient mapping
7420 * that will be removed when calling pmap_unmap_io_transient.
7422 * \param page The pages the caller wishes to obtain the virtual
7423 * address on the kernel memory map.
7424 * \param vaddr On return contains the kernel virtual memory address
7425 * of the pages passed in the page parameter.
7426 * \param count Number of pages passed in.
7427 * \param can_fault TRUE if the thread using the mapped pages can take
7428 * page faults, FALSE otherwise.
7430 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7431 * finished or FALSE otherwise.
7435 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7436 boolean_t can_fault)
7439 boolean_t needs_mapping;
7440 int error __diagused, i;
7443 * Allocate any KVA space that we need, this is done in a separate
7444 * loop to prevent calling vmem_alloc while pinned.
7446 needs_mapping = FALSE;
7447 for (i = 0; i < count; i++) {
7448 paddr = VM_PAGE_TO_PHYS(page[i]);
7449 if (__predict_false(!PHYS_IN_DMAP(paddr))) {
7450 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7451 M_BESTFIT | M_WAITOK, &vaddr[i]);
7452 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7453 needs_mapping = TRUE;
7455 vaddr[i] = PHYS_TO_DMAP(paddr);
7459 /* Exit early if everything is covered by the DMAP */
7465 for (i = 0; i < count; i++) {
7466 paddr = VM_PAGE_TO_PHYS(page[i]);
7467 if (!PHYS_IN_DMAP(paddr)) {
7469 "pmap_map_io_transient: TODO: Map out of DMAP data");
7473 return (needs_mapping);
7477 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7478 boolean_t can_fault)
7485 for (i = 0; i < count; i++) {
7486 paddr = VM_PAGE_TO_PHYS(page[i]);
7487 if (!PHYS_IN_DMAP(paddr)) {
7488 panic("ARM64TODO: pmap_unmap_io_transient: Unmap data");
7494 pmap_is_valid_memattr(pmap_t pmap __unused, vm_memattr_t mode)
7497 return (mode >= VM_MEMATTR_DEVICE && mode <= VM_MEMATTR_WRITE_THROUGH);
7501 * Track a range of the kernel's virtual address space that is contiguous
7502 * in various mapping attributes.
7504 struct pmap_kernel_map_range {
7514 sysctl_kmaps_dump(struct sbuf *sb, struct pmap_kernel_map_range *range,
7520 if (eva <= range->sva)
7523 index = range->attrs & ATTR_S1_IDX_MASK;
7525 case ATTR_S1_IDX(VM_MEMATTR_DEVICE):
7528 case ATTR_S1_IDX(VM_MEMATTR_UNCACHEABLE):
7531 case ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK):
7534 case ATTR_S1_IDX(VM_MEMATTR_WRITE_THROUGH):
7539 "%s: unknown memory type %x for range 0x%016lx-0x%016lx\n",
7540 __func__, index, range->sva, eva);
7545 sbuf_printf(sb, "0x%016lx-0x%016lx r%c%c%c%c %3s %d %d %d %d\n",
7547 (range->attrs & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP_RW ? 'w' : '-',
7548 (range->attrs & ATTR_S1_PXN) != 0 ? '-' : 'x',
7549 (range->attrs & ATTR_S1_UXN) != 0 ? '-' : 'X',
7550 (range->attrs & ATTR_S1_AP(ATTR_S1_AP_USER)) != 0 ? 'u' : 's',
7551 mode, range->l1blocks, range->l2blocks, range->l3contig,
7554 /* Reset to sentinel value. */
7555 range->sva = 0xfffffffffffffffful;
7559 * Determine whether the attributes specified by a page table entry match those
7560 * being tracked by the current range.
7563 sysctl_kmaps_match(struct pmap_kernel_map_range *range, pt_entry_t attrs)
7566 return (range->attrs == attrs);
7570 sysctl_kmaps_reinit(struct pmap_kernel_map_range *range, vm_offset_t va,
7574 memset(range, 0, sizeof(*range));
7576 range->attrs = attrs;
7579 /* Get the block/page attributes that correspond to the table attributes */
7581 sysctl_kmaps_table_attrs(pd_entry_t table)
7586 if ((table & TATTR_UXN_TABLE) != 0)
7587 attrs |= ATTR_S1_UXN;
7588 if ((table & TATTR_PXN_TABLE) != 0)
7589 attrs |= ATTR_S1_PXN;
7590 if ((table & TATTR_AP_TABLE_RO) != 0)
7591 attrs |= ATTR_S1_AP(ATTR_S1_AP_RO);
7596 /* Read the block/page attributes we care about */
7598 sysctl_kmaps_block_attrs(pt_entry_t block)
7600 return (block & (ATTR_S1_AP_MASK | ATTR_S1_XN | ATTR_S1_IDX_MASK));
7604 * Given a leaf PTE, derive the mapping's attributes. If they do not match
7605 * those of the current run, dump the address range and its attributes, and
7609 sysctl_kmaps_check(struct sbuf *sb, struct pmap_kernel_map_range *range,
7610 vm_offset_t va, pd_entry_t l0e, pd_entry_t l1e, pd_entry_t l2e,
7615 attrs = sysctl_kmaps_table_attrs(l0e);
7617 if ((l1e & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
7618 attrs |= sysctl_kmaps_block_attrs(l1e);
7621 attrs |= sysctl_kmaps_table_attrs(l1e);
7623 if ((l2e & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK) {
7624 attrs |= sysctl_kmaps_block_attrs(l2e);
7627 attrs |= sysctl_kmaps_table_attrs(l2e);
7628 attrs |= sysctl_kmaps_block_attrs(l3e);
7631 if (range->sva > va || !sysctl_kmaps_match(range, attrs)) {
7632 sysctl_kmaps_dump(sb, range, va);
7633 sysctl_kmaps_reinit(range, va, attrs);
7638 sysctl_kmaps(SYSCTL_HANDLER_ARGS)
7640 struct pmap_kernel_map_range range;
7641 struct sbuf sbuf, *sb;
7642 pd_entry_t l0e, *l1, l1e, *l2, l2e;
7643 pt_entry_t *l3, l3e;
7646 int error, i, j, k, l;
7648 error = sysctl_wire_old_buffer(req, 0);
7652 sbuf_new_for_sysctl(sb, NULL, PAGE_SIZE, req);
7654 /* Sentinel value. */
7655 range.sva = 0xfffffffffffffffful;
7658 * Iterate over the kernel page tables without holding the kernel pmap
7659 * lock. Kernel page table pages are never freed, so at worst we will
7660 * observe inconsistencies in the output.
7662 for (sva = 0xffff000000000000ul, i = pmap_l0_index(sva); i < Ln_ENTRIES;
7664 if (i == pmap_l0_index(DMAP_MIN_ADDRESS))
7665 sbuf_printf(sb, "\nDirect map:\n");
7666 else if (i == pmap_l0_index(VM_MIN_KERNEL_ADDRESS))
7667 sbuf_printf(sb, "\nKernel map:\n");
7669 l0e = kernel_pmap->pm_l0[i];
7670 if ((l0e & ATTR_DESCR_VALID) == 0) {
7671 sysctl_kmaps_dump(sb, &range, sva);
7675 pa = l0e & ~ATTR_MASK;
7676 l1 = (pd_entry_t *)PHYS_TO_DMAP(pa);
7678 for (j = pmap_l1_index(sva); j < Ln_ENTRIES; j++) {
7680 if ((l1e & ATTR_DESCR_VALID) == 0) {
7681 sysctl_kmaps_dump(sb, &range, sva);
7685 if ((l1e & ATTR_DESCR_MASK) == L1_BLOCK) {
7686 PMAP_ASSERT_L1_BLOCKS_SUPPORTED;
7687 sysctl_kmaps_check(sb, &range, sva, l0e, l1e,
7693 pa = l1e & ~ATTR_MASK;
7694 l2 = (pd_entry_t *)PHYS_TO_DMAP(pa);
7696 for (k = pmap_l2_index(sva); k < Ln_ENTRIES; k++) {
7698 if ((l2e & ATTR_DESCR_VALID) == 0) {
7699 sysctl_kmaps_dump(sb, &range, sva);
7703 if ((l2e & ATTR_DESCR_MASK) == L2_BLOCK) {
7704 sysctl_kmaps_check(sb, &range, sva,
7710 pa = l2e & ~ATTR_MASK;
7711 l3 = (pt_entry_t *)PHYS_TO_DMAP(pa);
7713 for (l = pmap_l3_index(sva); l < Ln_ENTRIES;
7714 l++, sva += L3_SIZE) {
7716 if ((l3e & ATTR_DESCR_VALID) == 0) {
7717 sysctl_kmaps_dump(sb, &range,
7721 sysctl_kmaps_check(sb, &range, sva,
7722 l0e, l1e, l2e, l3e);
7723 if ((l3e & ATTR_CONTIGUOUS) != 0)
7724 range.l3contig += l % 16 == 0 ?
7733 error = sbuf_finish(sb);
7737 SYSCTL_OID(_vm_pmap, OID_AUTO, kernel_maps,
7738 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
7739 NULL, 0, sysctl_kmaps, "A",
7740 "Dump kernel address layout");