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>
153 #define PMAP_ASSERT_STAGE1(pmap) MPASS((pmap)->pm_stage == PM_STAGE1)
154 #define PMAP_ASSERT_STAGE2(pmap) MPASS((pmap)->pm_stage == PM_STAGE2)
156 #define NL0PG (PAGE_SIZE/(sizeof (pd_entry_t)))
157 #define NL1PG (PAGE_SIZE/(sizeof (pd_entry_t)))
158 #define NL2PG (PAGE_SIZE/(sizeof (pd_entry_t)))
159 #define NL3PG (PAGE_SIZE/(sizeof (pt_entry_t)))
161 #define NUL0E L0_ENTRIES
162 #define NUL1E (NUL0E * NL1PG)
163 #define NUL2E (NUL1E * NL2PG)
165 #if !defined(DIAGNOSTIC)
166 #ifdef __GNUC_GNU_INLINE__
167 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
169 #define PMAP_INLINE extern inline
176 #define PV_STAT(x) do { x ; } while (0)
178 #define PV_STAT(x) do { } while (0)
181 #define pmap_l0_pindex(v) (NUL2E + NUL1E + ((v) >> L0_SHIFT))
182 #define pmap_l1_pindex(v) (NUL2E + ((v) >> L1_SHIFT))
183 #define pmap_l2_pindex(v) ((v) >> L2_SHIFT)
185 static struct md_page *
186 pa_to_pvh(vm_paddr_t pa)
188 struct vm_phys_seg *seg;
191 for (segind = 0; segind < vm_phys_nsegs; segind++) {
192 seg = &vm_phys_segs[segind];
193 if (pa >= seg->start && pa < seg->end)
194 return ((struct md_page *)seg->md_first +
195 pmap_l2_pindex(pa) - pmap_l2_pindex(seg->start));
197 panic("pa 0x%jx not within vm_phys_segs", (uintmax_t)pa);
200 static struct md_page *
201 page_to_pvh(vm_page_t m)
203 struct vm_phys_seg *seg;
205 seg = &vm_phys_segs[m->segind];
206 return ((struct md_page *)seg->md_first +
207 pmap_l2_pindex(VM_PAGE_TO_PHYS(m)) - pmap_l2_pindex(seg->start));
210 #define NPV_LIST_LOCKS MAXCPU
212 #define PHYS_TO_PV_LIST_LOCK(pa) \
213 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
215 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
216 struct rwlock **_lockp = (lockp); \
217 struct rwlock *_new_lock; \
219 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
220 if (_new_lock != *_lockp) { \
221 if (*_lockp != NULL) \
222 rw_wunlock(*_lockp); \
223 *_lockp = _new_lock; \
228 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
229 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
231 #define RELEASE_PV_LIST_LOCK(lockp) do { \
232 struct rwlock **_lockp = (lockp); \
234 if (*_lockp != NULL) { \
235 rw_wunlock(*_lockp); \
240 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
241 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
244 * The presence of this flag indicates that the mapping is writeable.
245 * If the ATTR_S1_AP_RO bit is also set, then the mapping is clean, otherwise
246 * it is dirty. This flag may only be set on managed mappings.
248 * The DBM bit is reserved on ARMv8.0 but it seems we can safely treat it
249 * as a software managed bit.
251 #define ATTR_SW_DBM ATTR_DBM
253 struct pmap kernel_pmap_store;
255 /* Used for mapping ACPI memory before VM is initialized */
256 #define PMAP_PREINIT_MAPPING_COUNT 32
257 #define PMAP_PREINIT_MAPPING_SIZE (PMAP_PREINIT_MAPPING_COUNT * L2_SIZE)
258 static vm_offset_t preinit_map_va; /* Start VA of pre-init mapping space */
259 static int vm_initialized = 0; /* No need to use pre-init maps when set */
262 * Reserve a few L2 blocks starting from 'preinit_map_va' pointer.
263 * Always map entire L2 block for simplicity.
264 * VA of L2 block = preinit_map_va + i * L2_SIZE
266 static struct pmap_preinit_mapping {
270 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
272 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
273 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
274 vm_offset_t kernel_vm_end = 0;
277 * Data for the pv entry allocation mechanism.
279 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
280 static struct mtx pv_chunks_mutex;
281 static struct rwlock pv_list_locks[NPV_LIST_LOCKS];
282 static struct md_page *pv_table;
283 static struct md_page pv_dummy;
285 vm_paddr_t dmap_phys_base; /* The start of the dmap region */
286 vm_paddr_t dmap_phys_max; /* The limit of the dmap region */
287 vm_offset_t dmap_max_addr; /* The virtual address limit of the dmap */
289 /* This code assumes all L1 DMAP entries will be used */
290 CTASSERT((DMAP_MIN_ADDRESS & ~L0_OFFSET) == DMAP_MIN_ADDRESS);
291 CTASSERT((DMAP_MAX_ADDRESS & ~L0_OFFSET) == DMAP_MAX_ADDRESS);
293 #define DMAP_TABLES ((DMAP_MAX_ADDRESS - DMAP_MIN_ADDRESS) >> L0_SHIFT)
294 extern pt_entry_t pagetable_dmap[];
296 #define PHYSMAP_SIZE (2 * (VM_PHYSSEG_MAX - 1))
297 static vm_paddr_t physmap[PHYSMAP_SIZE];
298 static u_int physmap_idx;
300 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
301 "VM/pmap parameters");
304 * This ASID allocator uses a bit vector ("asid_set") to remember which ASIDs
305 * that it has currently allocated to a pmap, a cursor ("asid_next") to
306 * optimize its search for a free ASID in the bit vector, and an epoch number
307 * ("asid_epoch") to indicate when it has reclaimed all previously allocated
308 * ASIDs that are not currently active on a processor.
310 * The current epoch number is always in the range [0, INT_MAX). Negative
311 * numbers and INT_MAX are reserved for special cases that are described
320 struct mtx asid_set_mutex;
323 static struct asid_set asids;
324 static struct asid_set vmids;
326 static SYSCTL_NODE(_vm_pmap, OID_AUTO, asid, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
328 SYSCTL_INT(_vm_pmap_asid, OID_AUTO, bits, CTLFLAG_RD, &asids.asid_bits, 0,
329 "The number of bits in an ASID");
330 SYSCTL_INT(_vm_pmap_asid, OID_AUTO, next, CTLFLAG_RD, &asids.asid_next, 0,
331 "The last allocated ASID plus one");
332 SYSCTL_INT(_vm_pmap_asid, OID_AUTO, epoch, CTLFLAG_RD, &asids.asid_epoch, 0,
333 "The current epoch number");
335 static SYSCTL_NODE(_vm_pmap, OID_AUTO, vmid, CTLFLAG_RD, 0, "VMID allocator");
336 SYSCTL_INT(_vm_pmap_vmid, OID_AUTO, bits, CTLFLAG_RD, &vmids.asid_bits, 0,
337 "The number of bits in an VMID");
338 SYSCTL_INT(_vm_pmap_vmid, OID_AUTO, next, CTLFLAG_RD, &vmids.asid_next, 0,
339 "The last allocated VMID plus one");
340 SYSCTL_INT(_vm_pmap_vmid, OID_AUTO, epoch, CTLFLAG_RD, &vmids.asid_epoch, 0,
341 "The current epoch number");
343 void (*pmap_clean_stage2_tlbi)(void);
344 void (*pmap_invalidate_vpipt_icache)(void);
347 * A pmap's cookie encodes an ASID and epoch number. Cookies for reserved
348 * ASIDs have a negative epoch number, specifically, INT_MIN. Cookies for
349 * dynamically allocated ASIDs have a non-negative epoch number.
351 * An invalid ASID is represented by -1.
353 * There are two special-case cookie values: (1) COOKIE_FROM(-1, INT_MIN),
354 * which indicates that an ASID should never be allocated to the pmap, and
355 * (2) COOKIE_FROM(-1, INT_MAX), which indicates that an ASID should be
356 * allocated when the pmap is next activated.
358 #define COOKIE_FROM(asid, epoch) ((long)((u_int)(asid) | \
359 ((u_long)(epoch) << 32)))
360 #define COOKIE_TO_ASID(cookie) ((int)(cookie))
361 #define COOKIE_TO_EPOCH(cookie) ((int)((u_long)(cookie) >> 32))
363 static int superpages_enabled = 1;
364 SYSCTL_INT(_vm_pmap, OID_AUTO, superpages_enabled,
365 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &superpages_enabled, 0,
366 "Are large page mappings enabled?");
369 * Internal flags for pmap_enter()'s helper functions.
371 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
372 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
374 static void free_pv_chunk(struct pv_chunk *pc);
375 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
376 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
377 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
378 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
379 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
382 static void pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte);
383 static bool pmap_activate_int(pmap_t pmap);
384 static void pmap_alloc_asid(pmap_t pmap);
385 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode);
386 static pt_entry_t *pmap_demote_l1(pmap_t pmap, pt_entry_t *l1, vm_offset_t va);
387 static pt_entry_t *pmap_demote_l2_locked(pmap_t pmap, pt_entry_t *l2,
388 vm_offset_t va, struct rwlock **lockp);
389 static pt_entry_t *pmap_demote_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va);
390 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
391 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
392 static int pmap_enter_l2(pmap_t pmap, vm_offset_t va, pd_entry_t new_l2,
393 u_int flags, vm_page_t m, struct rwlock **lockp);
394 static int pmap_remove_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva,
395 pd_entry_t l1e, struct spglist *free, struct rwlock **lockp);
396 static int pmap_remove_l3(pmap_t pmap, pt_entry_t *l3, vm_offset_t sva,
397 pd_entry_t l2e, struct spglist *free, struct rwlock **lockp);
398 static void pmap_reset_asid_set(pmap_t pmap);
399 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
400 vm_page_t m, struct rwlock **lockp);
402 static vm_page_t _pmap_alloc_l3(pmap_t pmap, vm_pindex_t ptepindex,
403 struct rwlock **lockp);
405 static void _pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m,
406 struct spglist *free);
407 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
408 static __inline vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
411 * These load the old table data and store the new value.
412 * They need to be atomic as the System MMU may write to the table at
413 * the same time as the CPU.
415 #define pmap_clear(table) atomic_store_64(table, 0)
416 #define pmap_clear_bits(table, bits) atomic_clear_64(table, bits)
417 #define pmap_load(table) (*table)
418 #define pmap_load_clear(table) atomic_swap_64(table, 0)
419 #define pmap_load_store(table, entry) atomic_swap_64(table, entry)
420 #define pmap_set_bits(table, bits) atomic_set_64(table, bits)
421 #define pmap_store(table, entry) atomic_store_64(table, entry)
423 /********************/
424 /* Inline functions */
425 /********************/
428 pagecopy(void *s, void *d)
431 memcpy(d, s, PAGE_SIZE);
434 static __inline pd_entry_t *
435 pmap_l0(pmap_t pmap, vm_offset_t va)
438 return (&pmap->pm_l0[pmap_l0_index(va)]);
441 static __inline pd_entry_t *
442 pmap_l0_to_l1(pd_entry_t *l0, vm_offset_t va)
446 l1 = (pd_entry_t *)PHYS_TO_DMAP(pmap_load(l0) & ~ATTR_MASK);
447 return (&l1[pmap_l1_index(va)]);
450 static __inline pd_entry_t *
451 pmap_l1(pmap_t pmap, vm_offset_t va)
455 l0 = pmap_l0(pmap, va);
456 if ((pmap_load(l0) & ATTR_DESCR_MASK) != L0_TABLE)
459 return (pmap_l0_to_l1(l0, va));
462 static __inline pd_entry_t *
463 pmap_l1_to_l2(pd_entry_t *l1p, vm_offset_t va)
470 * The valid bit may be clear if pmap_update_entry() is concurrently
471 * modifying the entry, so for KVA only the entry type may be checked.
473 KASSERT(va >= VM_MAX_USER_ADDRESS || (l1 & ATTR_DESCR_VALID) != 0,
474 ("%s: L1 entry %#lx for %#lx is invalid", __func__, l1, va));
475 KASSERT((l1 & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_TABLE,
476 ("%s: L1 entry %#lx for %#lx is a leaf", __func__, l1, va));
477 l2p = (pd_entry_t *)PHYS_TO_DMAP(l1 & ~ATTR_MASK);
478 return (&l2p[pmap_l2_index(va)]);
481 static __inline pd_entry_t *
482 pmap_l2(pmap_t pmap, vm_offset_t va)
486 l1 = pmap_l1(pmap, va);
487 if ((pmap_load(l1) & ATTR_DESCR_MASK) != L1_TABLE)
490 return (pmap_l1_to_l2(l1, va));
493 static __inline pt_entry_t *
494 pmap_l2_to_l3(pd_entry_t *l2p, vm_offset_t va)
502 * The valid bit may be clear if pmap_update_entry() is concurrently
503 * modifying the entry, so for KVA only the entry type may be checked.
505 KASSERT(va >= VM_MAX_USER_ADDRESS || (l2 & ATTR_DESCR_VALID) != 0,
506 ("%s: L2 entry %#lx for %#lx is invalid", __func__, l2, va));
507 KASSERT((l2 & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_TABLE,
508 ("%s: L2 entry %#lx for %#lx is a leaf", __func__, l2, va));
509 l3p = (pt_entry_t *)PHYS_TO_DMAP(l2 & ~ATTR_MASK);
510 return (&l3p[pmap_l3_index(va)]);
514 * Returns the lowest valid pde for a given virtual address.
515 * The next level may or may not point to a valid page or block.
517 static __inline pd_entry_t *
518 pmap_pde(pmap_t pmap, vm_offset_t va, int *level)
520 pd_entry_t *l0, *l1, *l2, desc;
522 l0 = pmap_l0(pmap, va);
523 desc = pmap_load(l0) & ATTR_DESCR_MASK;
524 if (desc != L0_TABLE) {
529 l1 = pmap_l0_to_l1(l0, va);
530 desc = pmap_load(l1) & ATTR_DESCR_MASK;
531 if (desc != L1_TABLE) {
536 l2 = pmap_l1_to_l2(l1, va);
537 desc = pmap_load(l2) & ATTR_DESCR_MASK;
538 if (desc != L2_TABLE) {
548 * Returns the lowest valid pte block or table entry for a given virtual
549 * address. If there are no valid entries return NULL and set the level to
550 * the first invalid level.
552 static __inline pt_entry_t *
553 pmap_pte(pmap_t pmap, vm_offset_t va, int *level)
555 pd_entry_t *l1, *l2, desc;
558 l1 = pmap_l1(pmap, va);
563 desc = pmap_load(l1) & ATTR_DESCR_MASK;
564 if (desc == L1_BLOCK) {
569 if (desc != L1_TABLE) {
574 l2 = pmap_l1_to_l2(l1, va);
575 desc = pmap_load(l2) & ATTR_DESCR_MASK;
576 if (desc == L2_BLOCK) {
581 if (desc != L2_TABLE) {
587 l3 = pmap_l2_to_l3(l2, va);
588 if ((pmap_load(l3) & ATTR_DESCR_MASK) != L3_PAGE)
595 pmap_ps_enabled(pmap_t pmap __unused)
598 return (superpages_enabled != 0);
602 pmap_get_tables(pmap_t pmap, vm_offset_t va, pd_entry_t **l0, pd_entry_t **l1,
603 pd_entry_t **l2, pt_entry_t **l3)
605 pd_entry_t *l0p, *l1p, *l2p;
607 if (pmap->pm_l0 == NULL)
610 l0p = pmap_l0(pmap, va);
613 if ((pmap_load(l0p) & ATTR_DESCR_MASK) != L0_TABLE)
616 l1p = pmap_l0_to_l1(l0p, va);
619 if ((pmap_load(l1p) & ATTR_DESCR_MASK) == L1_BLOCK) {
625 if ((pmap_load(l1p) & ATTR_DESCR_MASK) != L1_TABLE)
628 l2p = pmap_l1_to_l2(l1p, va);
631 if ((pmap_load(l2p) & ATTR_DESCR_MASK) == L2_BLOCK) {
636 if ((pmap_load(l2p) & ATTR_DESCR_MASK) != L2_TABLE)
639 *l3 = pmap_l2_to_l3(l2p, va);
645 pmap_l3_valid(pt_entry_t l3)
648 return ((l3 & ATTR_DESCR_MASK) == L3_PAGE);
651 CTASSERT(L1_BLOCK == L2_BLOCK);
654 pmap_pte_memattr(pmap_t pmap, vm_memattr_t memattr)
658 if (pmap->pm_stage == PM_STAGE1) {
659 val = ATTR_S1_IDX(memattr);
660 if (memattr == VM_MEMATTR_DEVICE)
668 case VM_MEMATTR_DEVICE:
669 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_DEVICE_nGnRnE) |
670 ATTR_S2_XN(ATTR_S2_XN_ALL));
671 case VM_MEMATTR_UNCACHEABLE:
672 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_NC));
673 case VM_MEMATTR_WRITE_BACK:
674 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_WB));
675 case VM_MEMATTR_WRITE_THROUGH:
676 return (ATTR_S2_MEMATTR(ATTR_S2_MEMATTR_WT));
678 panic("%s: invalid memory attribute %x", __func__, memattr);
683 pmap_pte_prot(pmap_t pmap, vm_prot_t prot)
688 if (pmap->pm_stage == PM_STAGE1) {
689 if ((prot & VM_PROT_EXECUTE) == 0)
691 if ((prot & VM_PROT_WRITE) == 0)
692 val |= ATTR_S1_AP(ATTR_S1_AP_RO);
694 if ((prot & VM_PROT_WRITE) != 0)
695 val |= ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
696 if ((prot & VM_PROT_READ) != 0)
697 val |= ATTR_S2_S2AP(ATTR_S2_S2AP_READ);
698 if ((prot & VM_PROT_EXECUTE) == 0)
699 val |= ATTR_S2_XN(ATTR_S2_XN_ALL);
706 * Checks if the PTE is dirty.
709 pmap_pte_dirty(pmap_t pmap, pt_entry_t pte)
712 KASSERT((pte & ATTR_SW_MANAGED) != 0, ("pte %#lx is unmanaged", pte));
714 if (pmap->pm_stage == PM_STAGE1) {
715 KASSERT((pte & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) != 0,
716 ("pte %#lx is writeable and missing ATTR_SW_DBM", pte));
718 return ((pte & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
719 (ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_SW_DBM));
722 return ((pte & ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE)) ==
723 ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE));
727 pmap_resident_count_inc(pmap_t pmap, int count)
730 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
731 pmap->pm_stats.resident_count += count;
735 pmap_resident_count_dec(pmap_t pmap, int count)
738 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
739 KASSERT(pmap->pm_stats.resident_count >= count,
740 ("pmap %p resident count underflow %ld %d", pmap,
741 pmap->pm_stats.resident_count, count));
742 pmap->pm_stats.resident_count -= count;
746 pmap_early_page_idx(vm_offset_t l1pt, vm_offset_t va, u_int *l1_slot,
752 l1 = (pd_entry_t *)l1pt;
753 *l1_slot = (va >> L1_SHIFT) & Ln_ADDR_MASK;
755 /* Check locore has used a table L1 map */
756 KASSERT((l1[*l1_slot] & ATTR_DESCR_MASK) == L1_TABLE,
757 ("Invalid bootstrap L1 table"));
758 /* Find the address of the L2 table */
759 l2 = (pt_entry_t *)init_pt_va;
760 *l2_slot = pmap_l2_index(va);
766 pmap_early_vtophys(vm_offset_t l1pt, vm_offset_t va)
768 u_int l1_slot, l2_slot;
771 l2 = pmap_early_page_idx(l1pt, va, &l1_slot, &l2_slot);
773 return ((l2[l2_slot] & ~ATTR_MASK) + (va & L2_OFFSET));
777 pmap_bootstrap_dmap(vm_offset_t kern_l1, vm_paddr_t min_pa,
778 vm_offset_t freemempos)
782 vm_paddr_t l2_pa, pa;
783 u_int l1_slot, l2_slot, prev_l1_slot;
786 dmap_phys_base = min_pa & ~L1_OFFSET;
792 #define DMAP_TABLES ((DMAP_MAX_ADDRESS - DMAP_MIN_ADDRESS) >> L0_SHIFT)
793 memset(pagetable_dmap, 0, PAGE_SIZE * DMAP_TABLES);
795 for (i = 0; i < (physmap_idx * 2); i += 2) {
796 pa = physmap[i] & ~L2_OFFSET;
797 va = pa - dmap_phys_base + DMAP_MIN_ADDRESS;
799 /* Create L2 mappings at the start of the region */
800 if ((pa & L1_OFFSET) != 0) {
801 l1_slot = ((va - DMAP_MIN_ADDRESS) >> L1_SHIFT);
802 if (l1_slot != prev_l1_slot) {
803 prev_l1_slot = l1_slot;
804 l2 = (pt_entry_t *)freemempos;
805 l2_pa = pmap_early_vtophys(kern_l1,
807 freemempos += PAGE_SIZE;
809 pmap_store(&pagetable_dmap[l1_slot],
810 (l2_pa & ~Ln_TABLE_MASK) | L1_TABLE);
812 memset(l2, 0, PAGE_SIZE);
815 ("pmap_bootstrap_dmap: NULL l2 map"));
816 for (; va < DMAP_MAX_ADDRESS && pa < physmap[i + 1];
817 pa += L2_SIZE, va += L2_SIZE) {
819 * We are on a boundary, stop to
820 * create a level 1 block
822 if ((pa & L1_OFFSET) == 0)
825 l2_slot = pmap_l2_index(va);
826 KASSERT(l2_slot != 0, ("..."));
827 pmap_store(&l2[l2_slot],
828 (pa & ~L2_OFFSET) | ATTR_DEFAULT |
830 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) |
833 KASSERT(va == (pa - dmap_phys_base + DMAP_MIN_ADDRESS),
837 for (; va < DMAP_MAX_ADDRESS && pa < physmap[i + 1] &&
838 (physmap[i + 1] - pa) >= L1_SIZE;
839 pa += L1_SIZE, va += L1_SIZE) {
840 l1_slot = ((va - DMAP_MIN_ADDRESS) >> L1_SHIFT);
841 pmap_store(&pagetable_dmap[l1_slot],
842 (pa & ~L1_OFFSET) | ATTR_DEFAULT | ATTR_S1_XN |
843 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) | L1_BLOCK);
846 /* Create L2 mappings at the end of the region */
847 if (pa < physmap[i + 1]) {
848 l1_slot = ((va - DMAP_MIN_ADDRESS) >> L1_SHIFT);
849 if (l1_slot != prev_l1_slot) {
850 prev_l1_slot = l1_slot;
851 l2 = (pt_entry_t *)freemempos;
852 l2_pa = pmap_early_vtophys(kern_l1,
854 freemempos += PAGE_SIZE;
856 pmap_store(&pagetable_dmap[l1_slot],
857 (l2_pa & ~Ln_TABLE_MASK) | L1_TABLE);
859 memset(l2, 0, PAGE_SIZE);
862 ("pmap_bootstrap_dmap: NULL l2 map"));
863 for (; va < DMAP_MAX_ADDRESS && pa < physmap[i + 1];
864 pa += L2_SIZE, va += L2_SIZE) {
865 l2_slot = pmap_l2_index(va);
866 pmap_store(&l2[l2_slot],
867 (pa & ~L2_OFFSET) | ATTR_DEFAULT |
869 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) |
874 if (pa > dmap_phys_max) {
886 pmap_bootstrap_l2(vm_offset_t l1pt, vm_offset_t va, vm_offset_t l2_start)
893 KASSERT((va & L1_OFFSET) == 0, ("Invalid virtual address"));
895 l1 = (pd_entry_t *)l1pt;
896 l1_slot = pmap_l1_index(va);
899 for (; va < VM_MAX_KERNEL_ADDRESS; l1_slot++, va += L1_SIZE) {
900 KASSERT(l1_slot < Ln_ENTRIES, ("Invalid L1 index"));
902 pa = pmap_early_vtophys(l1pt, l2pt);
903 pmap_store(&l1[l1_slot],
904 (pa & ~Ln_TABLE_MASK) | L1_TABLE);
908 /* Clean the L2 page table */
909 memset((void *)l2_start, 0, l2pt - l2_start);
915 pmap_bootstrap_l3(vm_offset_t l1pt, vm_offset_t va, vm_offset_t l3_start)
922 KASSERT((va & L2_OFFSET) == 0, ("Invalid virtual address"));
924 l2 = pmap_l2(kernel_pmap, va);
925 l2 = (pd_entry_t *)rounddown2((uintptr_t)l2, PAGE_SIZE);
926 l2_slot = pmap_l2_index(va);
929 for (; va < VM_MAX_KERNEL_ADDRESS; l2_slot++, va += L2_SIZE) {
930 KASSERT(l2_slot < Ln_ENTRIES, ("Invalid L2 index"));
932 pa = pmap_early_vtophys(l1pt, l3pt);
933 pmap_store(&l2[l2_slot],
934 (pa & ~Ln_TABLE_MASK) | ATTR_S1_UXN | L2_TABLE);
938 /* Clean the L2 page table */
939 memset((void *)l3_start, 0, l3pt - l3_start);
945 * Bootstrap the system enough to run with virtual memory.
948 pmap_bootstrap(vm_offset_t l0pt, vm_offset_t l1pt, vm_paddr_t kernstart,
951 vm_offset_t freemempos;
952 vm_offset_t dpcpu, msgbufpv;
953 vm_paddr_t start_pa, pa, min_pa;
957 /* Verify that the ASID is set through TTBR0. */
958 KASSERT((READ_SPECIALREG(tcr_el1) & TCR_A1) == 0,
959 ("pmap_bootstrap: TCR_EL1.A1 != 0"));
961 kern_delta = KERNBASE - kernstart;
963 printf("pmap_bootstrap %lx %lx %lx\n", l1pt, kernstart, kernlen);
964 printf("%lx\n", l1pt);
965 printf("%lx\n", (KERNBASE >> L1_SHIFT) & Ln_ADDR_MASK);
967 /* Set this early so we can use the pagetable walking functions */
968 kernel_pmap_store.pm_l0 = (pd_entry_t *)l0pt;
969 PMAP_LOCK_INIT(kernel_pmap);
970 kernel_pmap->pm_l0_paddr = l0pt - kern_delta;
971 kernel_pmap->pm_cookie = COOKIE_FROM(-1, INT_MIN);
972 kernel_pmap->pm_stage = PM_STAGE1;
973 kernel_pmap->pm_levels = 4;
974 kernel_pmap->pm_ttbr = kernel_pmap->pm_l0_paddr;
975 kernel_pmap->pm_asid_set = &asids;
977 /* Assume the address we were loaded to is a valid physical address */
978 min_pa = KERNBASE - kern_delta;
980 physmap_idx = physmem_avail(physmap, nitems(physmap));
984 * Find the minimum physical address. physmap is sorted,
985 * but may contain empty ranges.
987 for (i = 0; i < physmap_idx * 2; i += 2) {
988 if (physmap[i] == physmap[i + 1])
990 if (physmap[i] <= min_pa)
994 freemempos = KERNBASE + kernlen;
995 freemempos = roundup2(freemempos, PAGE_SIZE);
997 /* Create a direct map region early so we can use it for pa -> va */
998 freemempos = pmap_bootstrap_dmap(l1pt, min_pa, freemempos);
1000 start_pa = pa = KERNBASE - kern_delta;
1003 * Create the l2 tables up to VM_MAX_KERNEL_ADDRESS. We assume that the
1004 * loader allocated the first and only l2 page table page used to map
1005 * the kernel, preloaded files and module metadata.
1007 freemempos = pmap_bootstrap_l2(l1pt, KERNBASE + L1_SIZE, freemempos);
1008 /* And the l3 tables for the early devmap */
1009 freemempos = pmap_bootstrap_l3(l1pt,
1010 VM_MAX_KERNEL_ADDRESS - (PMAP_MAPDEV_EARLY_SIZE), freemempos);
1014 #define alloc_pages(var, np) \
1015 (var) = freemempos; \
1016 freemempos += (np * PAGE_SIZE); \
1017 memset((char *)(var), 0, ((np) * PAGE_SIZE));
1019 /* Allocate dynamic per-cpu area. */
1020 alloc_pages(dpcpu, DPCPU_SIZE / PAGE_SIZE);
1021 dpcpu_init((void *)dpcpu, 0);
1023 /* Allocate memory for the msgbuf, e.g. for /sbin/dmesg */
1024 alloc_pages(msgbufpv, round_page(msgbufsize) / PAGE_SIZE);
1025 msgbufp = (void *)msgbufpv;
1027 /* Reserve some VA space for early BIOS/ACPI mapping */
1028 preinit_map_va = roundup2(freemempos, L2_SIZE);
1030 virtual_avail = preinit_map_va + PMAP_PREINIT_MAPPING_SIZE;
1031 virtual_avail = roundup2(virtual_avail, L1_SIZE);
1032 virtual_end = VM_MAX_KERNEL_ADDRESS - (PMAP_MAPDEV_EARLY_SIZE);
1033 kernel_vm_end = virtual_avail;
1035 pa = pmap_early_vtophys(l1pt, freemempos);
1037 physmem_exclude_region(start_pa, pa - start_pa, EXFLAG_NOALLOC);
1043 * Initialize a vm_page's machine-dependent fields.
1046 pmap_page_init(vm_page_t m)
1049 TAILQ_INIT(&m->md.pv_list);
1050 m->md.pv_memattr = VM_MEMATTR_WRITE_BACK;
1054 pmap_init_asids(struct asid_set *set, int bits)
1058 set->asid_bits = bits;
1061 * We may be too early in the overall initialization process to use
1064 set->asid_set_size = 1 << set->asid_bits;
1065 set->asid_set = (bitstr_t *)kmem_malloc(bitstr_size(set->asid_set_size),
1067 for (i = 0; i < ASID_FIRST_AVAILABLE; i++)
1068 bit_set(set->asid_set, i);
1069 set->asid_next = ASID_FIRST_AVAILABLE;
1070 mtx_init(&set->asid_set_mutex, "asid set", NULL, MTX_SPIN);
1074 * Initialize the pmap module.
1075 * Called by vm_init, to initialize any structures that the pmap
1076 * system needs to map virtual memory.
1081 struct vm_phys_seg *seg, *next_seg;
1082 struct md_page *pvh;
1085 int i, pv_npg, vmid_bits;
1088 * Are large page mappings enabled?
1090 TUNABLE_INT_FETCH("vm.pmap.superpages_enabled", &superpages_enabled);
1091 if (superpages_enabled) {
1092 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1093 ("pmap_init: can't assign to pagesizes[1]"));
1094 pagesizes[1] = L2_SIZE;
1095 KASSERT(MAXPAGESIZES > 2 && pagesizes[2] == 0,
1096 ("pmap_init: can't assign to pagesizes[2]"));
1097 pagesizes[2] = L1_SIZE;
1101 * Initialize the ASID allocator.
1103 pmap_init_asids(&asids,
1104 (READ_SPECIALREG(tcr_el1) & TCR_ASID_16) != 0 ? 16 : 8);
1107 mmfr1 = READ_SPECIALREG(id_aa64mmfr1_el1);
1110 if (ID_AA64MMFR1_VMIDBits_VAL(mmfr1) ==
1111 ID_AA64MMFR1_VMIDBits_16)
1113 pmap_init_asids(&vmids, vmid_bits);
1117 * Initialize the pv chunk list mutex.
1119 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1122 * Initialize the pool of pv list locks.
1124 for (i = 0; i < NPV_LIST_LOCKS; i++)
1125 rw_init(&pv_list_locks[i], "pmap pv list");
1128 * Calculate the size of the pv head table for superpages.
1131 for (i = 0; i < vm_phys_nsegs; i++) {
1132 seg = &vm_phys_segs[i];
1133 pv_npg += pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) -
1134 pmap_l2_pindex(seg->start);
1138 * Allocate memory for the pv head table for superpages.
1140 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1142 pv_table = (struct md_page *)kmem_malloc(s, M_WAITOK | M_ZERO);
1143 for (i = 0; i < pv_npg; i++)
1144 TAILQ_INIT(&pv_table[i].pv_list);
1145 TAILQ_INIT(&pv_dummy.pv_list);
1148 * Set pointers from vm_phys_segs to pv_table.
1150 for (i = 0, pvh = pv_table; i < vm_phys_nsegs; i++) {
1151 seg = &vm_phys_segs[i];
1152 seg->md_first = pvh;
1153 pvh += pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) -
1154 pmap_l2_pindex(seg->start);
1157 * If there is a following segment, and the final
1158 * superpage of this segment and the initial superpage
1159 * of the next segment are the same then adjust the
1160 * pv_table entry for that next segment down by one so
1161 * that the pv_table entries will be shared.
1163 if (i + 1 < vm_phys_nsegs) {
1164 next_seg = &vm_phys_segs[i + 1];
1165 if (pmap_l2_pindex(roundup2(seg->end, L2_SIZE)) - 1 ==
1166 pmap_l2_pindex(next_seg->start)) {
1175 static SYSCTL_NODE(_vm_pmap, OID_AUTO, l2, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
1176 "2MB page mapping counters");
1178 static u_long pmap_l2_demotions;
1179 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, demotions, CTLFLAG_RD,
1180 &pmap_l2_demotions, 0, "2MB page demotions");
1182 static u_long pmap_l2_mappings;
1183 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, mappings, CTLFLAG_RD,
1184 &pmap_l2_mappings, 0, "2MB page mappings");
1186 static u_long pmap_l2_p_failures;
1187 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, p_failures, CTLFLAG_RD,
1188 &pmap_l2_p_failures, 0, "2MB page promotion failures");
1190 static u_long pmap_l2_promotions;
1191 SYSCTL_ULONG(_vm_pmap_l2, OID_AUTO, promotions, CTLFLAG_RD,
1192 &pmap_l2_promotions, 0, "2MB page promotions");
1195 * Invalidate a single TLB entry.
1197 static __inline void
1198 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1202 PMAP_ASSERT_STAGE1(pmap);
1205 if (pmap == kernel_pmap) {
1207 __asm __volatile("tlbi vaae1is, %0" : : "r" (r));
1209 r = ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie)) | atop(va);
1210 __asm __volatile("tlbi vae1is, %0" : : "r" (r));
1216 static __inline void
1217 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1219 uint64_t end, r, start;
1221 PMAP_ASSERT_STAGE1(pmap);
1224 if (pmap == kernel_pmap) {
1227 for (r = start; r < end; r++)
1228 __asm __volatile("tlbi vaae1is, %0" : : "r" (r));
1230 start = end = ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
1233 for (r = start; r < end; r++)
1234 __asm __volatile("tlbi vae1is, %0" : : "r" (r));
1240 static __inline void
1241 pmap_invalidate_all(pmap_t pmap)
1245 PMAP_ASSERT_STAGE1(pmap);
1248 if (pmap == kernel_pmap) {
1249 __asm __volatile("tlbi vmalle1is");
1251 r = ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie));
1252 __asm __volatile("tlbi aside1is, %0" : : "r" (r));
1259 * Routine: pmap_extract
1261 * Extract the physical page address associated
1262 * with the given map/virtual_address pair.
1265 pmap_extract(pmap_t pmap, vm_offset_t va)
1267 pt_entry_t *pte, tpte;
1274 * Find the block or page map for this virtual address. pmap_pte
1275 * will return either a valid block/page entry, or NULL.
1277 pte = pmap_pte(pmap, va, &lvl);
1279 tpte = pmap_load(pte);
1280 pa = tpte & ~ATTR_MASK;
1283 KASSERT((tpte & ATTR_DESCR_MASK) == L1_BLOCK,
1284 ("pmap_extract: Invalid L1 pte found: %lx",
1285 tpte & ATTR_DESCR_MASK));
1286 pa |= (va & L1_OFFSET);
1289 KASSERT((tpte & ATTR_DESCR_MASK) == L2_BLOCK,
1290 ("pmap_extract: Invalid L2 pte found: %lx",
1291 tpte & ATTR_DESCR_MASK));
1292 pa |= (va & L2_OFFSET);
1295 KASSERT((tpte & ATTR_DESCR_MASK) == L3_PAGE,
1296 ("pmap_extract: Invalid L3 pte found: %lx",
1297 tpte & ATTR_DESCR_MASK));
1298 pa |= (va & L3_OFFSET);
1307 * Routine: pmap_extract_and_hold
1309 * Atomically extract and hold the physical page
1310 * with the given pmap and virtual address pair
1311 * if that mapping permits the given protection.
1314 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1316 pt_entry_t *pte, tpte;
1324 pte = pmap_pte(pmap, va, &lvl);
1326 tpte = pmap_load(pte);
1328 KASSERT(lvl > 0 && lvl <= 3,
1329 ("pmap_extract_and_hold: Invalid level %d", lvl));
1330 CTASSERT(L1_BLOCK == L2_BLOCK);
1331 KASSERT((lvl == 3 && (tpte & ATTR_DESCR_MASK) == L3_PAGE) ||
1332 (lvl < 3 && (tpte & ATTR_DESCR_MASK) == L1_BLOCK),
1333 ("pmap_extract_and_hold: Invalid pte at L%d: %lx", lvl,
1334 tpte & ATTR_DESCR_MASK));
1337 if ((prot & VM_PROT_WRITE) == 0)
1339 else if (pmap->pm_stage == PM_STAGE1 &&
1340 (tpte & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP(ATTR_S1_AP_RW))
1342 else if (pmap->pm_stage == PM_STAGE2 &&
1343 ((tpte & ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE)) ==
1344 ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE)))
1350 off = va & L1_OFFSET;
1353 off = va & L2_OFFSET;
1359 m = PHYS_TO_VM_PAGE((tpte & ~ATTR_MASK) | off);
1360 if (m != NULL && !vm_page_wire_mapped(m))
1369 pmap_kextract(vm_offset_t va)
1371 pt_entry_t *pte, tpte;
1373 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
1374 return (DMAP_TO_PHYS(va));
1375 pte = pmap_l1(kernel_pmap, va);
1380 * A concurrent pmap_update_entry() will clear the entry's valid bit
1381 * but leave the rest of the entry unchanged. Therefore, we treat a
1382 * non-zero entry as being valid, and we ignore the valid bit when
1383 * determining whether the entry maps a block, page, or table.
1385 tpte = pmap_load(pte);
1388 if ((tpte & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK)
1389 return ((tpte & ~ATTR_MASK) | (va & L1_OFFSET));
1390 pte = pmap_l1_to_l2(&tpte, va);
1391 tpte = pmap_load(pte);
1394 if ((tpte & ATTR_DESCR_TYPE_MASK) == ATTR_DESCR_TYPE_BLOCK)
1395 return ((tpte & ~ATTR_MASK) | (va & L2_OFFSET));
1396 pte = pmap_l2_to_l3(&tpte, va);
1397 tpte = pmap_load(pte);
1400 return ((tpte & ~ATTR_MASK) | (va & L3_OFFSET));
1403 /***************************************************
1404 * Low level mapping routines.....
1405 ***************************************************/
1408 pmap_kenter(vm_offset_t sva, vm_size_t size, vm_paddr_t pa, int mode)
1411 pt_entry_t *pte, attr;
1415 KASSERT((pa & L3_OFFSET) == 0,
1416 ("pmap_kenter: Invalid physical address"));
1417 KASSERT((sva & L3_OFFSET) == 0,
1418 ("pmap_kenter: Invalid virtual address"));
1419 KASSERT((size & PAGE_MASK) == 0,
1420 ("pmap_kenter: Mapping is not page-sized"));
1422 attr = ATTR_DEFAULT | ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_S1_XN |
1423 ATTR_S1_IDX(mode) | L3_PAGE;
1426 pde = pmap_pde(kernel_pmap, va, &lvl);
1427 KASSERT(pde != NULL,
1428 ("pmap_kenter: Invalid page entry, va: 0x%lx", va));
1429 KASSERT(lvl == 2, ("pmap_kenter: Invalid level %d", lvl));
1431 pte = pmap_l2_to_l3(pde, va);
1432 pmap_load_store(pte, (pa & ~L3_OFFSET) | attr);
1438 pmap_invalidate_range(kernel_pmap, sva, va);
1442 pmap_kenter_device(vm_offset_t sva, vm_size_t size, vm_paddr_t pa)
1445 pmap_kenter(sva, size, pa, VM_MEMATTR_DEVICE);
1449 * Remove a page from the kernel pagetables.
1452 pmap_kremove(vm_offset_t va)
1457 pte = pmap_pte(kernel_pmap, va, &lvl);
1458 KASSERT(pte != NULL, ("pmap_kremove: Invalid address"));
1459 KASSERT(lvl == 3, ("pmap_kremove: Invalid pte level %d", lvl));
1462 pmap_invalidate_page(kernel_pmap, va);
1466 pmap_kremove_device(vm_offset_t sva, vm_size_t size)
1472 KASSERT((sva & L3_OFFSET) == 0,
1473 ("pmap_kremove_device: Invalid virtual address"));
1474 KASSERT((size & PAGE_MASK) == 0,
1475 ("pmap_kremove_device: Mapping is not page-sized"));
1479 pte = pmap_pte(kernel_pmap, va, &lvl);
1480 KASSERT(pte != NULL, ("Invalid page table, va: 0x%lx", va));
1482 ("Invalid device pagetable level: %d != 3", lvl));
1488 pmap_invalidate_range(kernel_pmap, sva, va);
1492 * Used to map a range of physical addresses into kernel
1493 * virtual address space.
1495 * The value passed in '*virt' is a suggested virtual address for
1496 * the mapping. Architectures which can support a direct-mapped
1497 * physical to virtual region can return the appropriate address
1498 * within that region, leaving '*virt' unchanged. Other
1499 * architectures should map the pages starting at '*virt' and
1500 * update '*virt' with the first usable address after the mapped
1504 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
1506 return PHYS_TO_DMAP(start);
1510 * Add a list of wired pages to the kva
1511 * this routine is only used for temporary
1512 * kernel mappings that do not need to have
1513 * page modification or references recorded.
1514 * Note that old mappings are simply written
1515 * over. The page *must* be wired.
1516 * Note: SMP coherent. Uses a ranged shootdown IPI.
1519 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
1522 pt_entry_t *pte, pa;
1528 for (i = 0; i < count; i++) {
1529 pde = pmap_pde(kernel_pmap, va, &lvl);
1530 KASSERT(pde != NULL,
1531 ("pmap_qenter: Invalid page entry, va: 0x%lx", va));
1533 ("pmap_qenter: Invalid level %d", lvl));
1536 pa = VM_PAGE_TO_PHYS(m) | ATTR_DEFAULT |
1537 ATTR_S1_AP(ATTR_S1_AP_RW) | ATTR_S1_XN |
1538 ATTR_S1_IDX(m->md.pv_memattr) | L3_PAGE;
1539 pte = pmap_l2_to_l3(pde, va);
1540 pmap_load_store(pte, pa);
1544 pmap_invalidate_range(kernel_pmap, sva, va);
1548 * This routine tears out page mappings from the
1549 * kernel -- it is meant only for temporary mappings.
1552 pmap_qremove(vm_offset_t sva, int count)
1558 KASSERT(sva >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", sva));
1561 while (count-- > 0) {
1562 pte = pmap_pte(kernel_pmap, va, &lvl);
1564 ("Invalid device pagetable level: %d != 3", lvl));
1571 pmap_invalidate_range(kernel_pmap, sva, va);
1574 /***************************************************
1575 * Page table page management routines.....
1576 ***************************************************/
1578 * Schedule the specified unused page table page to be freed. Specifically,
1579 * add the page to the specified list of pages that will be released to the
1580 * physical memory manager after the TLB has been updated.
1582 static __inline void
1583 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
1584 boolean_t set_PG_ZERO)
1588 m->flags |= PG_ZERO;
1590 m->flags &= ~PG_ZERO;
1591 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
1595 * Decrements a page table page's reference count, which is used to record the
1596 * number of valid page table entries within the page. If the reference count
1597 * drops to zero, then the page table page is unmapped. Returns TRUE if the
1598 * page table page was unmapped and FALSE otherwise.
1600 static inline boolean_t
1601 pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
1605 if (m->ref_count == 0) {
1606 _pmap_unwire_l3(pmap, va, m, free);
1613 _pmap_unwire_l3(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
1616 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1618 * unmap the page table page
1620 if (m->pindex >= (NUL2E + NUL1E)) {
1624 l0 = pmap_l0(pmap, va);
1626 } else if (m->pindex >= NUL2E) {
1630 l1 = pmap_l1(pmap, va);
1636 l2 = pmap_l2(pmap, va);
1639 pmap_resident_count_dec(pmap, 1);
1640 if (m->pindex < NUL2E) {
1641 /* We just released an l3, unhold the matching l2 */
1642 pd_entry_t *l1, tl1;
1645 l1 = pmap_l1(pmap, va);
1646 tl1 = pmap_load(l1);
1647 l2pg = PHYS_TO_VM_PAGE(tl1 & ~ATTR_MASK);
1648 pmap_unwire_l3(pmap, va, l2pg, free);
1649 } else if (m->pindex < (NUL2E + NUL1E)) {
1650 /* We just released an l2, unhold the matching l1 */
1651 pd_entry_t *l0, tl0;
1654 l0 = pmap_l0(pmap, va);
1655 tl0 = pmap_load(l0);
1656 l1pg = PHYS_TO_VM_PAGE(tl0 & ~ATTR_MASK);
1657 pmap_unwire_l3(pmap, va, l1pg, free);
1659 pmap_invalidate_page(pmap, va);
1662 * Put page on a list so that it is released after
1663 * *ALL* TLB shootdown is done
1665 pmap_add_delayed_free_list(m, free, TRUE);
1669 * After removing a page table entry, this routine is used to
1670 * conditionally free the page, and manage the reference count.
1673 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
1674 struct spglist *free)
1678 if (va >= VM_MAXUSER_ADDRESS)
1680 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
1681 mpte = PHYS_TO_VM_PAGE(ptepde & ~ATTR_MASK);
1682 return (pmap_unwire_l3(pmap, va, mpte, free));
1686 * Release a page table page reference after a failed attempt to create a
1690 pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
1692 struct spglist free;
1695 if (pmap_unwire_l3(pmap, va, mpte, &free)) {
1697 * Although "va" was never mapped, the TLB could nonetheless
1698 * have intermediate entries that refer to the freed page
1699 * table pages. Invalidate those entries.
1701 * XXX redundant invalidation (See _pmap_unwire_l3().)
1703 pmap_invalidate_page(pmap, va);
1704 vm_page_free_pages_toq(&free, true);
1709 pmap_pinit0(pmap_t pmap)
1712 PMAP_LOCK_INIT(pmap);
1713 bzero(&pmap->pm_stats, sizeof(pmap->pm_stats));
1714 pmap->pm_l0_paddr = READ_SPECIALREG(ttbr0_el1);
1715 pmap->pm_l0 = (pd_entry_t *)PHYS_TO_DMAP(pmap->pm_l0_paddr);
1716 pmap->pm_root.rt_root = 0;
1717 pmap->pm_cookie = COOKIE_FROM(ASID_RESERVED_FOR_PID_0, INT_MIN);
1718 pmap->pm_stage = PM_STAGE1;
1719 pmap->pm_levels = 4;
1720 pmap->pm_ttbr = pmap->pm_l0_paddr;
1721 pmap->pm_asid_set = &asids;
1723 PCPU_SET(curpmap, pmap);
1727 pmap_pinit_stage(pmap_t pmap, enum pmap_stage stage, int levels)
1732 * allocate the l0 page
1734 while ((m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
1735 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL)
1738 pmap->pm_l0_paddr = VM_PAGE_TO_PHYS(m);
1739 pmap->pm_l0 = (pd_entry_t *)PHYS_TO_DMAP(pmap->pm_l0_paddr);
1741 if ((m->flags & PG_ZERO) == 0)
1742 pagezero(pmap->pm_l0);
1744 pmap->pm_root.rt_root = 0;
1745 bzero(&pmap->pm_stats, sizeof(pmap->pm_stats));
1746 pmap->pm_cookie = COOKIE_FROM(-1, INT_MAX);
1748 MPASS(levels == 3 || levels == 4);
1749 pmap->pm_levels = levels;
1750 pmap->pm_stage = stage;
1753 pmap->pm_asid_set = &asids;
1756 pmap->pm_asid_set = &vmids;
1759 panic("%s: Invalid pmap type %d", __func__, stage);
1763 /* XXX Temporarily disable deferred ASID allocation. */
1764 pmap_alloc_asid(pmap);
1767 * Allocate the level 1 entry to use as the root. This will increase
1768 * the refcount on the level 1 page so it won't be removed until
1769 * pmap_release() is called.
1771 if (pmap->pm_levels == 3) {
1773 m = _pmap_alloc_l3(pmap, NUL2E + NUL1E, NULL);
1776 pmap->pm_ttbr = VM_PAGE_TO_PHYS(m);
1782 pmap_pinit(pmap_t pmap)
1785 return (pmap_pinit_stage(pmap, PM_STAGE1, 4));
1789 * This routine is called if the desired page table page does not exist.
1791 * If page table page allocation fails, this routine may sleep before
1792 * returning NULL. It sleeps only if a lock pointer was given.
1794 * Note: If a page allocation fails at page table level two or three,
1795 * one or two pages may be held during the wait, only to be released
1796 * afterwards. This conservative approach is easily argued to avoid
1800 _pmap_alloc_l3(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
1802 vm_page_t m, l1pg, l2pg;
1804 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1807 * Allocate a page table page.
1809 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
1810 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
1811 if (lockp != NULL) {
1812 RELEASE_PV_LIST_LOCK(lockp);
1819 * Indicate the need to retry. While waiting, the page table
1820 * page may have been allocated.
1824 if ((m->flags & PG_ZERO) == 0)
1828 * Because of AArch64's weak memory consistency model, we must have a
1829 * barrier here to ensure that the stores for zeroing "m", whether by
1830 * pmap_zero_page() or an earlier function, are visible before adding
1831 * "m" to the page table. Otherwise, a page table walk by another
1832 * processor's MMU could see the mapping to "m" and a stale, non-zero
1838 * Map the pagetable page into the process address space, if
1839 * it isn't already there.
1842 if (ptepindex >= (NUL2E + NUL1E)) {
1844 vm_pindex_t l0index;
1846 l0index = ptepindex - (NUL2E + NUL1E);
1847 l0 = &pmap->pm_l0[l0index];
1848 pmap_store(l0, VM_PAGE_TO_PHYS(m) | L0_TABLE);
1849 } else if (ptepindex >= NUL2E) {
1850 vm_pindex_t l0index, l1index;
1851 pd_entry_t *l0, *l1;
1854 l1index = ptepindex - NUL2E;
1855 l0index = l1index >> L0_ENTRIES_SHIFT;
1857 l0 = &pmap->pm_l0[l0index];
1858 tl0 = pmap_load(l0);
1860 /* recurse for allocating page dir */
1861 if (_pmap_alloc_l3(pmap, NUL2E + NUL1E + l0index,
1863 vm_page_unwire_noq(m);
1864 vm_page_free_zero(m);
1868 l1pg = PHYS_TO_VM_PAGE(tl0 & ~ATTR_MASK);
1872 l1 = (pd_entry_t *)PHYS_TO_DMAP(pmap_load(l0) & ~ATTR_MASK);
1873 l1 = &l1[ptepindex & Ln_ADDR_MASK];
1874 pmap_store(l1, VM_PAGE_TO_PHYS(m) | L1_TABLE);
1876 vm_pindex_t l0index, l1index;
1877 pd_entry_t *l0, *l1, *l2;
1878 pd_entry_t tl0, tl1;
1880 l1index = ptepindex >> Ln_ENTRIES_SHIFT;
1881 l0index = l1index >> L0_ENTRIES_SHIFT;
1883 l0 = &pmap->pm_l0[l0index];
1884 tl0 = pmap_load(l0);
1886 /* recurse for allocating page dir */
1887 if (_pmap_alloc_l3(pmap, NUL2E + l1index,
1889 vm_page_unwire_noq(m);
1890 vm_page_free_zero(m);
1893 tl0 = pmap_load(l0);
1894 l1 = (pd_entry_t *)PHYS_TO_DMAP(tl0 & ~ATTR_MASK);
1895 l1 = &l1[l1index & Ln_ADDR_MASK];
1897 l1 = (pd_entry_t *)PHYS_TO_DMAP(tl0 & ~ATTR_MASK);
1898 l1 = &l1[l1index & Ln_ADDR_MASK];
1899 tl1 = pmap_load(l1);
1901 /* recurse for allocating page dir */
1902 if (_pmap_alloc_l3(pmap, NUL2E + l1index,
1904 vm_page_unwire_noq(m);
1905 vm_page_free_zero(m);
1909 l2pg = PHYS_TO_VM_PAGE(tl1 & ~ATTR_MASK);
1914 l2 = (pd_entry_t *)PHYS_TO_DMAP(pmap_load(l1) & ~ATTR_MASK);
1915 l2 = &l2[ptepindex & Ln_ADDR_MASK];
1916 pmap_store(l2, VM_PAGE_TO_PHYS(m) | L2_TABLE);
1919 pmap_resident_count_inc(pmap, 1);
1925 pmap_alloc_l2(pmap_t pmap, vm_offset_t va, vm_page_t *l2pgp,
1926 struct rwlock **lockp)
1928 pd_entry_t *l1, *l2;
1930 vm_pindex_t l2pindex;
1933 l1 = pmap_l1(pmap, va);
1934 if (l1 != NULL && (pmap_load(l1) & ATTR_DESCR_MASK) == L1_TABLE) {
1935 l2 = pmap_l1_to_l2(l1, va);
1936 if (va < VM_MAXUSER_ADDRESS) {
1937 /* Add a reference to the L2 page. */
1938 l2pg = PHYS_TO_VM_PAGE(pmap_load(l1) & ~ATTR_MASK);
1942 } else if (va < VM_MAXUSER_ADDRESS) {
1943 /* Allocate a L2 page. */
1944 l2pindex = pmap_l2_pindex(va) >> Ln_ENTRIES_SHIFT;
1945 l2pg = _pmap_alloc_l3(pmap, NUL2E + l2pindex, lockp);
1952 l2 = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(l2pg));
1953 l2 = &l2[pmap_l2_index(va)];
1955 panic("pmap_alloc_l2: missing page table page for va %#lx",
1962 pmap_alloc_l3(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
1964 vm_pindex_t ptepindex;
1965 pd_entry_t *pde, tpde;
1973 * Calculate pagetable page index
1975 ptepindex = pmap_l2_pindex(va);
1978 * Get the page directory entry
1980 pde = pmap_pde(pmap, va, &lvl);
1983 * If the page table page is mapped, we just increment the hold count,
1984 * and activate it. If we get a level 2 pde it will point to a level 3
1992 pte = pmap_l0_to_l1(pde, va);
1993 KASSERT(pmap_load(pte) == 0,
1994 ("pmap_alloc_l3: TODO: l0 superpages"));
1999 pte = pmap_l1_to_l2(pde, va);
2000 KASSERT(pmap_load(pte) == 0,
2001 ("pmap_alloc_l3: TODO: l1 superpages"));
2005 tpde = pmap_load(pde);
2007 m = PHYS_TO_VM_PAGE(tpde & ~ATTR_MASK);
2013 panic("pmap_alloc_l3: Invalid level %d", lvl);
2017 * Here if the pte page isn't mapped, or if it has been deallocated.
2019 m = _pmap_alloc_l3(pmap, ptepindex, lockp);
2020 if (m == NULL && lockp != NULL)
2026 /***************************************************
2027 * Pmap allocation/deallocation routines.
2028 ***************************************************/
2031 * Release any resources held by the given physical map.
2032 * Called when a pmap initialized by pmap_pinit is being released.
2033 * Should only be called if the map contains no valid mappings.
2036 pmap_release(pmap_t pmap)
2039 struct spglist free;
2040 struct asid_set *set;
2044 if (pmap->pm_levels != 4) {
2045 PMAP_ASSERT_STAGE2(pmap);
2046 KASSERT(pmap->pm_stats.resident_count == 1,
2047 ("pmap_release: pmap resident count %ld != 0",
2048 pmap->pm_stats.resident_count));
2049 KASSERT((pmap->pm_l0[0] & ATTR_DESCR_VALID) == ATTR_DESCR_VALID,
2050 ("pmap_release: Invalid l0 entry: %lx", pmap->pm_l0[0]));
2053 m = PHYS_TO_VM_PAGE(pmap->pm_ttbr);
2055 rv = pmap_unwire_l3(pmap, 0, m, &free);
2058 vm_page_free_pages_toq(&free, true);
2061 KASSERT(pmap->pm_stats.resident_count == 0,
2062 ("pmap_release: pmap resident count %ld != 0",
2063 pmap->pm_stats.resident_count));
2064 KASSERT(vm_radix_is_empty(&pmap->pm_root),
2065 ("pmap_release: pmap has reserved page table page(s)"));
2067 set = pmap->pm_asid_set;
2068 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
2071 * Allow the ASID to be reused. In stage 2 VMIDs we don't invalidate
2072 * the entries when removing them so rely on a later tlb invalidation.
2073 * this will happen when updating the VMID generation. Because of this
2074 * we don't reuse VMIDs within a generation.
2076 if (pmap->pm_stage == PM_STAGE1) {
2077 mtx_lock_spin(&set->asid_set_mutex);
2078 if (COOKIE_TO_EPOCH(pmap->pm_cookie) == set->asid_epoch) {
2079 asid = COOKIE_TO_ASID(pmap->pm_cookie);
2080 KASSERT(asid >= ASID_FIRST_AVAILABLE &&
2081 asid < set->asid_set_size,
2082 ("pmap_release: pmap cookie has out-of-range asid"));
2083 bit_clear(set->asid_set, asid);
2085 mtx_unlock_spin(&set->asid_set_mutex);
2088 m = PHYS_TO_VM_PAGE(pmap->pm_l0_paddr);
2089 vm_page_unwire_noq(m);
2090 vm_page_free_zero(m);
2094 kvm_size(SYSCTL_HANDLER_ARGS)
2096 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
2098 return sysctl_handle_long(oidp, &ksize, 0, req);
2100 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
2101 0, 0, kvm_size, "LU",
2105 kvm_free(SYSCTL_HANDLER_ARGS)
2107 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2109 return sysctl_handle_long(oidp, &kfree, 0, req);
2111 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
2112 0, 0, kvm_free, "LU",
2113 "Amount of KVM free");
2116 * grow the number of kernel page table entries, if needed
2119 pmap_growkernel(vm_offset_t addr)
2123 pd_entry_t *l0, *l1, *l2;
2125 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2127 addr = roundup2(addr, L2_SIZE);
2128 if (addr - 1 >= vm_map_max(kernel_map))
2129 addr = vm_map_max(kernel_map);
2130 while (kernel_vm_end < addr) {
2131 l0 = pmap_l0(kernel_pmap, kernel_vm_end);
2132 KASSERT(pmap_load(l0) != 0,
2133 ("pmap_growkernel: No level 0 kernel entry"));
2135 l1 = pmap_l0_to_l1(l0, kernel_vm_end);
2136 if (pmap_load(l1) == 0) {
2137 /* We need a new PDP entry */
2138 nkpg = vm_page_alloc(NULL, kernel_vm_end >> L1_SHIFT,
2139 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
2140 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
2142 panic("pmap_growkernel: no memory to grow kernel");
2143 if ((nkpg->flags & PG_ZERO) == 0)
2144 pmap_zero_page(nkpg);
2145 /* See the dmb() in _pmap_alloc_l3(). */
2147 paddr = VM_PAGE_TO_PHYS(nkpg);
2148 pmap_store(l1, paddr | L1_TABLE);
2149 continue; /* try again */
2151 l2 = pmap_l1_to_l2(l1, kernel_vm_end);
2152 if (pmap_load(l2) != 0) {
2153 kernel_vm_end = (kernel_vm_end + L2_SIZE) & ~L2_OFFSET;
2154 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
2155 kernel_vm_end = vm_map_max(kernel_map);
2161 nkpg = vm_page_alloc(NULL, kernel_vm_end >> L2_SHIFT,
2162 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
2165 panic("pmap_growkernel: no memory to grow kernel");
2166 if ((nkpg->flags & PG_ZERO) == 0)
2167 pmap_zero_page(nkpg);
2168 /* See the dmb() in _pmap_alloc_l3(). */
2170 paddr = VM_PAGE_TO_PHYS(nkpg);
2171 pmap_store(l2, paddr | L2_TABLE);
2173 kernel_vm_end = (kernel_vm_end + L2_SIZE) & ~L2_OFFSET;
2174 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
2175 kernel_vm_end = vm_map_max(kernel_map);
2181 /***************************************************
2182 * page management routines.
2183 ***************************************************/
2185 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
2186 CTASSERT(_NPCM == 3);
2187 CTASSERT(_NPCPV == 168);
2189 static __inline struct pv_chunk *
2190 pv_to_chunk(pv_entry_t pv)
2193 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
2196 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
2198 #define PC_FREE0 0xfffffffffffffffful
2199 #define PC_FREE1 0xfffffffffffffffful
2200 #define PC_FREE2 0x000000fffffffffful
2202 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
2206 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2208 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2209 "Current number of pv entry chunks");
2210 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2211 "Current number of pv entry chunks allocated");
2212 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2213 "Current number of pv entry chunks frees");
2214 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
2215 "Number of times tried to get a chunk page but failed.");
2217 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
2218 static int pv_entry_spare;
2220 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2221 "Current number of pv entry frees");
2222 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
2223 "Current number of pv entry allocs");
2224 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2225 "Current number of pv entries");
2226 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2227 "Current number of spare pv entries");
2232 * We are in a serious low memory condition. Resort to
2233 * drastic measures to free some pages so we can allocate
2234 * another pv entry chunk.
2236 * Returns NULL if PV entries were reclaimed from the specified pmap.
2238 * We do not, however, unmap 2mpages because subsequent accesses will
2239 * allocate per-page pv entries until repromotion occurs, thereby
2240 * exacerbating the shortage of free pv entries.
2243 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
2245 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
2246 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
2247 struct md_page *pvh;
2249 pmap_t next_pmap, pmap;
2250 pt_entry_t *pte, tpte;
2254 struct spglist free;
2256 int bit, field, freed, lvl;
2257 static int active_reclaims = 0;
2259 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2260 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
2265 bzero(&pc_marker_b, sizeof(pc_marker_b));
2266 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
2267 pc_marker = (struct pv_chunk *)&pc_marker_b;
2268 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
2270 mtx_lock(&pv_chunks_mutex);
2272 TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
2273 TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
2274 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
2275 SLIST_EMPTY(&free)) {
2276 next_pmap = pc->pc_pmap;
2277 if (next_pmap == NULL) {
2279 * The next chunk is a marker. However, it is
2280 * not our marker, so active_reclaims must be
2281 * > 1. Consequently, the next_chunk code
2282 * will not rotate the pv_chunks list.
2286 mtx_unlock(&pv_chunks_mutex);
2289 * A pv_chunk can only be removed from the pc_lru list
2290 * when both pv_chunks_mutex is owned and the
2291 * corresponding pmap is locked.
2293 if (pmap != next_pmap) {
2294 if (pmap != NULL && pmap != locked_pmap)
2297 /* Avoid deadlock and lock recursion. */
2298 if (pmap > locked_pmap) {
2299 RELEASE_PV_LIST_LOCK(lockp);
2301 mtx_lock(&pv_chunks_mutex);
2303 } else if (pmap != locked_pmap) {
2304 if (PMAP_TRYLOCK(pmap)) {
2305 mtx_lock(&pv_chunks_mutex);
2308 pmap = NULL; /* pmap is not locked */
2309 mtx_lock(&pv_chunks_mutex);
2310 pc = TAILQ_NEXT(pc_marker, pc_lru);
2312 pc->pc_pmap != next_pmap)
2320 * Destroy every non-wired, 4 KB page mapping in the chunk.
2323 for (field = 0; field < _NPCM; field++) {
2324 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2325 inuse != 0; inuse &= ~(1UL << bit)) {
2326 bit = ffsl(inuse) - 1;
2327 pv = &pc->pc_pventry[field * 64 + bit];
2329 pde = pmap_pde(pmap, va, &lvl);
2332 pte = pmap_l2_to_l3(pde, va);
2333 tpte = pmap_load(pte);
2334 if ((tpte & ATTR_SW_WIRED) != 0)
2336 tpte = pmap_load_clear(pte);
2337 m = PHYS_TO_VM_PAGE(tpte & ~ATTR_MASK);
2338 if (pmap_pte_dirty(pmap, tpte))
2340 if ((tpte & ATTR_AF) != 0) {
2341 pmap_invalidate_page(pmap, va);
2342 vm_page_aflag_set(m, PGA_REFERENCED);
2344 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
2345 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
2347 if (TAILQ_EMPTY(&m->md.pv_list) &&
2348 (m->flags & PG_FICTITIOUS) == 0) {
2349 pvh = page_to_pvh(m);
2350 if (TAILQ_EMPTY(&pvh->pv_list)) {
2351 vm_page_aflag_clear(m,
2355 pc->pc_map[field] |= 1UL << bit;
2356 pmap_unuse_pt(pmap, va, pmap_load(pde), &free);
2361 mtx_lock(&pv_chunks_mutex);
2364 /* Every freed mapping is for a 4 KB page. */
2365 pmap_resident_count_dec(pmap, freed);
2366 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
2367 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
2368 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
2369 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2370 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
2371 pc->pc_map[2] == PC_FREE2) {
2372 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
2373 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
2374 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
2375 /* Entire chunk is free; return it. */
2376 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
2377 dump_drop_page(m_pc->phys_addr);
2378 mtx_lock(&pv_chunks_mutex);
2379 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2382 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2383 mtx_lock(&pv_chunks_mutex);
2384 /* One freed pv entry in locked_pmap is sufficient. */
2385 if (pmap == locked_pmap)
2389 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
2390 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
2391 if (active_reclaims == 1 && pmap != NULL) {
2393 * Rotate the pv chunks list so that we do not
2394 * scan the same pv chunks that could not be
2395 * freed (because they contained a wired
2396 * and/or superpage mapping) on every
2397 * invocation of reclaim_pv_chunk().
2399 while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
2400 MPASS(pc->pc_pmap != NULL);
2401 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2402 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
2406 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
2407 TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
2409 mtx_unlock(&pv_chunks_mutex);
2410 if (pmap != NULL && pmap != locked_pmap)
2412 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
2413 m_pc = SLIST_FIRST(&free);
2414 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2415 /* Recycle a freed page table page. */
2416 m_pc->ref_count = 1;
2418 vm_page_free_pages_toq(&free, true);
2423 * free the pv_entry back to the free list
2426 free_pv_entry(pmap_t pmap, pv_entry_t pv)
2428 struct pv_chunk *pc;
2429 int idx, field, bit;
2431 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2432 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
2433 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
2434 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
2435 pc = pv_to_chunk(pv);
2436 idx = pv - &pc->pc_pventry[0];
2439 pc->pc_map[field] |= 1ul << bit;
2440 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
2441 pc->pc_map[2] != PC_FREE2) {
2442 /* 98% of the time, pc is already at the head of the list. */
2443 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
2444 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2445 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2449 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2454 free_pv_chunk(struct pv_chunk *pc)
2458 mtx_lock(&pv_chunks_mutex);
2459 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2460 mtx_unlock(&pv_chunks_mutex);
2461 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
2462 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
2463 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
2464 /* entire chunk is free, return it */
2465 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
2466 dump_drop_page(m->phys_addr);
2467 vm_page_unwire_noq(m);
2472 * Returns a new PV entry, allocating a new PV chunk from the system when
2473 * needed. If this PV chunk allocation fails and a PV list lock pointer was
2474 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
2477 * The given PV list lock may be released.
2480 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
2484 struct pv_chunk *pc;
2487 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2488 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
2490 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
2492 for (field = 0; field < _NPCM; field++) {
2493 if (pc->pc_map[field]) {
2494 bit = ffsl(pc->pc_map[field]) - 1;
2498 if (field < _NPCM) {
2499 pv = &pc->pc_pventry[field * 64 + bit];
2500 pc->pc_map[field] &= ~(1ul << bit);
2501 /* If this was the last item, move it to tail */
2502 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
2503 pc->pc_map[2] == 0) {
2504 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2505 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
2508 PV_STAT(atomic_add_long(&pv_entry_count, 1));
2509 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
2513 /* No free items, allocate another chunk */
2514 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
2517 if (lockp == NULL) {
2518 PV_STAT(pc_chunk_tryfail++);
2521 m = reclaim_pv_chunk(pmap, lockp);
2525 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
2526 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
2527 dump_add_page(m->phys_addr);
2528 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
2530 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
2531 pc->pc_map[1] = PC_FREE1;
2532 pc->pc_map[2] = PC_FREE2;
2533 mtx_lock(&pv_chunks_mutex);
2534 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
2535 mtx_unlock(&pv_chunks_mutex);
2536 pv = &pc->pc_pventry[0];
2537 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2538 PV_STAT(atomic_add_long(&pv_entry_count, 1));
2539 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
2544 * Ensure that the number of spare PV entries in the specified pmap meets or
2545 * exceeds the given count, "needed".
2547 * The given PV list lock may be released.
2550 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
2552 struct pch new_tail;
2553 struct pv_chunk *pc;
2558 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2559 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
2562 * Newly allocated PV chunks must be stored in a private list until
2563 * the required number of PV chunks have been allocated. Otherwise,
2564 * reclaim_pv_chunk() could recycle one of these chunks. In
2565 * contrast, these chunks must be added to the pmap upon allocation.
2567 TAILQ_INIT(&new_tail);
2570 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
2571 bit_count((bitstr_t *)pc->pc_map, 0,
2572 sizeof(pc->pc_map) * NBBY, &free);
2576 if (avail >= needed)
2579 for (reclaimed = false; avail < needed; avail += _NPCPV) {
2580 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
2583 m = reclaim_pv_chunk(pmap, lockp);
2588 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
2589 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
2590 dump_add_page(m->phys_addr);
2591 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
2593 pc->pc_map[0] = PC_FREE0;
2594 pc->pc_map[1] = PC_FREE1;
2595 pc->pc_map[2] = PC_FREE2;
2596 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2597 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
2598 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
2601 * The reclaim might have freed a chunk from the current pmap.
2602 * If that chunk contained available entries, we need to
2603 * re-count the number of available entries.
2608 if (!TAILQ_EMPTY(&new_tail)) {
2609 mtx_lock(&pv_chunks_mutex);
2610 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
2611 mtx_unlock(&pv_chunks_mutex);
2616 * First find and then remove the pv entry for the specified pmap and virtual
2617 * address from the specified pv list. Returns the pv entry if found and NULL
2618 * otherwise. This operation can be performed on pv lists for either 4KB or
2619 * 2MB page mappings.
2621 static __inline pv_entry_t
2622 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
2626 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
2627 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
2628 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
2637 * After demotion from a 2MB page mapping to 512 4KB page mappings,
2638 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
2639 * entries for each of the 4KB page mappings.
2642 pmap_pv_demote_l2(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
2643 struct rwlock **lockp)
2645 struct md_page *pvh;
2646 struct pv_chunk *pc;
2648 vm_offset_t va_last;
2652 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2653 KASSERT((va & L2_OFFSET) == 0,
2654 ("pmap_pv_demote_l2: va is not 2mpage aligned"));
2655 KASSERT((pa & L2_OFFSET) == 0,
2656 ("pmap_pv_demote_l2: pa is not 2mpage aligned"));
2657 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
2660 * Transfer the 2mpage's pv entry for this mapping to the first
2661 * page's pv list. Once this transfer begins, the pv list lock
2662 * must not be released until the last pv entry is reinstantiated.
2664 pvh = pa_to_pvh(pa);
2665 pv = pmap_pvh_remove(pvh, pmap, va);
2666 KASSERT(pv != NULL, ("pmap_pv_demote_l2: pv not found"));
2667 m = PHYS_TO_VM_PAGE(pa);
2668 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
2670 /* Instantiate the remaining Ln_ENTRIES - 1 pv entries. */
2671 PV_STAT(atomic_add_long(&pv_entry_allocs, Ln_ENTRIES - 1));
2672 va_last = va + L2_SIZE - PAGE_SIZE;
2674 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
2675 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
2676 pc->pc_map[2] != 0, ("pmap_pv_demote_l2: missing spare"));
2677 for (field = 0; field < _NPCM; field++) {
2678 while (pc->pc_map[field]) {
2679 bit = ffsl(pc->pc_map[field]) - 1;
2680 pc->pc_map[field] &= ~(1ul << bit);
2681 pv = &pc->pc_pventry[field * 64 + bit];
2685 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2686 ("pmap_pv_demote_l2: page %p is not managed", m));
2687 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
2693 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2694 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
2697 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
2698 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2699 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
2701 PV_STAT(atomic_add_long(&pv_entry_count, Ln_ENTRIES - 1));
2702 PV_STAT(atomic_subtract_int(&pv_entry_spare, Ln_ENTRIES - 1));
2706 * First find and then destroy the pv entry for the specified pmap and virtual
2707 * address. This operation can be performed on pv lists for either 4KB or 2MB
2711 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
2715 pv = pmap_pvh_remove(pvh, pmap, va);
2716 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
2717 free_pv_entry(pmap, pv);
2721 * Conditionally create the PV entry for a 4KB page mapping if the required
2722 * memory can be allocated without resorting to reclamation.
2725 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
2726 struct rwlock **lockp)
2730 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2731 /* Pass NULL instead of the lock pointer to disable reclamation. */
2732 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
2734 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
2735 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
2743 * Create the PV entry for a 2MB page mapping. Always returns true unless the
2744 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
2745 * false if the PV entry cannot be allocated without resorting to reclamation.
2748 pmap_pv_insert_l2(pmap_t pmap, vm_offset_t va, pd_entry_t l2e, u_int flags,
2749 struct rwlock **lockp)
2751 struct md_page *pvh;
2755 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2756 /* Pass NULL instead of the lock pointer to disable reclamation. */
2757 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
2758 NULL : lockp)) == NULL)
2761 pa = l2e & ~ATTR_MASK;
2762 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
2763 pvh = pa_to_pvh(pa);
2764 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
2770 pmap_remove_kernel_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va)
2772 pt_entry_t newl2, oldl2;
2776 KASSERT(!VIRT_IN_DMAP(va), ("removing direct mapping of %#lx", va));
2777 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
2778 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2780 ml3 = pmap_remove_pt_page(pmap, va);
2782 panic("pmap_remove_kernel_l2: Missing pt page");
2784 ml3pa = VM_PAGE_TO_PHYS(ml3);
2785 newl2 = ml3pa | L2_TABLE;
2788 * If this page table page was unmapped by a promotion, then it
2789 * contains valid mappings. Zero it to invalidate those mappings.
2791 if (ml3->valid != 0)
2792 pagezero((void *)PHYS_TO_DMAP(ml3pa));
2795 * Demote the mapping. The caller must have already invalidated the
2796 * mapping (i.e., the "break" in break-before-make).
2798 oldl2 = pmap_load_store(l2, newl2);
2799 KASSERT(oldl2 == 0, ("%s: found existing mapping at %p: %#lx",
2800 __func__, l2, oldl2));
2804 * pmap_remove_l2: Do the things to unmap a level 2 superpage.
2807 pmap_remove_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva,
2808 pd_entry_t l1e, struct spglist *free, struct rwlock **lockp)
2810 struct md_page *pvh;
2812 vm_offset_t eva, va;
2815 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2816 KASSERT((sva & L2_OFFSET) == 0, ("pmap_remove_l2: sva is not aligned"));
2817 old_l2 = pmap_load_clear(l2);
2818 KASSERT((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK,
2819 ("pmap_remove_l2: L2e %lx is not a block mapping", old_l2));
2822 * Since a promotion must break the 4KB page mappings before making
2823 * the 2MB page mapping, a pmap_invalidate_page() suffices.
2825 pmap_invalidate_page(pmap, sva);
2827 if (old_l2 & ATTR_SW_WIRED)
2828 pmap->pm_stats.wired_count -= L2_SIZE / PAGE_SIZE;
2829 pmap_resident_count_dec(pmap, L2_SIZE / PAGE_SIZE);
2830 if (old_l2 & ATTR_SW_MANAGED) {
2831 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, old_l2 & ~ATTR_MASK);
2832 pvh = pa_to_pvh(old_l2 & ~ATTR_MASK);
2833 pmap_pvh_free(pvh, pmap, sva);
2834 eva = sva + L2_SIZE;
2835 for (va = sva, m = PHYS_TO_VM_PAGE(old_l2 & ~ATTR_MASK);
2836 va < eva; va += PAGE_SIZE, m++) {
2837 if (pmap_pte_dirty(pmap, old_l2))
2839 if (old_l2 & ATTR_AF)
2840 vm_page_aflag_set(m, PGA_REFERENCED);
2841 if (TAILQ_EMPTY(&m->md.pv_list) &&
2842 TAILQ_EMPTY(&pvh->pv_list))
2843 vm_page_aflag_clear(m, PGA_WRITEABLE);
2846 if (pmap == kernel_pmap) {
2847 pmap_remove_kernel_l2(pmap, l2, sva);
2849 ml3 = pmap_remove_pt_page(pmap, sva);
2851 KASSERT(ml3->valid == VM_PAGE_BITS_ALL,
2852 ("pmap_remove_l2: l3 page not promoted"));
2853 pmap_resident_count_dec(pmap, 1);
2854 KASSERT(ml3->ref_count == NL3PG,
2855 ("pmap_remove_l2: l3 page ref count error"));
2857 pmap_add_delayed_free_list(ml3, free, FALSE);
2860 return (pmap_unuse_pt(pmap, sva, l1e, free));
2864 * pmap_remove_l3: do the things to unmap a page in a process
2867 pmap_remove_l3(pmap_t pmap, pt_entry_t *l3, vm_offset_t va,
2868 pd_entry_t l2e, struct spglist *free, struct rwlock **lockp)
2870 struct md_page *pvh;
2874 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2875 old_l3 = pmap_load_clear(l3);
2876 pmap_invalidate_page(pmap, va);
2877 if (old_l3 & ATTR_SW_WIRED)
2878 pmap->pm_stats.wired_count -= 1;
2879 pmap_resident_count_dec(pmap, 1);
2880 if (old_l3 & ATTR_SW_MANAGED) {
2881 m = PHYS_TO_VM_PAGE(old_l3 & ~ATTR_MASK);
2882 if (pmap_pte_dirty(pmap, old_l3))
2884 if (old_l3 & ATTR_AF)
2885 vm_page_aflag_set(m, PGA_REFERENCED);
2886 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
2887 pmap_pvh_free(&m->md, pmap, va);
2888 if (TAILQ_EMPTY(&m->md.pv_list) &&
2889 (m->flags & PG_FICTITIOUS) == 0) {
2890 pvh = page_to_pvh(m);
2891 if (TAILQ_EMPTY(&pvh->pv_list))
2892 vm_page_aflag_clear(m, PGA_WRITEABLE);
2895 return (pmap_unuse_pt(pmap, va, l2e, free));
2899 * Remove the specified range of addresses from the L3 page table that is
2900 * identified by the given L2 entry.
2903 pmap_remove_l3_range(pmap_t pmap, pd_entry_t l2e, vm_offset_t sva,
2904 vm_offset_t eva, struct spglist *free, struct rwlock **lockp)
2906 struct md_page *pvh;
2907 struct rwlock *new_lock;
2908 pt_entry_t *l3, old_l3;
2912 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2913 KASSERT(rounddown2(sva, L2_SIZE) + L2_SIZE == roundup2(eva, L2_SIZE),
2914 ("pmap_remove_l3_range: range crosses an L3 page table boundary"));
2915 l3pg = sva < VM_MAXUSER_ADDRESS ? PHYS_TO_VM_PAGE(l2e & ~ATTR_MASK) :
2918 for (l3 = pmap_l2_to_l3(&l2e, sva); sva != eva; l3++, sva += L3_SIZE) {
2919 if (!pmap_l3_valid(pmap_load(l3))) {
2921 pmap_invalidate_range(pmap, va, sva);
2926 old_l3 = pmap_load_clear(l3);
2927 if ((old_l3 & ATTR_SW_WIRED) != 0)
2928 pmap->pm_stats.wired_count--;
2929 pmap_resident_count_dec(pmap, 1);
2930 if ((old_l3 & ATTR_SW_MANAGED) != 0) {
2931 m = PHYS_TO_VM_PAGE(old_l3 & ~ATTR_MASK);
2932 if (pmap_pte_dirty(pmap, old_l3))
2934 if ((old_l3 & ATTR_AF) != 0)
2935 vm_page_aflag_set(m, PGA_REFERENCED);
2936 new_lock = PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m));
2937 if (new_lock != *lockp) {
2938 if (*lockp != NULL) {
2940 * Pending TLB invalidations must be
2941 * performed before the PV list lock is
2942 * released. Otherwise, a concurrent
2943 * pmap_remove_all() on a physical page
2944 * could return while a stale TLB entry
2945 * still provides access to that page.
2948 pmap_invalidate_range(pmap, va,
2957 pmap_pvh_free(&m->md, pmap, sva);
2958 if (TAILQ_EMPTY(&m->md.pv_list) &&
2959 (m->flags & PG_FICTITIOUS) == 0) {
2960 pvh = page_to_pvh(m);
2961 if (TAILQ_EMPTY(&pvh->pv_list))
2962 vm_page_aflag_clear(m, PGA_WRITEABLE);
2967 if (l3pg != NULL && pmap_unwire_l3(pmap, sva, l3pg, free)) {
2973 pmap_invalidate_range(pmap, va, sva);
2977 * Remove the given range of addresses from the specified map.
2979 * It is assumed that the start and end are properly
2980 * rounded to the page size.
2983 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2985 struct rwlock *lock;
2986 vm_offset_t va_next;
2987 pd_entry_t *l0, *l1, *l2;
2988 pt_entry_t l3_paddr;
2989 struct spglist free;
2992 * Perform an unsynchronized read. This is, however, safe.
2994 if (pmap->pm_stats.resident_count == 0)
3002 for (; sva < eva; sva = va_next) {
3003 if (pmap->pm_stats.resident_count == 0)
3006 l0 = pmap_l0(pmap, sva);
3007 if (pmap_load(l0) == 0) {
3008 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
3014 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
3017 l1 = pmap_l0_to_l1(l0, sva);
3018 if (pmap_load(l1) == 0)
3020 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
3021 KASSERT(va_next <= eva,
3022 ("partial update of non-transparent 1G page "
3023 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
3024 pmap_load(l1), sva, eva, va_next));
3025 MPASS(pmap != kernel_pmap);
3026 MPASS((pmap_load(l1) & ATTR_SW_MANAGED) == 0);
3028 pmap_invalidate_page(pmap, sva);
3029 pmap_resident_count_dec(pmap, L1_SIZE / PAGE_SIZE);
3030 pmap_unuse_pt(pmap, sva, pmap_load(l0), &free);
3035 * Calculate index for next page table.
3037 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
3041 l2 = pmap_l1_to_l2(l1, sva);
3045 l3_paddr = pmap_load(l2);
3047 if ((l3_paddr & ATTR_DESCR_MASK) == L2_BLOCK) {
3048 if (sva + L2_SIZE == va_next && eva >= va_next) {
3049 pmap_remove_l2(pmap, l2, sva, pmap_load(l1),
3052 } else if (pmap_demote_l2_locked(pmap, l2, sva,
3055 l3_paddr = pmap_load(l2);
3059 * Weed out invalid mappings.
3061 if ((l3_paddr & ATTR_DESCR_MASK) != L2_TABLE)
3065 * Limit our scan to either the end of the va represented
3066 * by the current page table page, or to the end of the
3067 * range being removed.
3072 pmap_remove_l3_range(pmap, l3_paddr, sva, va_next, &free,
3078 vm_page_free_pages_toq(&free, true);
3082 * Routine: pmap_remove_all
3084 * Removes this physical page from
3085 * all physical maps in which it resides.
3086 * Reflects back modify bits to the pager.
3089 * Original versions of this routine were very
3090 * inefficient because they iteratively called
3091 * pmap_remove (slow...)
3095 pmap_remove_all(vm_page_t m)
3097 struct md_page *pvh;
3100 struct rwlock *lock;
3101 pd_entry_t *pde, tpde;
3102 pt_entry_t *pte, tpte;
3104 struct spglist free;
3105 int lvl, pvh_gen, md_gen;
3107 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3108 ("pmap_remove_all: page %p is not managed", m));
3110 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
3111 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
3114 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
3116 if (!PMAP_TRYLOCK(pmap)) {
3117 pvh_gen = pvh->pv_gen;
3121 if (pvh_gen != pvh->pv_gen) {
3128 pte = pmap_pte(pmap, va, &lvl);
3129 KASSERT(pte != NULL,
3130 ("pmap_remove_all: no page table entry found"));
3132 ("pmap_remove_all: invalid pte level %d", lvl));
3134 pmap_demote_l2_locked(pmap, pte, va, &lock);
3137 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3139 PMAP_ASSERT_STAGE1(pmap);
3140 if (!PMAP_TRYLOCK(pmap)) {
3141 pvh_gen = pvh->pv_gen;
3142 md_gen = m->md.pv_gen;
3146 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
3152 pmap_resident_count_dec(pmap, 1);
3154 pde = pmap_pde(pmap, pv->pv_va, &lvl);
3155 KASSERT(pde != NULL,
3156 ("pmap_remove_all: no page directory entry found"));
3158 ("pmap_remove_all: invalid pde level %d", lvl));
3159 tpde = pmap_load(pde);
3161 pte = pmap_l2_to_l3(pde, pv->pv_va);
3162 tpte = pmap_load_clear(pte);
3163 if (tpte & ATTR_SW_WIRED)
3164 pmap->pm_stats.wired_count--;
3165 if ((tpte & ATTR_AF) != 0) {
3166 pmap_invalidate_page(pmap, pv->pv_va);
3167 vm_page_aflag_set(m, PGA_REFERENCED);
3171 * Update the vm_page_t clean and reference bits.
3173 if (pmap_pte_dirty(pmap, tpte))
3175 pmap_unuse_pt(pmap, pv->pv_va, tpde, &free);
3176 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3178 free_pv_entry(pmap, pv);
3181 vm_page_aflag_clear(m, PGA_WRITEABLE);
3183 vm_page_free_pages_toq(&free, true);
3187 * pmap_protect_l2: do the things to protect a 2MB page in a pmap
3190 pmap_protect_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t sva, pt_entry_t mask,
3196 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3197 PMAP_ASSERT_STAGE1(pmap);
3198 KASSERT((sva & L2_OFFSET) == 0,
3199 ("pmap_protect_l2: sva is not 2mpage aligned"));
3200 old_l2 = pmap_load(l2);
3201 KASSERT((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK,
3202 ("pmap_protect_l2: L2e %lx is not a block mapping", old_l2));
3205 * Return if the L2 entry already has the desired access restrictions
3209 if ((old_l2 & mask) == nbits)
3213 * When a dirty read/write superpage mapping is write protected,
3214 * update the dirty field of each of the superpage's constituent 4KB
3217 if ((old_l2 & ATTR_SW_MANAGED) != 0 &&
3218 (nbits & ATTR_S1_AP(ATTR_S1_AP_RO)) != 0 &&
3219 pmap_pte_dirty(pmap, old_l2)) {
3220 m = PHYS_TO_VM_PAGE(old_l2 & ~ATTR_MASK);
3221 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
3225 if (!atomic_fcmpset_64(l2, &old_l2, (old_l2 & ~mask) | nbits))
3229 * Since a promotion must break the 4KB page mappings before making
3230 * the 2MB page mapping, a pmap_invalidate_page() suffices.
3232 pmap_invalidate_page(pmap, sva);
3236 * Set the physical protection on the
3237 * specified range of this map as requested.
3240 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
3242 vm_offset_t va, va_next;
3243 pd_entry_t *l0, *l1, *l2;
3244 pt_entry_t *l3p, l3, mask, nbits;
3246 PMAP_ASSERT_STAGE1(pmap);
3247 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
3248 if (prot == VM_PROT_NONE) {
3249 pmap_remove(pmap, sva, eva);
3254 if ((prot & VM_PROT_WRITE) == 0) {
3255 mask |= ATTR_S1_AP_RW_BIT | ATTR_SW_DBM;
3256 nbits |= ATTR_S1_AP(ATTR_S1_AP_RO);
3258 if ((prot & VM_PROT_EXECUTE) == 0) {
3260 nbits |= ATTR_S1_XN;
3266 for (; sva < eva; sva = va_next) {
3267 l0 = pmap_l0(pmap, sva);
3268 if (pmap_load(l0) == 0) {
3269 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
3275 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
3278 l1 = pmap_l0_to_l1(l0, sva);
3279 if (pmap_load(l1) == 0)
3281 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
3282 KASSERT(va_next <= eva,
3283 ("partial update of non-transparent 1G page "
3284 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
3285 pmap_load(l1), sva, eva, va_next));
3286 MPASS((pmap_load(l1) & ATTR_SW_MANAGED) == 0);
3287 if ((pmap_load(l1) & mask) != nbits) {
3288 pmap_store(l1, (pmap_load(l1) & ~mask) | nbits);
3289 pmap_invalidate_page(pmap, sva);
3294 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
3298 l2 = pmap_l1_to_l2(l1, sva);
3299 if (pmap_load(l2) == 0)
3302 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK) {
3303 if (sva + L2_SIZE == va_next && eva >= va_next) {
3304 pmap_protect_l2(pmap, l2, sva, mask, nbits);
3306 } else if (pmap_demote_l2(pmap, l2, sva) == NULL)
3309 KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
3310 ("pmap_protect: Invalid L2 entry after demotion"));
3316 for (l3p = pmap_l2_to_l3(l2, sva); sva != va_next; l3p++,
3318 l3 = pmap_load(l3p);
3321 * Go to the next L3 entry if the current one is
3322 * invalid or already has the desired access
3323 * restrictions in place. (The latter case occurs
3324 * frequently. For example, in a "buildworld"
3325 * workload, almost 1 out of 4 L3 entries already
3326 * have the desired restrictions.)
3328 if (!pmap_l3_valid(l3) || (l3 & mask) == nbits) {
3329 if (va != va_next) {
3330 pmap_invalidate_range(pmap, va, sva);
3337 * When a dirty read/write mapping is write protected,
3338 * update the page's dirty field.
3340 if ((l3 & ATTR_SW_MANAGED) != 0 &&
3341 (nbits & ATTR_S1_AP(ATTR_S1_AP_RO)) != 0 &&
3342 pmap_pte_dirty(pmap, l3))
3343 vm_page_dirty(PHYS_TO_VM_PAGE(l3 & ~ATTR_MASK));
3345 if (!atomic_fcmpset_64(l3p, &l3, (l3 & ~mask) | nbits))
3351 pmap_invalidate_range(pmap, va, sva);
3357 * Inserts the specified page table page into the specified pmap's collection
3358 * of idle page table pages. Each of a pmap's page table pages is responsible
3359 * for mapping a distinct range of virtual addresses. The pmap's collection is
3360 * ordered by this virtual address range.
3362 * If "promoted" is false, then the page table page "mpte" must be zero filled.
3365 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted)
3368 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3369 mpte->valid = promoted ? VM_PAGE_BITS_ALL : 0;
3370 return (vm_radix_insert(&pmap->pm_root, mpte));
3374 * Removes the page table page mapping the specified virtual address from the
3375 * specified pmap's collection of idle page table pages, and returns it.
3376 * Otherwise, returns NULL if there is no page table page corresponding to the
3377 * specified virtual address.
3379 static __inline vm_page_t
3380 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
3383 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3384 return (vm_radix_remove(&pmap->pm_root, pmap_l2_pindex(va)));
3388 * Performs a break-before-make update of a pmap entry. This is needed when
3389 * either promoting or demoting pages to ensure the TLB doesn't get into an
3390 * inconsistent state.
3393 pmap_update_entry(pmap_t pmap, pd_entry_t *pte, pd_entry_t newpte,
3394 vm_offset_t va, vm_size_t size)
3398 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3401 * Ensure we don't get switched out with the page table in an
3402 * inconsistent state. We also need to ensure no interrupts fire
3403 * as they may make use of an address we are about to invalidate.
3405 intr = intr_disable();
3408 * Clear the old mapping's valid bit, but leave the rest of the entry
3409 * unchanged, so that a lockless, concurrent pmap_kextract() can still
3410 * lookup the physical address.
3412 pmap_clear_bits(pte, ATTR_DESCR_VALID);
3413 pmap_invalidate_range(pmap, va, va + size);
3415 /* Create the new mapping */
3416 pmap_store(pte, newpte);
3422 #if VM_NRESERVLEVEL > 0
3424 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3425 * replace the many pv entries for the 4KB page mappings by a single pv entry
3426 * for the 2MB page mapping.
3429 pmap_pv_promote_l2(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3430 struct rwlock **lockp)
3432 struct md_page *pvh;
3434 vm_offset_t va_last;
3437 KASSERT((pa & L2_OFFSET) == 0,
3438 ("pmap_pv_promote_l2: pa is not 2mpage aligned"));
3439 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3442 * Transfer the first page's pv entry for this mapping to the 2mpage's
3443 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3444 * a transfer avoids the possibility that get_pv_entry() calls
3445 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3446 * mappings that is being promoted.
3448 m = PHYS_TO_VM_PAGE(pa);
3449 va = va & ~L2_OFFSET;
3450 pv = pmap_pvh_remove(&m->md, pmap, va);
3451 KASSERT(pv != NULL, ("pmap_pv_promote_l2: pv not found"));
3452 pvh = pa_to_pvh(pa);
3453 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3455 /* Free the remaining NPTEPG - 1 pv entries. */
3456 va_last = va + L2_SIZE - PAGE_SIZE;
3460 pmap_pvh_free(&m->md, pmap, va);
3461 } while (va < va_last);
3465 * Tries to promote the 512, contiguous 4KB page mappings that are within a
3466 * single level 2 table entry to a single 2MB page mapping. For promotion
3467 * to occur, two conditions must be met: (1) the 4KB page mappings must map
3468 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
3469 * identical characteristics.
3472 pmap_promote_l2(pmap_t pmap, pd_entry_t *l2, vm_offset_t va,
3473 struct rwlock **lockp)
3475 pt_entry_t *firstl3, *l3, newl2, oldl3, pa;
3479 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3480 PMAP_ASSERT_STAGE1(pmap);
3482 sva = va & ~L2_OFFSET;
3483 firstl3 = pmap_l2_to_l3(l2, sva);
3484 newl2 = pmap_load(firstl3);
3487 if (((newl2 & (~ATTR_MASK | ATTR_AF)) & L2_OFFSET) != ATTR_AF) {
3488 atomic_add_long(&pmap_l2_p_failures, 1);
3489 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
3490 " in pmap %p", va, pmap);
3494 if ((newl2 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
3495 (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM)) {
3496 if (!atomic_fcmpset_64(l2, &newl2, newl2 & ~ATTR_SW_DBM))
3498 newl2 &= ~ATTR_SW_DBM;
3501 pa = newl2 + L2_SIZE - PAGE_SIZE;
3502 for (l3 = firstl3 + NL3PG - 1; l3 > firstl3; l3--) {
3503 oldl3 = pmap_load(l3);
3505 if ((oldl3 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) ==
3506 (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM)) {
3507 if (!atomic_fcmpset_64(l3, &oldl3, oldl3 &
3510 oldl3 &= ~ATTR_SW_DBM;
3513 atomic_add_long(&pmap_l2_p_failures, 1);
3514 CTR2(KTR_PMAP, "pmap_promote_l2: failure for va %#lx"
3515 " in pmap %p", va, pmap);
3522 * Save the page table page in its current state until the L2
3523 * mapping the superpage is demoted by pmap_demote_l2() or
3524 * destroyed by pmap_remove_l3().
3526 mpte = PHYS_TO_VM_PAGE(pmap_load(l2) & ~ATTR_MASK);
3527 KASSERT(mpte >= vm_page_array &&
3528 mpte < &vm_page_array[vm_page_array_size],
3529 ("pmap_promote_l2: page table page is out of range"));
3530 KASSERT(mpte->pindex == pmap_l2_pindex(va),
3531 ("pmap_promote_l2: page table page's pindex is wrong"));
3532 if (pmap_insert_pt_page(pmap, mpte, true)) {
3533 atomic_add_long(&pmap_l2_p_failures, 1);
3535 "pmap_promote_l2: failure for va %#lx in pmap %p", va,
3540 if ((newl2 & ATTR_SW_MANAGED) != 0)
3541 pmap_pv_promote_l2(pmap, va, newl2 & ~ATTR_MASK, lockp);
3543 newl2 &= ~ATTR_DESCR_MASK;
3546 pmap_update_entry(pmap, l2, newl2, sva, L2_SIZE);
3548 atomic_add_long(&pmap_l2_promotions, 1);
3549 CTR2(KTR_PMAP, "pmap_promote_l2: success for va %#lx in pmap %p", va,
3552 #endif /* VM_NRESERVLEVEL > 0 */
3555 pmap_enter_largepage(pmap_t pmap, vm_offset_t va, pt_entry_t newpte, int flags,
3558 pd_entry_t *l0p, *l1p, *l2p, origpte;
3561 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3562 KASSERT(psind > 0 && psind < MAXPAGESIZES,
3563 ("psind %d unexpected", psind));
3564 KASSERT(((newpte & ~ATTR_MASK) & (pagesizes[psind] - 1)) == 0,
3565 ("unaligned phys address %#lx newpte %#lx psind %d",
3566 (newpte & ~ATTR_MASK), newpte, psind));
3570 l0p = pmap_l0(pmap, va);
3571 if ((pmap_load(l0p) & ATTR_DESCR_VALID) == 0) {
3572 mp = _pmap_alloc_l3(pmap, pmap_l0_pindex(va), NULL);
3574 if ((flags & PMAP_ENTER_NOSLEEP) != 0)
3575 return (KERN_RESOURCE_SHORTAGE);
3581 l1p = pmap_l0_to_l1(l0p, va);
3582 KASSERT(l1p != NULL, ("va %#lx lost l1 entry", va));
3583 origpte = pmap_load(l1p);
3585 l1p = pmap_l0_to_l1(l0p, va);
3586 KASSERT(l1p != NULL, ("va %#lx lost l1 entry", va));
3587 origpte = pmap_load(l1p);
3588 if ((origpte & ATTR_DESCR_VALID) == 0) {
3589 mp = PHYS_TO_VM_PAGE(pmap_load(l0p) &
3594 KASSERT((origpte & ATTR_DESCR_VALID) == 0 ||
3595 ((origpte & ATTR_DESCR_MASK) == L1_BLOCK &&
3596 (origpte & ~ATTR_MASK) == (newpte & ~ATTR_MASK)),
3597 ("va %#lx changing 1G phys page l1 %#lx newpte %#lx",
3598 va, origpte, newpte));
3599 pmap_store(l1p, newpte);
3600 } else /* (psind == 1) */ {
3601 l2p = pmap_l2(pmap, va);
3603 mp = _pmap_alloc_l3(pmap, pmap_l1_pindex(va), NULL);
3605 if ((flags & PMAP_ENTER_NOSLEEP) != 0)
3606 return (KERN_RESOURCE_SHORTAGE);
3612 l2p = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
3613 l2p = &l2p[pmap_l2_index(va)];
3614 origpte = pmap_load(l2p);
3616 l1p = pmap_l1(pmap, va);
3617 origpte = pmap_load(l2p);
3618 if ((origpte & ATTR_DESCR_VALID) == 0) {
3619 mp = PHYS_TO_VM_PAGE(pmap_load(l1p) &
3624 KASSERT((origpte & ATTR_DESCR_VALID) == 0 ||
3625 ((origpte & ATTR_DESCR_MASK) == L2_BLOCK &&
3626 (origpte & ~ATTR_MASK) == (newpte & ~ATTR_MASK)),
3627 ("va %#lx changing 2M phys page l2 %#lx newpte %#lx",
3628 va, origpte, newpte));
3629 pmap_store(l2p, newpte);
3633 if ((origpte & ATTR_DESCR_VALID) == 0)
3634 pmap_resident_count_inc(pmap, pagesizes[psind] / PAGE_SIZE);
3635 if ((newpte & ATTR_SW_WIRED) != 0 && (origpte & ATTR_SW_WIRED) == 0)
3636 pmap->pm_stats.wired_count += pagesizes[psind] / PAGE_SIZE;
3637 else if ((newpte & ATTR_SW_WIRED) == 0 &&
3638 (origpte & ATTR_SW_WIRED) != 0)
3639 pmap->pm_stats.wired_count -= pagesizes[psind] / PAGE_SIZE;
3641 return (KERN_SUCCESS);
3645 * Add a single SMMU entry. This function does not sleep.
3648 pmap_senter(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3649 vm_prot_t prot, u_int flags)
3652 pt_entry_t new_l3, orig_l3;
3658 PMAP_ASSERT_STAGE1(pmap);
3659 KASSERT(va < VM_MAXUSER_ADDRESS, ("wrong address space"));
3661 va = trunc_page(va);
3662 new_l3 = (pt_entry_t)(pa | ATTR_DEFAULT |
3663 ATTR_S1_IDX(VM_MEMATTR_DEVICE) | L3_PAGE);
3664 if ((prot & VM_PROT_WRITE) == 0)
3665 new_l3 |= ATTR_S1_AP(ATTR_S1_AP_RO);
3666 new_l3 |= ATTR_S1_XN; /* Execute never. */
3667 new_l3 |= ATTR_S1_AP(ATTR_S1_AP_USER);
3668 new_l3 |= ATTR_S1_nG; /* Non global. */
3670 CTR2(KTR_PMAP, "pmap_senter: %.16lx -> %.16lx", va, pa);
3675 * In the case that a page table page is not
3676 * resident, we are creating it here.
3679 pde = pmap_pde(pmap, va, &lvl);
3680 if (pde != NULL && lvl == 2) {
3681 l3 = pmap_l2_to_l3(pde, va);
3683 mpte = _pmap_alloc_l3(pmap, pmap_l2_pindex(va), NULL);
3685 CTR0(KTR_PMAP, "pmap_enter: mpte == NULL");
3686 rv = KERN_RESOURCE_SHORTAGE;
3692 orig_l3 = pmap_load(l3);
3693 KASSERT(!pmap_l3_valid(orig_l3), ("l3 is valid"));
3696 pmap_store(l3, new_l3);
3697 pmap_resident_count_inc(pmap, 1);
3708 * Remove a single SMMU entry.
3711 pmap_sremove(pmap_t pmap, vm_offset_t va)
3719 pte = pmap_pte(pmap, va, &lvl);
3721 ("Invalid SMMU pagetable level: %d != 3", lvl));
3724 pmap_resident_count_dec(pmap, 1);
3736 * Remove all the allocated L1, L2 pages from SMMU pmap.
3737 * All the L3 entires must be cleared in advance, otherwise
3738 * this function panics.
3741 pmap_sremove_pages(pmap_t pmap)
3743 pd_entry_t l0e, *l1, l1e, *l2, l2e;
3744 pt_entry_t *l3, l3e;
3745 vm_page_t m, m0, m1;
3754 for (sva = VM_MINUSER_ADDRESS, i = pmap_l0_index(sva);
3755 (i < Ln_ENTRIES && sva < VM_MAXUSER_ADDRESS); i++) {
3756 l0e = pmap->pm_l0[i];
3757 if ((l0e & ATTR_DESCR_VALID) == 0) {
3761 pa0 = l0e & ~ATTR_MASK;
3762 m0 = PHYS_TO_VM_PAGE(pa0);
3763 l1 = (pd_entry_t *)PHYS_TO_DMAP(pa0);
3765 for (j = pmap_l1_index(sva); j < Ln_ENTRIES; j++) {
3767 if ((l1e & ATTR_DESCR_VALID) == 0) {
3771 if ((l1e & ATTR_DESCR_MASK) == L1_BLOCK) {
3775 pa1 = l1e & ~ATTR_MASK;
3776 m1 = PHYS_TO_VM_PAGE(pa1);
3777 l2 = (pd_entry_t *)PHYS_TO_DMAP(pa1);
3779 for (k = pmap_l2_index(sva); k < Ln_ENTRIES; k++) {
3781 if ((l2e & ATTR_DESCR_VALID) == 0) {
3785 pa = l2e & ~ATTR_MASK;
3786 m = PHYS_TO_VM_PAGE(pa);
3787 l3 = (pt_entry_t *)PHYS_TO_DMAP(pa);
3789 for (l = pmap_l3_index(sva); l < Ln_ENTRIES;
3790 l++, sva += L3_SIZE) {
3792 if ((l3e & ATTR_DESCR_VALID) == 0)
3794 panic("%s: l3e found for va %jx\n",
3798 vm_page_unwire_noq(m1);
3799 vm_page_unwire_noq(m);
3800 pmap_resident_count_dec(pmap, 1);
3805 vm_page_unwire_noq(m0);
3806 pmap_resident_count_dec(pmap, 1);
3811 pmap_resident_count_dec(pmap, 1);
3813 pmap_clear(&pmap->pm_l0[i]);
3816 KASSERT(pmap->pm_stats.resident_count == 0,
3817 ("Invalid resident count %jd", pmap->pm_stats.resident_count));
3823 * Insert the given physical page (p) at
3824 * the specified virtual address (v) in the
3825 * target physical map with the protection requested.
3827 * If specified, the page will be wired down, meaning
3828 * that the related pte can not be reclaimed.
3830 * NB: This is the only routine which MAY NOT lazy-evaluate
3831 * or lose information. That is, this routine must actually
3832 * insert this page into the given map NOW.
3835 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
3836 u_int flags, int8_t psind)
3838 struct rwlock *lock;
3840 pt_entry_t new_l3, orig_l3;
3841 pt_entry_t *l2, *l3;
3848 va = trunc_page(va);
3849 if ((m->oflags & VPO_UNMANAGED) == 0)
3850 VM_PAGE_OBJECT_BUSY_ASSERT(m);
3851 pa = VM_PAGE_TO_PHYS(m);
3852 new_l3 = (pt_entry_t)(pa | ATTR_DEFAULT | L3_PAGE);
3853 new_l3 |= pmap_pte_memattr(pmap, m->md.pv_memattr);
3854 new_l3 |= pmap_pte_prot(pmap, prot);
3856 if ((flags & PMAP_ENTER_WIRED) != 0)
3857 new_l3 |= ATTR_SW_WIRED;
3858 if (pmap->pm_stage == PM_STAGE1) {
3859 if (va < VM_MAXUSER_ADDRESS)
3860 new_l3 |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
3862 new_l3 |= ATTR_S1_UXN;
3863 if (pmap != kernel_pmap)
3864 new_l3 |= ATTR_S1_nG;
3867 * Clear the access flag on executable mappings, this will be
3868 * set later when the page is accessed. The fault handler is
3869 * required to invalidate the I-cache.
3871 * TODO: Switch to the valid flag to allow hardware management
3872 * of the access flag. Much of the pmap code assumes the
3873 * valid flag is set and fails to destroy the old page tables
3874 * correctly if it is clear.
3876 if (prot & VM_PROT_EXECUTE)
3879 if ((m->oflags & VPO_UNMANAGED) == 0) {
3880 new_l3 |= ATTR_SW_MANAGED;
3881 if ((prot & VM_PROT_WRITE) != 0) {
3882 new_l3 |= ATTR_SW_DBM;
3883 if ((flags & VM_PROT_WRITE) == 0) {
3884 if (pmap->pm_stage == PM_STAGE1)
3885 new_l3 |= ATTR_S1_AP(ATTR_S1_AP_RO);
3888 ~ATTR_S2_S2AP(ATTR_S2_S2AP_WRITE);
3893 CTR2(KTR_PMAP, "pmap_enter: %.16lx -> %.16lx", va, pa);
3897 if ((flags & PMAP_ENTER_LARGEPAGE) != 0) {
3898 KASSERT((m->oflags & VPO_UNMANAGED) != 0,
3899 ("managed largepage va %#lx flags %#x", va, flags));
3903 else /* (psind == 1) */
3905 rv = pmap_enter_largepage(pmap, va, new_l3, flags, psind);
3909 /* Assert the required virtual and physical alignment. */
3910 KASSERT((va & L2_OFFSET) == 0, ("pmap_enter: va unaligned"));
3911 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
3912 rv = pmap_enter_l2(pmap, va, (new_l3 & ~L3_PAGE) | L2_BLOCK,
3919 * In the case that a page table page is not
3920 * resident, we are creating it here.
3923 pde = pmap_pde(pmap, va, &lvl);
3924 if (pde != NULL && lvl == 2) {
3925 l3 = pmap_l2_to_l3(pde, va);
3926 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
3927 mpte = PHYS_TO_VM_PAGE(pmap_load(pde) & ~ATTR_MASK);
3931 } else if (pde != NULL && lvl == 1) {
3932 l2 = pmap_l1_to_l2(pde, va);
3933 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK &&
3934 (l3 = pmap_demote_l2_locked(pmap, l2, va, &lock)) != NULL) {
3935 l3 = &l3[pmap_l3_index(va)];
3936 if (va < VM_MAXUSER_ADDRESS) {
3937 mpte = PHYS_TO_VM_PAGE(
3938 pmap_load(l2) & ~ATTR_MASK);
3943 /* We need to allocate an L3 table. */
3945 if (va < VM_MAXUSER_ADDRESS) {
3946 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
3949 * We use _pmap_alloc_l3() instead of pmap_alloc_l3() in order
3950 * to handle the possibility that a superpage mapping for "va"
3951 * was created while we slept.
3953 mpte = _pmap_alloc_l3(pmap, pmap_l2_pindex(va),
3954 nosleep ? NULL : &lock);
3955 if (mpte == NULL && nosleep) {
3956 CTR0(KTR_PMAP, "pmap_enter: mpte == NULL");
3957 rv = KERN_RESOURCE_SHORTAGE;
3962 panic("pmap_enter: missing L3 table for kernel va %#lx", va);
3965 orig_l3 = pmap_load(l3);
3966 opa = orig_l3 & ~ATTR_MASK;
3970 * Is the specified virtual address already mapped?
3972 if (pmap_l3_valid(orig_l3)) {
3974 * Only allow adding new entries on stage 2 tables for now.
3975 * This simplifies cache invalidation as we may need to call
3976 * into EL2 to perform such actions.
3978 PMAP_ASSERT_STAGE1(pmap);
3980 * Wiring change, just update stats. We don't worry about
3981 * wiring PT pages as they remain resident as long as there
3982 * are valid mappings in them. Hence, if a user page is wired,
3983 * the PT page will be also.
3985 if ((flags & PMAP_ENTER_WIRED) != 0 &&
3986 (orig_l3 & ATTR_SW_WIRED) == 0)
3987 pmap->pm_stats.wired_count++;
3988 else if ((flags & PMAP_ENTER_WIRED) == 0 &&
3989 (orig_l3 & ATTR_SW_WIRED) != 0)
3990 pmap->pm_stats.wired_count--;
3993 * Remove the extra PT page reference.
3997 KASSERT(mpte->ref_count > 0,
3998 ("pmap_enter: missing reference to page table page,"
4003 * Has the physical page changed?
4007 * No, might be a protection or wiring change.
4009 if ((orig_l3 & ATTR_SW_MANAGED) != 0 &&
4010 (new_l3 & ATTR_SW_DBM) != 0)
4011 vm_page_aflag_set(m, PGA_WRITEABLE);
4016 * The physical page has changed. Temporarily invalidate
4019 orig_l3 = pmap_load_clear(l3);
4020 KASSERT((orig_l3 & ~ATTR_MASK) == opa,
4021 ("pmap_enter: unexpected pa update for %#lx", va));
4022 if ((orig_l3 & ATTR_SW_MANAGED) != 0) {
4023 om = PHYS_TO_VM_PAGE(opa);
4026 * The pmap lock is sufficient to synchronize with
4027 * concurrent calls to pmap_page_test_mappings() and
4028 * pmap_ts_referenced().
4030 if (pmap_pte_dirty(pmap, orig_l3))
4032 if ((orig_l3 & ATTR_AF) != 0) {
4033 pmap_invalidate_page(pmap, va);
4034 vm_page_aflag_set(om, PGA_REFERENCED);
4036 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4037 pv = pmap_pvh_remove(&om->md, pmap, va);
4038 if ((m->oflags & VPO_UNMANAGED) != 0)
4039 free_pv_entry(pmap, pv);
4040 if ((om->a.flags & PGA_WRITEABLE) != 0 &&
4041 TAILQ_EMPTY(&om->md.pv_list) &&
4042 ((om->flags & PG_FICTITIOUS) != 0 ||
4043 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4044 vm_page_aflag_clear(om, PGA_WRITEABLE);
4046 KASSERT((orig_l3 & ATTR_AF) != 0,
4047 ("pmap_enter: unmanaged mapping lacks ATTR_AF"));
4048 pmap_invalidate_page(pmap, va);
4053 * Increment the counters.
4055 if ((new_l3 & ATTR_SW_WIRED) != 0)
4056 pmap->pm_stats.wired_count++;
4057 pmap_resident_count_inc(pmap, 1);
4060 * Enter on the PV list if part of our managed memory.
4062 if ((m->oflags & VPO_UNMANAGED) == 0) {
4064 pv = get_pv_entry(pmap, &lock);
4067 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4068 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4070 if ((new_l3 & ATTR_SW_DBM) != 0)
4071 vm_page_aflag_set(m, PGA_WRITEABLE);
4075 if (pmap->pm_stage == PM_STAGE1) {
4077 * Sync icache if exec permission and attribute
4078 * VM_MEMATTR_WRITE_BACK is set. Do it now, before the mapping
4079 * is stored and made valid for hardware table walk. If done
4080 * later, then other can access this page before caches are
4081 * properly synced. Don't do it for kernel memory which is
4082 * mapped with exec permission even if the memory isn't going
4083 * to hold executable code. The only time when icache sync is
4084 * needed is after kernel module is loaded and the relocation
4085 * info is processed. And it's done in elf_cpu_load_file().
4087 if ((prot & VM_PROT_EXECUTE) && pmap != kernel_pmap &&
4088 m->md.pv_memattr == VM_MEMATTR_WRITE_BACK &&
4089 (opa != pa || (orig_l3 & ATTR_S1_XN))) {
4090 PMAP_ASSERT_STAGE1(pmap);
4091 cpu_icache_sync_range(PHYS_TO_DMAP(pa), PAGE_SIZE);
4094 cpu_dcache_wb_range(PHYS_TO_DMAP(pa), PAGE_SIZE);
4098 * Update the L3 entry
4100 if (pmap_l3_valid(orig_l3)) {
4101 PMAP_ASSERT_STAGE1(pmap);
4102 KASSERT(opa == pa, ("pmap_enter: invalid update"));
4103 if ((orig_l3 & ~ATTR_AF) != (new_l3 & ~ATTR_AF)) {
4104 /* same PA, different attributes */
4105 orig_l3 = pmap_load_store(l3, new_l3);
4106 pmap_invalidate_page(pmap, va);
4107 if ((orig_l3 & ATTR_SW_MANAGED) != 0 &&
4108 pmap_pte_dirty(pmap, orig_l3))
4113 * This can happens if multiple threads simultaneously
4114 * access not yet mapped page. This bad for performance
4115 * since this can cause full demotion-NOP-promotion
4117 * Another possible reasons are:
4118 * - VM and pmap memory layout are diverged
4119 * - tlb flush is missing somewhere and CPU doesn't see
4122 CTR4(KTR_PMAP, "%s: already mapped page - "
4123 "pmap %p va 0x%#lx pte 0x%lx",
4124 __func__, pmap, va, new_l3);
4128 pmap_store(l3, new_l3);
4132 #if VM_NRESERVLEVEL > 0
4134 * Try to promote from level 3 pages to a level 2 superpage. This
4135 * currently only works on stage 1 pmaps as pmap_promote_l2 looks at
4136 * stage 1 specific fields and performs a break-before-make sequence
4137 * that is incorrect a stage 2 pmap.
4139 if ((mpte == NULL || mpte->ref_count == NL3PG) &&
4140 pmap_ps_enabled(pmap) && pmap->pm_stage == PM_STAGE1 &&
4141 (m->flags & PG_FICTITIOUS) == 0 &&
4142 vm_reserv_level_iffullpop(m) == 0) {
4143 pmap_promote_l2(pmap, pde, va, &lock);
4156 * Tries to create a read- and/or execute-only 2MB page mapping. Returns true
4157 * if successful. Returns false if (1) a page table page cannot be allocated
4158 * without sleeping, (2) a mapping already exists at the specified virtual
4159 * address, or (3) a PV entry cannot be allocated without reclaiming another
4163 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4164 struct rwlock **lockp)
4168 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4169 PMAP_ASSERT_STAGE1(pmap);
4171 new_l2 = (pd_entry_t)(VM_PAGE_TO_PHYS(m) | ATTR_DEFAULT |
4172 ATTR_S1_IDX(m->md.pv_memattr) | ATTR_S1_AP(ATTR_S1_AP_RO) |
4174 if ((m->oflags & VPO_UNMANAGED) == 0) {
4175 new_l2 |= ATTR_SW_MANAGED;
4178 if ((prot & VM_PROT_EXECUTE) == 0 ||
4179 m->md.pv_memattr == VM_MEMATTR_DEVICE)
4180 new_l2 |= ATTR_S1_XN;
4181 if (va < VM_MAXUSER_ADDRESS)
4182 new_l2 |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
4184 new_l2 |= ATTR_S1_UXN;
4185 if (pmap != kernel_pmap)
4186 new_l2 |= ATTR_S1_nG;
4187 return (pmap_enter_l2(pmap, va, new_l2, PMAP_ENTER_NOSLEEP |
4188 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
4193 * Returns true if every page table entry in the specified page table is
4197 pmap_every_pte_zero(vm_paddr_t pa)
4199 pt_entry_t *pt_end, *pte;
4201 KASSERT((pa & PAGE_MASK) == 0, ("pa is misaligned"));
4202 pte = (pt_entry_t *)PHYS_TO_DMAP(pa);
4203 for (pt_end = pte + Ln_ENTRIES; pte < pt_end; pte++) {
4211 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
4212 * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
4213 * otherwise. Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
4214 * a mapping already exists at the specified virtual address. Returns
4215 * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
4216 * page allocation failed. Returns KERN_RESOURCE_SHORTAGE if
4217 * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
4219 * The parameter "m" is only used when creating a managed, writeable mapping.
4222 pmap_enter_l2(pmap_t pmap, vm_offset_t va, pd_entry_t new_l2, u_int flags,
4223 vm_page_t m, struct rwlock **lockp)
4225 struct spglist free;
4226 pd_entry_t *l2, old_l2;
4229 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4231 if ((l2 = pmap_alloc_l2(pmap, va, &l2pg, (flags &
4232 PMAP_ENTER_NOSLEEP) != 0 ? NULL : lockp)) == NULL) {
4233 CTR2(KTR_PMAP, "pmap_enter_l2: failure for va %#lx in pmap %p",
4235 return (KERN_RESOURCE_SHORTAGE);
4239 * If there are existing mappings, either abort or remove them.
4241 if ((old_l2 = pmap_load(l2)) != 0) {
4242 KASSERT(l2pg == NULL || l2pg->ref_count > 1,
4243 ("pmap_enter_l2: l2pg's ref count is too low"));
4244 if ((flags & PMAP_ENTER_NOREPLACE) != 0 && (va <
4245 VM_MAXUSER_ADDRESS || (old_l2 & ATTR_DESCR_MASK) ==
4246 L2_BLOCK || !pmap_every_pte_zero(old_l2 & ~ATTR_MASK))) {
4249 CTR2(KTR_PMAP, "pmap_enter_l2: failure for va %#lx"
4250 " in pmap %p", va, pmap);
4251 return (KERN_FAILURE);
4254 if ((old_l2 & ATTR_DESCR_MASK) == L2_BLOCK)
4255 (void)pmap_remove_l2(pmap, l2, va,
4256 pmap_load(pmap_l1(pmap, va)), &free, lockp);
4258 pmap_remove_l3_range(pmap, old_l2, va, va + L2_SIZE,
4260 if (va < VM_MAXUSER_ADDRESS) {
4261 vm_page_free_pages_toq(&free, true);
4262 KASSERT(pmap_load(l2) == 0,
4263 ("pmap_enter_l2: non-zero L2 entry %p", l2));
4265 KASSERT(SLIST_EMPTY(&free),
4266 ("pmap_enter_l2: freed kernel page table page"));
4269 * Both pmap_remove_l2() and pmap_remove_l3_range()
4270 * will leave the kernel page table page zero filled.
4271 * Nonetheless, the TLB could have an intermediate
4272 * entry for the kernel page table page.
4274 mt = PHYS_TO_VM_PAGE(pmap_load(l2) & ~ATTR_MASK);
4275 if (pmap_insert_pt_page(pmap, mt, false))
4276 panic("pmap_enter_l2: trie insert failed");
4278 pmap_invalidate_page(pmap, va);
4282 if ((new_l2 & ATTR_SW_MANAGED) != 0) {
4284 * Abort this mapping if its PV entry could not be created.
4286 if (!pmap_pv_insert_l2(pmap, va, new_l2, flags, lockp)) {
4288 pmap_abort_ptp(pmap, va, l2pg);
4290 "pmap_enter_l2: failure for va %#lx in pmap %p",
4292 return (KERN_RESOURCE_SHORTAGE);
4294 if ((new_l2 & ATTR_SW_DBM) != 0)
4295 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
4296 vm_page_aflag_set(mt, PGA_WRITEABLE);
4300 * Increment counters.
4302 if ((new_l2 & ATTR_SW_WIRED) != 0)
4303 pmap->pm_stats.wired_count += L2_SIZE / PAGE_SIZE;
4304 pmap->pm_stats.resident_count += L2_SIZE / PAGE_SIZE;
4307 * Map the superpage.
4309 pmap_store(l2, new_l2);
4312 atomic_add_long(&pmap_l2_mappings, 1);
4313 CTR2(KTR_PMAP, "pmap_enter_l2: success for va %#lx in pmap %p",
4316 return (KERN_SUCCESS);
4320 * Maps a sequence of resident pages belonging to the same object.
4321 * The sequence begins with the given page m_start. This page is
4322 * mapped at the given virtual address start. Each subsequent page is
4323 * mapped at a virtual address that is offset from start by the same
4324 * amount as the page is offset from m_start within the object. The
4325 * last page in the sequence is the page with the largest offset from
4326 * m_start that can be mapped at a virtual address less than the given
4327 * virtual address end. Not every virtual page between start and end
4328 * is mapped; only those for which a resident page exists with the
4329 * corresponding offset from m_start are mapped.
4332 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
4333 vm_page_t m_start, vm_prot_t prot)
4335 struct rwlock *lock;
4338 vm_pindex_t diff, psize;
4340 VM_OBJECT_ASSERT_LOCKED(m_start->object);
4342 psize = atop(end - start);
4347 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
4348 va = start + ptoa(diff);
4349 if ((va & L2_OFFSET) == 0 && va + L2_SIZE <= end &&
4350 m->psind == 1 && pmap_ps_enabled(pmap) &&
4351 pmap_enter_2mpage(pmap, va, m, prot, &lock))
4352 m = &m[L2_SIZE / PAGE_SIZE - 1];
4354 mpte = pmap_enter_quick_locked(pmap, va, m, prot, mpte,
4356 m = TAILQ_NEXT(m, listq);
4364 * this code makes some *MAJOR* assumptions:
4365 * 1. Current pmap & pmap exists.
4368 * 4. No page table pages.
4369 * but is *MUCH* faster than pmap_enter...
4373 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
4375 struct rwlock *lock;
4379 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
4386 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
4387 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
4390 pt_entry_t *l2, *l3, l3_val;
4394 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
4395 (m->oflags & VPO_UNMANAGED) != 0,
4396 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
4397 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4398 PMAP_ASSERT_STAGE1(pmap);
4400 CTR2(KTR_PMAP, "pmap_enter_quick_locked: %p %lx", pmap, va);
4402 * In the case that a page table page is not
4403 * resident, we are creating it here.
4405 if (va < VM_MAXUSER_ADDRESS) {
4406 vm_pindex_t l2pindex;
4409 * Calculate pagetable page index
4411 l2pindex = pmap_l2_pindex(va);
4412 if (mpte && (mpte->pindex == l2pindex)) {
4418 pde = pmap_pde(pmap, va, &lvl);
4421 * If the page table page is mapped, we just increment
4422 * the hold count, and activate it. Otherwise, we
4423 * attempt to allocate a page table page. If this
4424 * attempt fails, we don't retry. Instead, we give up.
4427 l2 = pmap_l1_to_l2(pde, va);
4428 if ((pmap_load(l2) & ATTR_DESCR_MASK) ==
4432 if (lvl == 2 && pmap_load(pde) != 0) {
4434 PHYS_TO_VM_PAGE(pmap_load(pde) & ~ATTR_MASK);
4438 * Pass NULL instead of the PV list lock
4439 * pointer, because we don't intend to sleep.
4441 mpte = _pmap_alloc_l3(pmap, l2pindex, NULL);
4446 l3 = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
4447 l3 = &l3[pmap_l3_index(va)];
4450 pde = pmap_pde(kernel_pmap, va, &lvl);
4451 KASSERT(pde != NULL,
4452 ("pmap_enter_quick_locked: Invalid page entry, va: 0x%lx",
4455 ("pmap_enter_quick_locked: Invalid level %d", lvl));
4456 l3 = pmap_l2_to_l3(pde, va);
4460 * Abort if a mapping already exists.
4462 if (pmap_load(l3) != 0) {
4469 * Enter on the PV list if part of our managed memory.
4471 if ((m->oflags & VPO_UNMANAGED) == 0 &&
4472 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
4474 pmap_abort_ptp(pmap, va, mpte);
4479 * Increment counters
4481 pmap_resident_count_inc(pmap, 1);
4483 pa = VM_PAGE_TO_PHYS(m);
4484 l3_val = pa | ATTR_DEFAULT | ATTR_S1_IDX(m->md.pv_memattr) |
4485 ATTR_S1_AP(ATTR_S1_AP_RO) | L3_PAGE;
4486 if ((prot & VM_PROT_EXECUTE) == 0 ||
4487 m->md.pv_memattr == VM_MEMATTR_DEVICE)
4488 l3_val |= ATTR_S1_XN;
4489 if (va < VM_MAXUSER_ADDRESS)
4490 l3_val |= ATTR_S1_AP(ATTR_S1_AP_USER) | ATTR_S1_PXN;
4492 l3_val |= ATTR_S1_UXN;
4493 if (pmap != kernel_pmap)
4494 l3_val |= ATTR_S1_nG;
4497 * Now validate mapping with RO protection
4499 if ((m->oflags & VPO_UNMANAGED) == 0) {
4500 l3_val |= ATTR_SW_MANAGED;
4504 /* Sync icache before the mapping is stored to PTE */
4505 if ((prot & VM_PROT_EXECUTE) && pmap != kernel_pmap &&
4506 m->md.pv_memattr == VM_MEMATTR_WRITE_BACK)
4507 cpu_icache_sync_range(PHYS_TO_DMAP(pa), PAGE_SIZE);
4509 pmap_store(l3, l3_val);
4516 * This code maps large physical mmap regions into the
4517 * processor address space. Note that some shortcuts
4518 * are taken, but the code works.
4521 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
4522 vm_pindex_t pindex, vm_size_t size)
4525 VM_OBJECT_ASSERT_WLOCKED(object);
4526 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
4527 ("pmap_object_init_pt: non-device object"));
4531 * Clear the wired attribute from the mappings for the specified range of
4532 * addresses in the given pmap. Every valid mapping within that range
4533 * must have the wired attribute set. In contrast, invalid mappings
4534 * cannot have the wired attribute set, so they are ignored.
4536 * The wired attribute of the page table entry is not a hardware feature,
4537 * so there is no need to invalidate any TLB entries.
4540 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4542 vm_offset_t va_next;
4543 pd_entry_t *l0, *l1, *l2;
4547 for (; sva < eva; sva = va_next) {
4548 l0 = pmap_l0(pmap, sva);
4549 if (pmap_load(l0) == 0) {
4550 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
4556 l1 = pmap_l0_to_l1(l0, sva);
4557 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
4560 if (pmap_load(l1) == 0)
4563 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
4564 KASSERT(va_next <= eva,
4565 ("partial update of non-transparent 1G page "
4566 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
4567 pmap_load(l1), sva, eva, va_next));
4568 MPASS(pmap != kernel_pmap);
4569 MPASS((pmap_load(l1) & (ATTR_SW_MANAGED |
4570 ATTR_SW_WIRED)) == ATTR_SW_WIRED);
4571 pmap_clear_bits(l1, ATTR_SW_WIRED);
4572 pmap->pm_stats.wired_count -= L1_SIZE / PAGE_SIZE;
4576 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
4580 l2 = pmap_l1_to_l2(l1, sva);
4581 if (pmap_load(l2) == 0)
4584 if ((pmap_load(l2) & ATTR_DESCR_MASK) == L2_BLOCK) {
4585 if ((pmap_load(l2) & ATTR_SW_WIRED) == 0)
4586 panic("pmap_unwire: l2 %#jx is missing "
4587 "ATTR_SW_WIRED", (uintmax_t)pmap_load(l2));
4590 * Are we unwiring the entire large page? If not,
4591 * demote the mapping and fall through.
4593 if (sva + L2_SIZE == va_next && eva >= va_next) {
4594 pmap_clear_bits(l2, ATTR_SW_WIRED);
4595 pmap->pm_stats.wired_count -= L2_SIZE /
4598 } else if (pmap_demote_l2(pmap, l2, sva) == NULL)
4599 panic("pmap_unwire: demotion failed");
4601 KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
4602 ("pmap_unwire: Invalid l2 entry after demotion"));
4606 for (l3 = pmap_l2_to_l3(l2, sva); sva != va_next; l3++,
4608 if (pmap_load(l3) == 0)
4610 if ((pmap_load(l3) & ATTR_SW_WIRED) == 0)
4611 panic("pmap_unwire: l3 %#jx is missing "
4612 "ATTR_SW_WIRED", (uintmax_t)pmap_load(l3));
4615 * ATTR_SW_WIRED must be cleared atomically. Although
4616 * the pmap lock synchronizes access to ATTR_SW_WIRED,
4617 * the System MMU may write to the entry concurrently.
4619 pmap_clear_bits(l3, ATTR_SW_WIRED);
4620 pmap->pm_stats.wired_count--;
4627 * Copy the range specified by src_addr/len
4628 * from the source map to the range dst_addr/len
4629 * in the destination map.
4631 * This routine is only advisory and need not do anything.
4633 * Because the executable mappings created by this routine are copied,
4634 * it should not have to flush the instruction cache.
4637 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
4638 vm_offset_t src_addr)
4640 struct rwlock *lock;
4641 pd_entry_t *l0, *l1, *l2, srcptepaddr;
4642 pt_entry_t *dst_pte, mask, nbits, ptetemp, *src_pte;
4643 vm_offset_t addr, end_addr, va_next;
4644 vm_page_t dst_m, dstmpte, srcmpte;
4646 PMAP_ASSERT_STAGE1(dst_pmap);
4647 PMAP_ASSERT_STAGE1(src_pmap);
4649 if (dst_addr != src_addr)
4651 end_addr = src_addr + len;
4653 if (dst_pmap < src_pmap) {
4654 PMAP_LOCK(dst_pmap);
4655 PMAP_LOCK(src_pmap);
4657 PMAP_LOCK(src_pmap);
4658 PMAP_LOCK(dst_pmap);
4660 for (addr = src_addr; addr < end_addr; addr = va_next) {
4661 l0 = pmap_l0(src_pmap, addr);
4662 if (pmap_load(l0) == 0) {
4663 va_next = (addr + L0_SIZE) & ~L0_OFFSET;
4669 va_next = (addr + L1_SIZE) & ~L1_OFFSET;
4672 l1 = pmap_l0_to_l1(l0, addr);
4673 if (pmap_load(l1) == 0)
4675 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
4676 KASSERT(va_next <= end_addr,
4677 ("partial update of non-transparent 1G page "
4678 "l1 %#lx addr %#lx end_addr %#lx va_next %#lx",
4679 pmap_load(l1), addr, end_addr, va_next));
4680 srcptepaddr = pmap_load(l1);
4681 l1 = pmap_l1(dst_pmap, addr);
4683 if (_pmap_alloc_l3(dst_pmap,
4684 pmap_l0_pindex(addr), NULL) == NULL)
4686 l1 = pmap_l1(dst_pmap, addr);
4688 l0 = pmap_l0(dst_pmap, addr);
4689 dst_m = PHYS_TO_VM_PAGE(pmap_load(l0) &
4693 KASSERT(pmap_load(l1) == 0,
4694 ("1G mapping present in dst pmap "
4695 "l1 %#lx addr %#lx end_addr %#lx va_next %#lx",
4696 pmap_load(l1), addr, end_addr, va_next));
4697 pmap_store(l1, srcptepaddr & ~ATTR_SW_WIRED);
4698 pmap_resident_count_inc(dst_pmap, L1_SIZE / PAGE_SIZE);
4702 va_next = (addr + L2_SIZE) & ~L2_OFFSET;
4705 l2 = pmap_l1_to_l2(l1, addr);
4706 srcptepaddr = pmap_load(l2);
4707 if (srcptepaddr == 0)
4709 if ((srcptepaddr & ATTR_DESCR_MASK) == L2_BLOCK) {
4710 if ((addr & L2_OFFSET) != 0 ||
4711 addr + L2_SIZE > end_addr)
4713 l2 = pmap_alloc_l2(dst_pmap, addr, &dst_m, NULL);
4716 if (pmap_load(l2) == 0 &&
4717 ((srcptepaddr & ATTR_SW_MANAGED) == 0 ||
4718 pmap_pv_insert_l2(dst_pmap, addr, srcptepaddr,
4719 PMAP_ENTER_NORECLAIM, &lock))) {
4720 mask = ATTR_AF | ATTR_SW_WIRED;
4722 if ((srcptepaddr & ATTR_SW_DBM) != 0)
4723 nbits |= ATTR_S1_AP_RW_BIT;
4724 pmap_store(l2, (srcptepaddr & ~mask) | nbits);
4725 pmap_resident_count_inc(dst_pmap, L2_SIZE /
4727 atomic_add_long(&pmap_l2_mappings, 1);
4729 pmap_abort_ptp(dst_pmap, addr, dst_m);
4732 KASSERT((srcptepaddr & ATTR_DESCR_MASK) == L2_TABLE,
4733 ("pmap_copy: invalid L2 entry"));
4734 srcptepaddr &= ~ATTR_MASK;
4735 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
4736 KASSERT(srcmpte->ref_count > 0,
4737 ("pmap_copy: source page table page is unused"));
4738 if (va_next > end_addr)
4740 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
4741 src_pte = &src_pte[pmap_l3_index(addr)];
4743 for (; addr < va_next; addr += PAGE_SIZE, src_pte++) {
4744 ptetemp = pmap_load(src_pte);
4747 * We only virtual copy managed pages.
4749 if ((ptetemp & ATTR_SW_MANAGED) == 0)
4752 if (dstmpte != NULL) {
4753 KASSERT(dstmpte->pindex == pmap_l2_pindex(addr),
4754 ("dstmpte pindex/addr mismatch"));
4755 dstmpte->ref_count++;
4756 } else if ((dstmpte = pmap_alloc_l3(dst_pmap, addr,
4759 dst_pte = (pt_entry_t *)
4760 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
4761 dst_pte = &dst_pte[pmap_l3_index(addr)];
4762 if (pmap_load(dst_pte) == 0 &&
4763 pmap_try_insert_pv_entry(dst_pmap, addr,
4764 PHYS_TO_VM_PAGE(ptetemp & ~ATTR_MASK), &lock)) {
4766 * Clear the wired, modified, and accessed
4767 * (referenced) bits during the copy.
4769 mask = ATTR_AF | ATTR_SW_WIRED;
4771 if ((ptetemp & ATTR_SW_DBM) != 0)
4772 nbits |= ATTR_S1_AP_RW_BIT;
4773 pmap_store(dst_pte, (ptetemp & ~mask) | nbits);
4774 pmap_resident_count_inc(dst_pmap, 1);
4776 pmap_abort_ptp(dst_pmap, addr, dstmpte);
4779 /* Have we copied all of the valid mappings? */
4780 if (dstmpte->ref_count >= srcmpte->ref_count)
4786 * XXX This barrier may not be needed because the destination pmap is
4793 PMAP_UNLOCK(src_pmap);
4794 PMAP_UNLOCK(dst_pmap);
4798 * pmap_zero_page zeros the specified hardware page by mapping
4799 * the page into KVM and using bzero to clear its contents.
4802 pmap_zero_page(vm_page_t m)
4804 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
4806 pagezero((void *)va);
4810 * pmap_zero_page_area zeros the specified hardware page by mapping
4811 * the page into KVM and using bzero to clear its contents.
4813 * off and size may not cover an area beyond a single hardware page.
4816 pmap_zero_page_area(vm_page_t m, int off, int size)
4818 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
4820 if (off == 0 && size == PAGE_SIZE)
4821 pagezero((void *)va);
4823 bzero((char *)va + off, size);
4827 * pmap_copy_page copies the specified (machine independent)
4828 * page by mapping the page into virtual memory and using
4829 * bcopy to copy the page, one machine dependent page at a
4833 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
4835 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
4836 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
4838 pagecopy((void *)src, (void *)dst);
4841 int unmapped_buf_allowed = 1;
4844 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
4845 vm_offset_t b_offset, int xfersize)
4849 vm_paddr_t p_a, p_b;
4850 vm_offset_t a_pg_offset, b_pg_offset;
4853 while (xfersize > 0) {
4854 a_pg_offset = a_offset & PAGE_MASK;
4855 m_a = ma[a_offset >> PAGE_SHIFT];
4856 p_a = m_a->phys_addr;
4857 b_pg_offset = b_offset & PAGE_MASK;
4858 m_b = mb[b_offset >> PAGE_SHIFT];
4859 p_b = m_b->phys_addr;
4860 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
4861 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
4862 if (__predict_false(!PHYS_IN_DMAP(p_a))) {
4863 panic("!DMAP a %lx", p_a);
4865 a_cp = (char *)PHYS_TO_DMAP(p_a) + a_pg_offset;
4867 if (__predict_false(!PHYS_IN_DMAP(p_b))) {
4868 panic("!DMAP b %lx", p_b);
4870 b_cp = (char *)PHYS_TO_DMAP(p_b) + b_pg_offset;
4872 bcopy(a_cp, b_cp, cnt);
4880 pmap_quick_enter_page(vm_page_t m)
4883 return (PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)));
4887 pmap_quick_remove_page(vm_offset_t addr)
4892 * Returns true if the pmap's pv is one of the first
4893 * 16 pvs linked to from this page. This count may
4894 * be changed upwards or downwards in the future; it
4895 * is only necessary that true be returned for a small
4896 * subset of pmaps for proper page aging.
4899 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
4901 struct md_page *pvh;
4902 struct rwlock *lock;
4907 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4908 ("pmap_page_exists_quick: page %p is not managed", m));
4910 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4912 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
4913 if (PV_PMAP(pv) == pmap) {
4921 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
4922 pvh = page_to_pvh(m);
4923 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
4924 if (PV_PMAP(pv) == pmap) {
4938 * pmap_page_wired_mappings:
4940 * Return the number of managed mappings to the given physical page
4944 pmap_page_wired_mappings(vm_page_t m)
4946 struct rwlock *lock;
4947 struct md_page *pvh;
4951 int count, lvl, md_gen, pvh_gen;
4953 if ((m->oflags & VPO_UNMANAGED) != 0)
4955 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4959 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
4961 if (!PMAP_TRYLOCK(pmap)) {
4962 md_gen = m->md.pv_gen;
4966 if (md_gen != m->md.pv_gen) {
4971 pte = pmap_pte(pmap, pv->pv_va, &lvl);
4972 if (pte != NULL && (pmap_load(pte) & ATTR_SW_WIRED) != 0)
4976 if ((m->flags & PG_FICTITIOUS) == 0) {
4977 pvh = page_to_pvh(m);
4978 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
4980 if (!PMAP_TRYLOCK(pmap)) {
4981 md_gen = m->md.pv_gen;
4982 pvh_gen = pvh->pv_gen;
4986 if (md_gen != m->md.pv_gen ||
4987 pvh_gen != pvh->pv_gen) {
4992 pte = pmap_pte(pmap, pv->pv_va, &lvl);
4994 (pmap_load(pte) & ATTR_SW_WIRED) != 0)
5004 * Returns true if the given page is mapped individually or as part of
5005 * a 2mpage. Otherwise, returns false.
5008 pmap_page_is_mapped(vm_page_t m)
5010 struct rwlock *lock;
5013 if ((m->oflags & VPO_UNMANAGED) != 0)
5015 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5017 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5018 ((m->flags & PG_FICTITIOUS) == 0 &&
5019 !TAILQ_EMPTY(&page_to_pvh(m)->pv_list));
5025 * Destroy all managed, non-wired mappings in the given user-space
5026 * pmap. This pmap cannot be active on any processor besides the
5029 * This function cannot be applied to the kernel pmap. Moreover, it
5030 * is not intended for general use. It is only to be used during
5031 * process termination. Consequently, it can be implemented in ways
5032 * that make it faster than pmap_remove(). First, it can more quickly
5033 * destroy mappings by iterating over the pmap's collection of PV
5034 * entries, rather than searching the page table. Second, it doesn't
5035 * have to test and clear the page table entries atomically, because
5036 * no processor is currently accessing the user address space. In
5037 * particular, a page table entry's dirty bit won't change state once
5038 * this function starts.
5041 pmap_remove_pages(pmap_t pmap)
5044 pt_entry_t *pte, tpte;
5045 struct spglist free;
5046 vm_page_t m, ml3, mt;
5048 struct md_page *pvh;
5049 struct pv_chunk *pc, *npc;
5050 struct rwlock *lock;
5052 uint64_t inuse, bitmask;
5053 int allfree, field, freed, idx, lvl;
5060 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5063 for (field = 0; field < _NPCM; field++) {
5064 inuse = ~pc->pc_map[field] & pc_freemask[field];
5065 while (inuse != 0) {
5066 bit = ffsl(inuse) - 1;
5067 bitmask = 1UL << bit;
5068 idx = field * 64 + bit;
5069 pv = &pc->pc_pventry[idx];
5072 pde = pmap_pde(pmap, pv->pv_va, &lvl);
5073 KASSERT(pde != NULL,
5074 ("Attempting to remove an unmapped page"));
5078 pte = pmap_l1_to_l2(pde, pv->pv_va);
5079 tpte = pmap_load(pte);
5080 KASSERT((tpte & ATTR_DESCR_MASK) ==
5082 ("Attempting to remove an invalid "
5083 "block: %lx", tpte));
5086 pte = pmap_l2_to_l3(pde, pv->pv_va);
5087 tpte = pmap_load(pte);
5088 KASSERT((tpte & ATTR_DESCR_MASK) ==
5090 ("Attempting to remove an invalid "
5091 "page: %lx", tpte));
5095 "Invalid page directory level: %d",
5100 * We cannot remove wired pages from a process' mapping at this time
5102 if (tpte & ATTR_SW_WIRED) {
5107 pa = tpte & ~ATTR_MASK;
5109 m = PHYS_TO_VM_PAGE(pa);
5110 KASSERT(m->phys_addr == pa,
5111 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
5112 m, (uintmax_t)m->phys_addr,
5115 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
5116 m < &vm_page_array[vm_page_array_size],
5117 ("pmap_remove_pages: bad pte %#jx",
5121 * Because this pmap is not active on other
5122 * processors, the dirty bit cannot have
5123 * changed state since we last loaded pte.
5128 * Update the vm_page_t clean/reference bits.
5130 if (pmap_pte_dirty(pmap, tpte)) {
5133 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
5142 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
5145 pc->pc_map[field] |= bitmask;
5148 pmap_resident_count_dec(pmap,
5149 L2_SIZE / PAGE_SIZE);
5150 pvh = pa_to_pvh(tpte & ~ATTR_MASK);
5151 TAILQ_REMOVE(&pvh->pv_list, pv,pv_next);
5153 if (TAILQ_EMPTY(&pvh->pv_list)) {
5154 for (mt = m; mt < &m[L2_SIZE / PAGE_SIZE]; mt++)
5155 if ((mt->a.flags & PGA_WRITEABLE) != 0 &&
5156 TAILQ_EMPTY(&mt->md.pv_list))
5157 vm_page_aflag_clear(mt, PGA_WRITEABLE);
5159 ml3 = pmap_remove_pt_page(pmap,
5162 KASSERT(ml3->valid == VM_PAGE_BITS_ALL,
5163 ("pmap_remove_pages: l3 page not promoted"));
5164 pmap_resident_count_dec(pmap,1);
5165 KASSERT(ml3->ref_count == NL3PG,
5166 ("pmap_remove_pages: l3 page ref count error"));
5168 pmap_add_delayed_free_list(ml3,
5173 pmap_resident_count_dec(pmap, 1);
5174 TAILQ_REMOVE(&m->md.pv_list, pv,
5177 if ((m->a.flags & PGA_WRITEABLE) != 0 &&
5178 TAILQ_EMPTY(&m->md.pv_list) &&
5179 (m->flags & PG_FICTITIOUS) == 0) {
5180 pvh = page_to_pvh(m);
5181 if (TAILQ_EMPTY(&pvh->pv_list))
5182 vm_page_aflag_clear(m,
5187 pmap_unuse_pt(pmap, pv->pv_va, pmap_load(pde),
5192 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
5193 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
5194 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
5196 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5202 pmap_invalidate_all(pmap);
5204 vm_page_free_pages_toq(&free, true);
5208 * This is used to check if a page has been accessed or modified.
5211 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
5213 struct rwlock *lock;
5215 struct md_page *pvh;
5216 pt_entry_t *pte, mask, value;
5218 int lvl, md_gen, pvh_gen;
5222 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5225 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5227 PMAP_ASSERT_STAGE1(pmap);
5228 if (!PMAP_TRYLOCK(pmap)) {
5229 md_gen = m->md.pv_gen;
5233 if (md_gen != m->md.pv_gen) {
5238 pte = pmap_pte(pmap, pv->pv_va, &lvl);
5240 ("pmap_page_test_mappings: Invalid level %d", lvl));
5244 mask |= ATTR_S1_AP_RW_BIT;
5245 value |= ATTR_S1_AP(ATTR_S1_AP_RW);
5248 mask |= ATTR_AF | ATTR_DESCR_MASK;
5249 value |= ATTR_AF | L3_PAGE;
5251 rv = (pmap_load(pte) & mask) == value;
5256 if ((m->flags & PG_FICTITIOUS) == 0) {
5257 pvh = page_to_pvh(m);
5258 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5260 PMAP_ASSERT_STAGE1(pmap);
5261 if (!PMAP_TRYLOCK(pmap)) {
5262 md_gen = m->md.pv_gen;
5263 pvh_gen = pvh->pv_gen;
5267 if (md_gen != m->md.pv_gen ||
5268 pvh_gen != pvh->pv_gen) {
5273 pte = pmap_pte(pmap, pv->pv_va, &lvl);
5275 ("pmap_page_test_mappings: Invalid level %d", lvl));
5279 mask |= ATTR_S1_AP_RW_BIT;
5280 value |= ATTR_S1_AP(ATTR_S1_AP_RW);
5283 mask |= ATTR_AF | ATTR_DESCR_MASK;
5284 value |= ATTR_AF | L2_BLOCK;
5286 rv = (pmap_load(pte) & mask) == value;
5300 * Return whether or not the specified physical page was modified
5301 * in any physical maps.
5304 pmap_is_modified(vm_page_t m)
5307 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5308 ("pmap_is_modified: page %p is not managed", m));
5311 * If the page is not busied then this check is racy.
5313 if (!pmap_page_is_write_mapped(m))
5315 return (pmap_page_test_mappings(m, FALSE, TRUE));
5319 * pmap_is_prefaultable:
5321 * Return whether or not the specified virtual address is eligible
5325 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
5333 pte = pmap_pte(pmap, addr, &lvl);
5334 if (pte != NULL && pmap_load(pte) != 0) {
5342 * pmap_is_referenced:
5344 * Return whether or not the specified physical page was referenced
5345 * in any physical maps.
5348 pmap_is_referenced(vm_page_t m)
5351 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5352 ("pmap_is_referenced: page %p is not managed", m));
5353 return (pmap_page_test_mappings(m, TRUE, FALSE));
5357 * Clear the write and modified bits in each of the given page's mappings.
5360 pmap_remove_write(vm_page_t m)
5362 struct md_page *pvh;
5364 struct rwlock *lock;
5365 pv_entry_t next_pv, pv;
5366 pt_entry_t oldpte, *pte;
5368 int lvl, md_gen, pvh_gen;
5370 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5371 ("pmap_remove_write: page %p is not managed", m));
5372 vm_page_assert_busied(m);
5374 if (!pmap_page_is_write_mapped(m))
5376 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5377 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
5380 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
5382 PMAP_ASSERT_STAGE1(pmap);
5383 if (!PMAP_TRYLOCK(pmap)) {
5384 pvh_gen = pvh->pv_gen;
5388 if (pvh_gen != pvh->pv_gen) {
5395 pte = pmap_pte(pmap, pv->pv_va, &lvl);
5396 if ((pmap_load(pte) & ATTR_SW_DBM) != 0)
5397 (void)pmap_demote_l2_locked(pmap, pte, va, &lock);
5398 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
5399 ("inconsistent pv lock %p %p for page %p",
5400 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
5403 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5405 PMAP_ASSERT_STAGE1(pmap);
5406 if (!PMAP_TRYLOCK(pmap)) {
5407 pvh_gen = pvh->pv_gen;
5408 md_gen = m->md.pv_gen;
5412 if (pvh_gen != pvh->pv_gen ||
5413 md_gen != m->md.pv_gen) {
5419 pte = pmap_pte(pmap, pv->pv_va, &lvl);
5420 oldpte = pmap_load(pte);
5422 if ((oldpte & ATTR_SW_DBM) != 0) {
5423 if (!atomic_fcmpset_long(pte, &oldpte,
5424 (oldpte | ATTR_S1_AP_RW_BIT) & ~ATTR_SW_DBM))
5426 if ((oldpte & ATTR_S1_AP_RW_BIT) ==
5427 ATTR_S1_AP(ATTR_S1_AP_RW))
5429 pmap_invalidate_page(pmap, pv->pv_va);
5434 vm_page_aflag_clear(m, PGA_WRITEABLE);
5438 * pmap_ts_referenced:
5440 * Return a count of reference bits for a page, clearing those bits.
5441 * It is not necessary for every reference bit to be cleared, but it
5442 * is necessary that 0 only be returned when there are truly no
5443 * reference bits set.
5445 * As an optimization, update the page's dirty field if a modified bit is
5446 * found while counting reference bits. This opportunistic update can be
5447 * performed at low cost and can eliminate the need for some future calls
5448 * to pmap_is_modified(). However, since this function stops after
5449 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
5450 * dirty pages. Those dirty pages will only be detected by a future call
5451 * to pmap_is_modified().
5454 pmap_ts_referenced(vm_page_t m)
5456 struct md_page *pvh;
5459 struct rwlock *lock;
5460 pd_entry_t *pde, tpde;
5461 pt_entry_t *pte, tpte;
5464 int cleared, lvl, md_gen, not_cleared, pvh_gen;
5465 struct spglist free;
5467 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5468 ("pmap_ts_referenced: page %p is not managed", m));
5471 pa = VM_PAGE_TO_PHYS(m);
5472 lock = PHYS_TO_PV_LIST_LOCK(pa);
5473 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
5477 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
5478 goto small_mappings;
5484 if (!PMAP_TRYLOCK(pmap)) {
5485 pvh_gen = pvh->pv_gen;
5489 if (pvh_gen != pvh->pv_gen) {
5495 pde = pmap_pde(pmap, pv->pv_va, &lvl);
5496 KASSERT(pde != NULL, ("pmap_ts_referenced: no l1 table found"));
5498 ("pmap_ts_referenced: invalid pde level %d", lvl));
5499 tpde = pmap_load(pde);
5500 KASSERT((tpde & ATTR_DESCR_MASK) == L1_TABLE,
5501 ("pmap_ts_referenced: found an invalid l1 table"));
5502 pte = pmap_l1_to_l2(pde, pv->pv_va);
5503 tpte = pmap_load(pte);
5504 if (pmap_pte_dirty(pmap, tpte)) {
5506 * Although "tpte" is mapping a 2MB page, because
5507 * this function is called at a 4KB page granularity,
5508 * we only update the 4KB page under test.
5513 if ((tpte & ATTR_AF) != 0) {
5515 * Since this reference bit is shared by 512 4KB pages,
5516 * it should not be cleared every time it is tested.
5517 * Apply a simple "hash" function on the physical page
5518 * number, the virtual superpage number, and the pmap
5519 * address to select one 4KB page out of the 512 on
5520 * which testing the reference bit will result in
5521 * clearing that reference bit. This function is
5522 * designed to avoid the selection of the same 4KB page
5523 * for every 2MB page mapping.
5525 * On demotion, a mapping that hasn't been referenced
5526 * is simply destroyed. To avoid the possibility of a
5527 * subsequent page fault on a demoted wired mapping,
5528 * always leave its reference bit set. Moreover,
5529 * since the superpage is wired, the current state of
5530 * its reference bit won't affect page replacement.
5532 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> L2_SHIFT) ^
5533 (uintptr_t)pmap) & (Ln_ENTRIES - 1)) == 0 &&
5534 (tpte & ATTR_SW_WIRED) == 0) {
5535 pmap_clear_bits(pte, ATTR_AF);
5536 pmap_invalidate_page(pmap, pv->pv_va);
5542 /* Rotate the PV list if it has more than one entry. */
5543 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
5544 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5545 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5548 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
5550 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
5552 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
5559 if (!PMAP_TRYLOCK(pmap)) {
5560 pvh_gen = pvh->pv_gen;
5561 md_gen = m->md.pv_gen;
5565 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
5570 pde = pmap_pde(pmap, pv->pv_va, &lvl);
5571 KASSERT(pde != NULL, ("pmap_ts_referenced: no l2 table found"));
5573 ("pmap_ts_referenced: invalid pde level %d", lvl));
5574 tpde = pmap_load(pde);
5575 KASSERT((tpde & ATTR_DESCR_MASK) == L2_TABLE,
5576 ("pmap_ts_referenced: found an invalid l2 table"));
5577 pte = pmap_l2_to_l3(pde, pv->pv_va);
5578 tpte = pmap_load(pte);
5579 if (pmap_pte_dirty(pmap, tpte))
5581 if ((tpte & ATTR_AF) != 0) {
5582 if ((tpte & ATTR_SW_WIRED) == 0) {
5583 pmap_clear_bits(pte, ATTR_AF);
5584 pmap_invalidate_page(pmap, pv->pv_va);
5590 /* Rotate the PV list if it has more than one entry. */
5591 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
5592 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5593 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5596 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
5597 not_cleared < PMAP_TS_REFERENCED_MAX);
5600 vm_page_free_pages_toq(&free, true);
5601 return (cleared + not_cleared);
5605 * Apply the given advice to the specified range of addresses within the
5606 * given pmap. Depending on the advice, clear the referenced and/or
5607 * modified flags in each mapping and set the mapped page's dirty field.
5610 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
5612 struct rwlock *lock;
5613 vm_offset_t va, va_next;
5615 pd_entry_t *l0, *l1, *l2, oldl2;
5616 pt_entry_t *l3, oldl3;
5618 PMAP_ASSERT_STAGE1(pmap);
5620 if (advice != MADV_DONTNEED && advice != MADV_FREE)
5624 for (; sva < eva; sva = va_next) {
5625 l0 = pmap_l0(pmap, sva);
5626 if (pmap_load(l0) == 0) {
5627 va_next = (sva + L0_SIZE) & ~L0_OFFSET;
5633 va_next = (sva + L1_SIZE) & ~L1_OFFSET;
5636 l1 = pmap_l0_to_l1(l0, sva);
5637 if (pmap_load(l1) == 0)
5639 if ((pmap_load(l1) & ATTR_DESCR_MASK) == L1_BLOCK) {
5640 KASSERT(va_next <= eva,
5641 ("partial update of non-transparent 1G page "
5642 "l1 %#lx sva %#lx eva %#lx va_next %#lx",
5643 pmap_load(l1), sva, eva, va_next));
5647 va_next = (sva + L2_SIZE) & ~L2_OFFSET;
5650 l2 = pmap_l1_to_l2(l1, sva);
5651 oldl2 = pmap_load(l2);
5654 if ((oldl2 & ATTR_DESCR_MASK) == L2_BLOCK) {
5655 if ((oldl2 & ATTR_SW_MANAGED) == 0)
5658 if (!pmap_demote_l2_locked(pmap, l2, sva, &lock)) {
5663 * The 2MB page mapping was destroyed.
5669 * Unless the page mappings are wired, remove the
5670 * mapping to a single page so that a subsequent
5671 * access may repromote. Choosing the last page
5672 * within the address range [sva, min(va_next, eva))
5673 * generally results in more repromotions. Since the
5674 * underlying page table page is fully populated, this
5675 * removal never frees a page table page.
5677 if ((oldl2 & ATTR_SW_WIRED) == 0) {
5683 ("pmap_advise: no address gap"));
5684 l3 = pmap_l2_to_l3(l2, va);
5685 KASSERT(pmap_load(l3) != 0,
5686 ("pmap_advise: invalid PTE"));
5687 pmap_remove_l3(pmap, l3, va, pmap_load(l2),
5693 KASSERT((pmap_load(l2) & ATTR_DESCR_MASK) == L2_TABLE,
5694 ("pmap_advise: invalid L2 entry after demotion"));
5698 for (l3 = pmap_l2_to_l3(l2, sva); sva != va_next; l3++,
5700 oldl3 = pmap_load(l3);
5701 if ((oldl3 & (ATTR_SW_MANAGED | ATTR_DESCR_MASK)) !=
5702 (ATTR_SW_MANAGED | L3_PAGE))
5704 else if (pmap_pte_dirty(pmap, oldl3)) {
5705 if (advice == MADV_DONTNEED) {
5707 * Future calls to pmap_is_modified()
5708 * can be avoided by making the page
5711 m = PHYS_TO_VM_PAGE(oldl3 & ~ATTR_MASK);
5714 while (!atomic_fcmpset_long(l3, &oldl3,
5715 (oldl3 & ~ATTR_AF) |
5716 ATTR_S1_AP(ATTR_S1_AP_RO)))
5718 } else if ((oldl3 & ATTR_AF) != 0)
5719 pmap_clear_bits(l3, ATTR_AF);
5726 if (va != va_next) {
5727 pmap_invalidate_range(pmap, va, sva);
5732 pmap_invalidate_range(pmap, va, sva);
5738 * Clear the modify bits on the specified physical page.
5741 pmap_clear_modify(vm_page_t m)
5743 struct md_page *pvh;
5744 struct rwlock *lock;
5746 pv_entry_t next_pv, pv;
5747 pd_entry_t *l2, oldl2;
5748 pt_entry_t *l3, oldl3;
5750 int md_gen, pvh_gen;
5752 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5753 ("pmap_clear_modify: page %p is not managed", m));
5754 vm_page_assert_busied(m);
5756 if (!pmap_page_is_write_mapped(m))
5758 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : page_to_pvh(m);
5759 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5762 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
5764 PMAP_ASSERT_STAGE1(pmap);
5765 if (!PMAP_TRYLOCK(pmap)) {
5766 pvh_gen = pvh->pv_gen;
5770 if (pvh_gen != pvh->pv_gen) {
5776 l2 = pmap_l2(pmap, va);
5777 oldl2 = pmap_load(l2);
5778 /* If oldl2 has ATTR_SW_DBM set, then it is also dirty. */
5779 if ((oldl2 & ATTR_SW_DBM) != 0 &&
5780 pmap_demote_l2_locked(pmap, l2, va, &lock) &&
5781 (oldl2 & ATTR_SW_WIRED) == 0) {
5783 * Write protect the mapping to a single page so that
5784 * a subsequent write access may repromote.
5786 va += VM_PAGE_TO_PHYS(m) - (oldl2 & ~ATTR_MASK);
5787 l3 = pmap_l2_to_l3(l2, va);
5788 oldl3 = pmap_load(l3);
5789 while (!atomic_fcmpset_long(l3, &oldl3,
5790 (oldl3 & ~ATTR_SW_DBM) | ATTR_S1_AP(ATTR_S1_AP_RO)))
5793 pmap_invalidate_page(pmap, va);
5797 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5799 PMAP_ASSERT_STAGE1(pmap);
5800 if (!PMAP_TRYLOCK(pmap)) {
5801 md_gen = m->md.pv_gen;
5802 pvh_gen = pvh->pv_gen;
5806 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
5811 l2 = pmap_l2(pmap, pv->pv_va);
5812 l3 = pmap_l2_to_l3(l2, pv->pv_va);
5813 oldl3 = pmap_load(l3);
5814 if (pmap_l3_valid(oldl3) &&
5815 (oldl3 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) == ATTR_SW_DBM){
5816 pmap_set_bits(l3, ATTR_S1_AP(ATTR_S1_AP_RO));
5817 pmap_invalidate_page(pmap, pv->pv_va);
5825 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
5827 struct pmap_preinit_mapping *ppim;
5828 vm_offset_t va, offset;
5831 int i, lvl, l2_blocks, free_l2_count, start_idx;
5833 if (!vm_initialized) {
5835 * No L3 ptables so map entire L2 blocks where start VA is:
5836 * preinit_map_va + start_idx * L2_SIZE
5837 * There may be duplicate mappings (multiple VA -> same PA) but
5838 * ARM64 dcache is always PIPT so that's acceptable.
5843 /* Calculate how many L2 blocks are needed for the mapping */
5844 l2_blocks = (roundup2(pa + size, L2_SIZE) -
5845 rounddown2(pa, L2_SIZE)) >> L2_SHIFT;
5847 offset = pa & L2_OFFSET;
5849 if (preinit_map_va == 0)
5852 /* Map 2MiB L2 blocks from reserved VA space */
5856 /* Find enough free contiguous VA space */
5857 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
5858 ppim = pmap_preinit_mapping + i;
5859 if (free_l2_count > 0 && ppim->pa != 0) {
5860 /* Not enough space here */
5866 if (ppim->pa == 0) {
5868 if (start_idx == -1)
5871 if (free_l2_count == l2_blocks)
5875 if (free_l2_count != l2_blocks)
5876 panic("%s: too many preinit mappings", __func__);
5878 va = preinit_map_va + (start_idx * L2_SIZE);
5879 for (i = start_idx; i < start_idx + l2_blocks; i++) {
5880 /* Mark entries as allocated */
5881 ppim = pmap_preinit_mapping + i;
5883 ppim->va = va + offset;
5888 pa = rounddown2(pa, L2_SIZE);
5889 for (i = 0; i < l2_blocks; i++) {
5890 pde = pmap_pde(kernel_pmap, va, &lvl);
5891 KASSERT(pde != NULL,
5892 ("pmap_mapbios: Invalid page entry, va: 0x%lx",
5895 ("pmap_mapbios: Invalid level %d", lvl));
5897 /* Insert L2_BLOCK */
5898 l2 = pmap_l1_to_l2(pde, va);
5900 pa | ATTR_DEFAULT | ATTR_S1_XN |
5901 ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK) | L2_BLOCK);
5906 pmap_invalidate_all(kernel_pmap);
5908 va = preinit_map_va + (start_idx * L2_SIZE);
5911 /* kva_alloc may be used to map the pages */
5912 offset = pa & PAGE_MASK;
5913 size = round_page(offset + size);
5915 va = kva_alloc(size);
5917 panic("%s: Couldn't allocate KVA", __func__);
5919 pde = pmap_pde(kernel_pmap, va, &lvl);
5920 KASSERT(lvl == 2, ("pmap_mapbios: Invalid level %d", lvl));
5922 /* L3 table is linked */
5923 va = trunc_page(va);
5924 pa = trunc_page(pa);
5925 pmap_kenter(va, size, pa, memory_mapping_mode(pa));
5928 return ((void *)(va + offset));
5932 pmap_unmapbios(vm_offset_t va, vm_size_t size)
5934 struct pmap_preinit_mapping *ppim;
5935 vm_offset_t offset, tmpsize, va_trunc;
5938 int i, lvl, l2_blocks, block;
5942 (roundup2(va + size, L2_SIZE) - rounddown2(va, L2_SIZE)) >> L2_SHIFT;
5943 KASSERT(l2_blocks > 0, ("pmap_unmapbios: invalid size %lx", size));
5945 /* Remove preinit mapping */
5946 preinit_map = false;
5948 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
5949 ppim = pmap_preinit_mapping + i;
5950 if (ppim->va == va) {
5951 KASSERT(ppim->size == size,
5952 ("pmap_unmapbios: size mismatch"));
5957 offset = block * L2_SIZE;
5958 va_trunc = rounddown2(va, L2_SIZE) + offset;
5960 /* Remove L2_BLOCK */
5961 pde = pmap_pde(kernel_pmap, va_trunc, &lvl);
5962 KASSERT(pde != NULL,
5963 ("pmap_unmapbios: Invalid page entry, va: 0x%lx",
5965 l2 = pmap_l1_to_l2(pde, va_trunc);
5968 if (block == (l2_blocks - 1))
5974 pmap_invalidate_all(kernel_pmap);
5978 /* Unmap the pages reserved with kva_alloc. */
5979 if (vm_initialized) {
5980 offset = va & PAGE_MASK;
5981 size = round_page(offset + size);
5982 va = trunc_page(va);
5984 pde = pmap_pde(kernel_pmap, va, &lvl);
5985 KASSERT(pde != NULL,
5986 ("pmap_unmapbios: Invalid page entry, va: 0x%lx", va));
5987 KASSERT(lvl == 2, ("pmap_unmapbios: Invalid level %d", lvl));
5989 /* Unmap and invalidate the pages */
5990 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
5991 pmap_kremove(va + tmpsize);
5998 * Sets the memory attribute for the specified page.
6001 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
6004 m->md.pv_memattr = ma;
6007 * If "m" is a normal page, update its direct mapping. This update
6008 * can be relied upon to perform any cache operations that are
6009 * required for data coherence.
6011 if ((m->flags & PG_FICTITIOUS) == 0 &&
6012 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
6013 m->md.pv_memattr) != 0)
6014 panic("memory attribute change on the direct map failed");
6018 * Changes the specified virtual address range's memory type to that given by
6019 * the parameter "mode". The specified virtual address range must be
6020 * completely contained within either the direct map or the kernel map. If
6021 * the virtual address range is contained within the kernel map, then the
6022 * memory type for each of the corresponding ranges of the direct map is also
6023 * changed. (The corresponding ranges of the direct map are those ranges that
6024 * map the same physical pages as the specified virtual address range.) These
6025 * changes to the direct map are necessary because Intel describes the
6026 * behavior of their processors as "undefined" if two or more mappings to the
6027 * same physical page have different memory types.
6029 * Returns zero if the change completed successfully, and either EINVAL or
6030 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
6031 * of the virtual address range was not mapped, and ENOMEM is returned if
6032 * there was insufficient memory available to complete the change. In the
6033 * latter case, the memory type may have been changed on some part of the
6034 * virtual address range or the direct map.
6037 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
6041 PMAP_LOCK(kernel_pmap);
6042 error = pmap_change_attr_locked(va, size, mode);
6043 PMAP_UNLOCK(kernel_pmap);
6048 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
6050 vm_offset_t base, offset, tmpva;
6051 pt_entry_t l3, *pte, *newpte;
6054 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
6055 base = trunc_page(va);
6056 offset = va & PAGE_MASK;
6057 size = round_page(offset + size);
6059 if (!VIRT_IN_DMAP(base) &&
6060 !(base >= VM_MIN_KERNEL_ADDRESS && base < VM_MAX_KERNEL_ADDRESS))
6063 for (tmpva = base; tmpva < base + size; ) {
6064 pte = pmap_pte(kernel_pmap, tmpva, &lvl);
6068 if ((pmap_load(pte) & ATTR_S1_IDX_MASK) == ATTR_S1_IDX(mode)) {
6070 * We already have the correct attribute,
6071 * ignore this entry.
6075 panic("Invalid DMAP table level: %d\n", lvl);
6077 tmpva = (tmpva & ~L1_OFFSET) + L1_SIZE;
6080 tmpva = (tmpva & ~L2_OFFSET) + L2_SIZE;
6088 * Split the entry to an level 3 table, then
6089 * set the new attribute.
6093 panic("Invalid DMAP table level: %d\n", lvl);
6095 newpte = pmap_demote_l1(kernel_pmap, pte,
6096 tmpva & ~L1_OFFSET);
6099 pte = pmap_l1_to_l2(pte, tmpva);
6101 newpte = pmap_demote_l2(kernel_pmap, pte,
6105 pte = pmap_l2_to_l3(pte, tmpva);
6107 /* Update the entry */
6108 l3 = pmap_load(pte);
6109 l3 &= ~ATTR_S1_IDX_MASK;
6110 l3 |= ATTR_S1_IDX(mode);
6111 if (mode == VM_MEMATTR_DEVICE)
6114 pmap_update_entry(kernel_pmap, pte, l3, tmpva,
6118 * If moving to a non-cacheable entry flush
6121 if (mode == VM_MEMATTR_UNCACHEABLE)
6122 cpu_dcache_wbinv_range(tmpva, L3_SIZE);
6134 * Create an L2 table to map all addresses within an L1 mapping.
6137 pmap_demote_l1(pmap_t pmap, pt_entry_t *l1, vm_offset_t va)
6139 pt_entry_t *l2, newl2, oldl1;
6141 vm_paddr_t l2phys, phys;
6145 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6146 oldl1 = pmap_load(l1);
6147 KASSERT((oldl1 & ATTR_DESCR_MASK) == L1_BLOCK,
6148 ("pmap_demote_l1: Demoting a non-block entry"));
6149 KASSERT((va & L1_OFFSET) == 0,
6150 ("pmap_demote_l1: Invalid virtual address %#lx", va));
6151 KASSERT((oldl1 & ATTR_SW_MANAGED) == 0,
6152 ("pmap_demote_l1: Level 1 table shouldn't be managed"));
6155 if (va <= (vm_offset_t)l1 && va + L1_SIZE > (vm_offset_t)l1) {
6156 tmpl1 = kva_alloc(PAGE_SIZE);
6161 if ((ml2 = vm_page_alloc(NULL, 0, VM_ALLOC_INTERRUPT |
6162 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6163 CTR2(KTR_PMAP, "pmap_demote_l1: failure for va %#lx"
6164 " in pmap %p", va, pmap);
6168 l2phys = VM_PAGE_TO_PHYS(ml2);
6169 l2 = (pt_entry_t *)PHYS_TO_DMAP(l2phys);
6171 /* Address the range points at */
6172 phys = oldl1 & ~ATTR_MASK;
6173 /* The attributed from the old l1 table to be copied */
6174 newl2 = oldl1 & ATTR_MASK;
6176 /* Create the new entries */
6177 for (i = 0; i < Ln_ENTRIES; i++) {
6178 l2[i] = newl2 | phys;
6181 KASSERT(l2[0] == ((oldl1 & ~ATTR_DESCR_MASK) | L2_BLOCK),
6182 ("Invalid l2 page (%lx != %lx)", l2[0],
6183 (oldl1 & ~ATTR_DESCR_MASK) | L2_BLOCK));
6186 pmap_kenter(tmpl1, PAGE_SIZE,
6187 DMAP_TO_PHYS((vm_offset_t)l1) & ~L3_OFFSET,
6188 VM_MEMATTR_WRITE_BACK);
6189 l1 = (pt_entry_t *)(tmpl1 + ((vm_offset_t)l1 & PAGE_MASK));
6192 pmap_update_entry(pmap, l1, l2phys | L1_TABLE, va, PAGE_SIZE);
6195 pmap_kremove(tmpl1);
6196 kva_free(tmpl1, PAGE_SIZE);
6203 pmap_fill_l3(pt_entry_t *firstl3, pt_entry_t newl3)
6207 for (l3 = firstl3; l3 - firstl3 < Ln_ENTRIES; l3++) {
6214 pmap_demote_l2_abort(pmap_t pmap, vm_offset_t va, pt_entry_t *l2,
6215 struct rwlock **lockp)
6217 struct spglist free;
6220 (void)pmap_remove_l2(pmap, l2, va, pmap_load(pmap_l1(pmap, va)), &free,
6222 vm_page_free_pages_toq(&free, true);
6226 * Create an L3 table to map all addresses within an L2 mapping.
6229 pmap_demote_l2_locked(pmap_t pmap, pt_entry_t *l2, vm_offset_t va,
6230 struct rwlock **lockp)
6232 pt_entry_t *l3, newl3, oldl2;
6237 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6238 PMAP_ASSERT_STAGE1(pmap);
6240 oldl2 = pmap_load(l2);
6241 KASSERT((oldl2 & ATTR_DESCR_MASK) == L2_BLOCK,
6242 ("pmap_demote_l2: Demoting a non-block entry"));
6246 if (va <= (vm_offset_t)l2 && va + L2_SIZE > (vm_offset_t)l2) {
6247 tmpl2 = kva_alloc(PAGE_SIZE);
6253 * Invalidate the 2MB page mapping and return "failure" if the
6254 * mapping was never accessed.
6256 if ((oldl2 & ATTR_AF) == 0) {
6257 KASSERT((oldl2 & ATTR_SW_WIRED) == 0,
6258 ("pmap_demote_l2: a wired mapping is missing ATTR_AF"));
6259 pmap_demote_l2_abort(pmap, va, l2, lockp);
6260 CTR2(KTR_PMAP, "pmap_demote_l2: failure for va %#lx in pmap %p",
6265 if ((ml3 = pmap_remove_pt_page(pmap, va)) == NULL) {
6266 KASSERT((oldl2 & ATTR_SW_WIRED) == 0,
6267 ("pmap_demote_l2: page table page for a wired mapping"
6271 * If the page table page is missing and the mapping
6272 * is for a kernel address, the mapping must belong to
6273 * the direct map. Page table pages are preallocated
6274 * for every other part of the kernel address space,
6275 * so the direct map region is the only part of the
6276 * kernel address space that must be handled here.
6278 KASSERT(va < VM_MAXUSER_ADDRESS || VIRT_IN_DMAP(va),
6279 ("pmap_demote_l2: No saved mpte for va %#lx", va));
6282 * If the 2MB page mapping belongs to the direct map
6283 * region of the kernel's address space, then the page
6284 * allocation request specifies the highest possible
6285 * priority (VM_ALLOC_INTERRUPT). Otherwise, the
6286 * priority is normal.
6288 ml3 = vm_page_alloc(NULL, pmap_l2_pindex(va),
6289 (VIRT_IN_DMAP(va) ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
6290 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED);
6293 * If the allocation of the new page table page fails,
6294 * invalidate the 2MB page mapping and return "failure".
6297 pmap_demote_l2_abort(pmap, va, l2, lockp);
6298 CTR2(KTR_PMAP, "pmap_demote_l2: failure for va %#lx"
6299 " in pmap %p", va, pmap);
6303 if (va < VM_MAXUSER_ADDRESS) {
6304 ml3->ref_count = NL3PG;
6305 pmap_resident_count_inc(pmap, 1);
6308 l3phys = VM_PAGE_TO_PHYS(ml3);
6309 l3 = (pt_entry_t *)PHYS_TO_DMAP(l3phys);
6310 newl3 = (oldl2 & ~ATTR_DESCR_MASK) | L3_PAGE;
6311 KASSERT((oldl2 & (ATTR_S1_AP_RW_BIT | ATTR_SW_DBM)) !=
6312 (ATTR_S1_AP(ATTR_S1_AP_RO) | ATTR_SW_DBM),
6313 ("pmap_demote_l2: L2 entry is writeable but not dirty"));
6316 * If the page table page is not leftover from an earlier promotion,
6317 * or the mapping attributes have changed, (re)initialize the L3 table.
6319 * When pmap_update_entry() clears the old L2 mapping, it (indirectly)
6320 * performs a dsb(). That dsb() ensures that the stores for filling
6321 * "l3" are visible before "l3" is added to the page table.
6323 if (ml3->valid == 0 || (l3[0] & ATTR_MASK) != (newl3 & ATTR_MASK))
6324 pmap_fill_l3(l3, newl3);
6327 * Map the temporary page so we don't lose access to the l2 table.
6330 pmap_kenter(tmpl2, PAGE_SIZE,
6331 DMAP_TO_PHYS((vm_offset_t)l2) & ~L3_OFFSET,
6332 VM_MEMATTR_WRITE_BACK);
6333 l2 = (pt_entry_t *)(tmpl2 + ((vm_offset_t)l2 & PAGE_MASK));
6337 * The spare PV entries must be reserved prior to demoting the
6338 * mapping, that is, prior to changing the PDE. Otherwise, the state
6339 * of the L2 and the PV lists will be inconsistent, which can result
6340 * in reclaim_pv_chunk() attempting to remove a PV entry from the
6341 * wrong PV list and pmap_pv_demote_l2() failing to find the expected
6342 * PV entry for the 2MB page mapping that is being demoted.
6344 if ((oldl2 & ATTR_SW_MANAGED) != 0)
6345 reserve_pv_entries(pmap, Ln_ENTRIES - 1, lockp);
6348 * Pass PAGE_SIZE so that a single TLB invalidation is performed on
6349 * the 2MB page mapping.
6351 pmap_update_entry(pmap, l2, l3phys | L2_TABLE, va, PAGE_SIZE);
6354 * Demote the PV entry.
6356 if ((oldl2 & ATTR_SW_MANAGED) != 0)
6357 pmap_pv_demote_l2(pmap, va, oldl2 & ~ATTR_MASK, lockp);
6359 atomic_add_long(&pmap_l2_demotions, 1);
6360 CTR3(KTR_PMAP, "pmap_demote_l2: success for va %#lx"
6361 " in pmap %p %lx", va, pmap, l3[0]);
6365 pmap_kremove(tmpl2);
6366 kva_free(tmpl2, PAGE_SIZE);
6374 pmap_demote_l2(pmap_t pmap, pt_entry_t *l2, vm_offset_t va)
6376 struct rwlock *lock;
6380 l3 = pmap_demote_l2_locked(pmap, l2, va, &lock);
6387 * Perform the pmap work for mincore(2). If the page is not both referenced and
6388 * modified by this pmap, returns its physical address so that the caller can
6389 * find other mappings.
6392 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
6394 pt_entry_t *pte, tpte;
6395 vm_paddr_t mask, pa;
6399 PMAP_ASSERT_STAGE1(pmap);
6401 pte = pmap_pte(pmap, addr, &lvl);
6403 tpte = pmap_load(pte);
6416 panic("pmap_mincore: invalid level %d", lvl);
6419 managed = (tpte & ATTR_SW_MANAGED) != 0;
6420 val = MINCORE_INCORE;
6422 val |= MINCORE_PSIND(3 - lvl);
6423 if ((managed && pmap_pte_dirty(pmap, tpte)) || (!managed &&
6424 (tpte & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP(ATTR_S1_AP_RW)))
6425 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
6426 if ((tpte & ATTR_AF) == ATTR_AF)
6427 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
6429 pa = (tpte & ~ATTR_MASK) | (addr & mask);
6435 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
6436 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) && managed) {
6444 * Garbage collect every ASID that is neither active on a processor nor
6448 pmap_reset_asid_set(pmap_t pmap)
6451 int asid, cpuid, epoch;
6452 struct asid_set *set;
6453 enum pmap_stage stage;
6455 set = pmap->pm_asid_set;
6456 stage = pmap->pm_stage;
6458 set = pmap->pm_asid_set;
6459 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
6460 mtx_assert(&set->asid_set_mutex, MA_OWNED);
6463 * Ensure that the store to asid_epoch is globally visible before the
6464 * loads from pc_curpmap are performed.
6466 epoch = set->asid_epoch + 1;
6467 if (epoch == INT_MAX)
6469 set->asid_epoch = epoch;
6471 if (stage == PM_STAGE1) {
6472 __asm __volatile("tlbi vmalle1is");
6474 KASSERT(pmap_clean_stage2_tlbi != NULL,
6475 ("%s: Unset stage 2 tlb invalidation callback\n",
6477 pmap_clean_stage2_tlbi();
6480 bit_nclear(set->asid_set, ASID_FIRST_AVAILABLE,
6481 set->asid_set_size - 1);
6482 CPU_FOREACH(cpuid) {
6483 if (cpuid == curcpu)
6485 if (stage == PM_STAGE1) {
6486 curpmap = pcpu_find(cpuid)->pc_curpmap;
6487 PMAP_ASSERT_STAGE1(pmap);
6489 curpmap = pcpu_find(cpuid)->pc_curvmpmap;
6490 if (curpmap == NULL)
6492 PMAP_ASSERT_STAGE2(pmap);
6494 KASSERT(curpmap->pm_asid_set == set, ("Incorrect set"));
6495 asid = COOKIE_TO_ASID(curpmap->pm_cookie);
6498 bit_set(set->asid_set, asid);
6499 curpmap->pm_cookie = COOKIE_FROM(asid, epoch);
6504 * Allocate a new ASID for the specified pmap.
6507 pmap_alloc_asid(pmap_t pmap)
6509 struct asid_set *set;
6512 set = pmap->pm_asid_set;
6513 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
6515 mtx_lock_spin(&set->asid_set_mutex);
6518 * While this processor was waiting to acquire the asid set mutex,
6519 * pmap_reset_asid_set() running on another processor might have
6520 * updated this pmap's cookie to the current epoch. In which case, we
6521 * don't need to allocate a new ASID.
6523 if (COOKIE_TO_EPOCH(pmap->pm_cookie) == set->asid_epoch)
6526 bit_ffc_at(set->asid_set, set->asid_next, set->asid_set_size,
6528 if (new_asid == -1) {
6529 bit_ffc_at(set->asid_set, ASID_FIRST_AVAILABLE,
6530 set->asid_next, &new_asid);
6531 if (new_asid == -1) {
6532 pmap_reset_asid_set(pmap);
6533 bit_ffc_at(set->asid_set, ASID_FIRST_AVAILABLE,
6534 set->asid_set_size, &new_asid);
6535 KASSERT(new_asid != -1, ("ASID allocation failure"));
6538 bit_set(set->asid_set, new_asid);
6539 set->asid_next = new_asid + 1;
6540 pmap->pm_cookie = COOKIE_FROM(new_asid, set->asid_epoch);
6542 mtx_unlock_spin(&set->asid_set_mutex);
6546 * Compute the value that should be stored in ttbr0 to activate the specified
6547 * pmap. This value may change from time to time.
6550 pmap_to_ttbr0(pmap_t pmap)
6553 return (ASID_TO_OPERAND(COOKIE_TO_ASID(pmap->pm_cookie)) |
6558 pmap_activate_int(pmap_t pmap)
6560 struct asid_set *set;
6563 KASSERT(PCPU_GET(curpmap) != NULL, ("no active pmap"));
6564 KASSERT(pmap != kernel_pmap, ("kernel pmap activation"));
6566 if ((pmap->pm_stage == PM_STAGE1 && pmap == PCPU_GET(curpmap)) ||
6567 (pmap->pm_stage == PM_STAGE2 && pmap == PCPU_GET(curvmpmap))) {
6569 * Handle the possibility that the old thread was preempted
6570 * after an "ic" or "tlbi" instruction but before it performed
6571 * a "dsb" instruction. If the old thread migrates to a new
6572 * processor, its completion of a "dsb" instruction on that
6573 * new processor does not guarantee that the "ic" or "tlbi"
6574 * instructions performed on the old processor have completed.
6580 set = pmap->pm_asid_set;
6581 KASSERT(set != NULL, ("%s: NULL asid set", __func__));
6584 * Ensure that the store to curpmap is globally visible before the
6585 * load from asid_epoch is performed.
6587 if (pmap->pm_stage == PM_STAGE1)
6588 PCPU_SET(curpmap, pmap);
6590 PCPU_SET(curvmpmap, pmap);
6592 epoch = COOKIE_TO_EPOCH(pmap->pm_cookie);
6593 if (epoch >= 0 && epoch != set->asid_epoch)
6594 pmap_alloc_asid(pmap);
6596 if (pmap->pm_stage == PM_STAGE1) {
6597 set_ttbr0(pmap_to_ttbr0(pmap));
6598 if (PCPU_GET(bcast_tlbi_workaround) != 0)
6599 invalidate_local_icache();
6605 pmap_activate_vm(pmap_t pmap)
6608 PMAP_ASSERT_STAGE2(pmap);
6610 (void)pmap_activate_int(pmap);
6614 pmap_activate(struct thread *td)
6618 pmap = vmspace_pmap(td->td_proc->p_vmspace);
6619 PMAP_ASSERT_STAGE1(pmap);
6621 (void)pmap_activate_int(pmap);
6626 * To eliminate the unused parameter "old", we would have to add an instruction
6630 pmap_switch(struct thread *old __unused, struct thread *new)
6632 pcpu_bp_harden bp_harden;
6635 /* Store the new curthread */
6636 PCPU_SET(curthread, new);
6638 /* And the new pcb */
6640 PCPU_SET(curpcb, pcb);
6643 * TODO: We may need to flush the cache here if switching
6644 * to a user process.
6647 if (pmap_activate_int(vmspace_pmap(new->td_proc->p_vmspace))) {
6649 * Stop userspace from training the branch predictor against
6650 * other processes. This will call into a CPU specific
6651 * function that clears the branch predictor state.
6653 bp_harden = PCPU_GET(bp_harden);
6654 if (bp_harden != NULL)
6662 pmap_sync_icache(pmap_t pmap, vm_offset_t va, vm_size_t sz)
6665 PMAP_ASSERT_STAGE1(pmap);
6666 if (va >= VM_MIN_KERNEL_ADDRESS) {
6667 cpu_icache_sync_range(va, sz);
6672 /* Find the length of data in this page to flush */
6673 offset = va & PAGE_MASK;
6674 len = imin(PAGE_SIZE - offset, sz);
6677 /* Extract the physical address & find it in the DMAP */
6678 pa = pmap_extract(pmap, va);
6680 cpu_icache_sync_range(PHYS_TO_DMAP(pa), len);
6682 /* Move to the next page */
6685 /* Set the length for the next iteration */
6686 len = imin(PAGE_SIZE, sz);
6692 pmap_stage2_fault(pmap_t pmap, uint64_t esr, uint64_t far)
6695 pt_entry_t *ptep, pte;
6698 PMAP_ASSERT_STAGE2(pmap);
6701 /* Data and insn aborts use same encoding for FSC field. */
6702 dfsc = esr & ISS_DATA_DFSC_MASK;
6704 case ISS_DATA_DFSC_TF_L0:
6705 case ISS_DATA_DFSC_TF_L1:
6706 case ISS_DATA_DFSC_TF_L2:
6707 case ISS_DATA_DFSC_TF_L3:
6709 pdep = pmap_pde(pmap, far, &lvl);
6710 if (pdep == NULL || lvl != (dfsc - ISS_DATA_DFSC_TF_L1)) {
6717 ptep = pmap_l0_to_l1(pdep, far);
6720 ptep = pmap_l1_to_l2(pdep, far);
6723 ptep = pmap_l2_to_l3(pdep, far);
6726 panic("%s: Invalid pde level %d", __func__,lvl);
6730 case ISS_DATA_DFSC_AFF_L1:
6731 case ISS_DATA_DFSC_AFF_L2:
6732 case ISS_DATA_DFSC_AFF_L3:
6734 ptep = pmap_pte(pmap, far, &lvl);
6736 if (ptep != NULL && (pte = pmap_load(ptep)) != 0) {
6738 pmap_invalidate_vpipt_icache();
6741 * If accessing an executable page invalidate
6742 * the I-cache so it will be valid when we
6743 * continue execution in the guest. The D-cache
6744 * is assumed to already be clean to the Point
6747 if ((pte & ATTR_S2_XN_MASK) !=
6748 ATTR_S2_XN(ATTR_S2_XN_NONE)) {
6749 invalidate_icache();
6752 pmap_set_bits(ptep, ATTR_AF | ATTR_DESCR_VALID);
6763 pmap_fault(pmap_t pmap, uint64_t esr, uint64_t far)
6765 pt_entry_t pte, *ptep;
6772 ec = ESR_ELx_EXCEPTION(esr);
6774 case EXCP_INSN_ABORT_L:
6775 case EXCP_INSN_ABORT:
6776 case EXCP_DATA_ABORT_L:
6777 case EXCP_DATA_ABORT:
6783 if (pmap->pm_stage == PM_STAGE2)
6784 return (pmap_stage2_fault(pmap, esr, far));
6786 /* Data and insn aborts use same encoding for FSC field. */
6787 switch (esr & ISS_DATA_DFSC_MASK) {
6788 case ISS_DATA_DFSC_AFF_L1:
6789 case ISS_DATA_DFSC_AFF_L2:
6790 case ISS_DATA_DFSC_AFF_L3:
6792 ptep = pmap_pte(pmap, far, &lvl);
6794 pmap_set_bits(ptep, ATTR_AF);
6797 * XXXMJ as an optimization we could mark the entry
6798 * dirty if this is a write fault.
6803 case ISS_DATA_DFSC_PF_L1:
6804 case ISS_DATA_DFSC_PF_L2:
6805 case ISS_DATA_DFSC_PF_L3:
6806 if ((ec != EXCP_DATA_ABORT_L && ec != EXCP_DATA_ABORT) ||
6807 (esr & ISS_DATA_WnR) == 0)
6810 ptep = pmap_pte(pmap, far, &lvl);
6812 ((pte = pmap_load(ptep)) & ATTR_SW_DBM) != 0) {
6813 if ((pte & ATTR_S1_AP_RW_BIT) ==
6814 ATTR_S1_AP(ATTR_S1_AP_RO)) {
6815 pmap_clear_bits(ptep, ATTR_S1_AP_RW_BIT);
6816 pmap_invalidate_page(pmap, far);
6822 case ISS_DATA_DFSC_TF_L0:
6823 case ISS_DATA_DFSC_TF_L1:
6824 case ISS_DATA_DFSC_TF_L2:
6825 case ISS_DATA_DFSC_TF_L3:
6827 * Retry the translation. A break-before-make sequence can
6828 * produce a transient fault.
6830 if (pmap == kernel_pmap) {
6832 * The translation fault may have occurred within a
6833 * critical section. Therefore, we must check the
6834 * address without acquiring the kernel pmap's lock.
6836 if (pmap_kextract(far) != 0)
6840 /* Ask the MMU to check the address. */
6841 intr = intr_disable();
6842 par = arm64_address_translate_s1e0r(far);
6847 * If the translation was successful, then we can
6848 * return success to the trap handler.
6850 if (PAR_SUCCESS(par))
6860 * Increase the starting virtual address of the given mapping if a
6861 * different alignment might result in more superpage mappings.
6864 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
6865 vm_offset_t *addr, vm_size_t size)
6867 vm_offset_t superpage_offset;
6871 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
6872 offset += ptoa(object->pg_color);
6873 superpage_offset = offset & L2_OFFSET;
6874 if (size - ((L2_SIZE - superpage_offset) & L2_OFFSET) < L2_SIZE ||
6875 (*addr & L2_OFFSET) == superpage_offset)
6877 if ((*addr & L2_OFFSET) < superpage_offset)
6878 *addr = (*addr & ~L2_OFFSET) + superpage_offset;
6880 *addr = ((*addr + L2_OFFSET) & ~L2_OFFSET) + superpage_offset;
6884 * Get the kernel virtual address of a set of physical pages. If there are
6885 * physical addresses not covered by the DMAP perform a transient mapping
6886 * that will be removed when calling pmap_unmap_io_transient.
6888 * \param page The pages the caller wishes to obtain the virtual
6889 * address on the kernel memory map.
6890 * \param vaddr On return contains the kernel virtual memory address
6891 * of the pages passed in the page parameter.
6892 * \param count Number of pages passed in.
6893 * \param can_fault TRUE if the thread using the mapped pages can take
6894 * page faults, FALSE otherwise.
6896 * \returns TRUE if the caller must call pmap_unmap_io_transient when
6897 * finished or FALSE otherwise.
6901 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
6902 boolean_t can_fault)
6905 boolean_t needs_mapping;
6909 * Allocate any KVA space that we need, this is done in a separate
6910 * loop to prevent calling vmem_alloc while pinned.
6912 needs_mapping = FALSE;
6913 for (i = 0; i < count; i++) {
6914 paddr = VM_PAGE_TO_PHYS(page[i]);
6915 if (__predict_false(!PHYS_IN_DMAP(paddr))) {
6916 error = vmem_alloc(kernel_arena, PAGE_SIZE,
6917 M_BESTFIT | M_WAITOK, &vaddr[i]);
6918 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
6919 needs_mapping = TRUE;
6921 vaddr[i] = PHYS_TO_DMAP(paddr);
6925 /* Exit early if everything is covered by the DMAP */
6931 for (i = 0; i < count; i++) {
6932 paddr = VM_PAGE_TO_PHYS(page[i]);
6933 if (!PHYS_IN_DMAP(paddr)) {
6935 "pmap_map_io_transient: TODO: Map out of DMAP data");
6939 return (needs_mapping);
6943 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
6944 boolean_t can_fault)
6951 for (i = 0; i < count; i++) {
6952 paddr = VM_PAGE_TO_PHYS(page[i]);
6953 if (!PHYS_IN_DMAP(paddr)) {
6954 panic("ARM64TODO: pmap_unmap_io_transient: Unmap data");
6960 pmap_is_valid_memattr(pmap_t pmap __unused, vm_memattr_t mode)
6963 return (mode >= VM_MEMATTR_DEVICE && mode <= VM_MEMATTR_WRITE_THROUGH);
6967 * Track a range of the kernel's virtual address space that is contiguous
6968 * in various mapping attributes.
6970 struct pmap_kernel_map_range {
6980 sysctl_kmaps_dump(struct sbuf *sb, struct pmap_kernel_map_range *range,
6986 if (eva <= range->sva)
6989 index = range->attrs & ATTR_S1_IDX_MASK;
6991 case ATTR_S1_IDX(VM_MEMATTR_DEVICE):
6994 case ATTR_S1_IDX(VM_MEMATTR_UNCACHEABLE):
6997 case ATTR_S1_IDX(VM_MEMATTR_WRITE_BACK):
7000 case ATTR_S1_IDX(VM_MEMATTR_WRITE_THROUGH):
7005 "%s: unknown memory type %x for range 0x%016lx-0x%016lx\n",
7006 __func__, index, range->sva, eva);
7011 sbuf_printf(sb, "0x%016lx-0x%016lx r%c%c%c %3s %d %d %d %d\n",
7013 (range->attrs & ATTR_S1_AP_RW_BIT) == ATTR_S1_AP_RW ? 'w' : '-',
7014 (range->attrs & ATTR_S1_PXN) != 0 ? '-' : 'x',
7015 (range->attrs & ATTR_S1_AP_USER) != 0 ? 'u' : 's',
7016 mode, range->l1blocks, range->l2blocks, range->l3contig,
7019 /* Reset to sentinel value. */
7020 range->sva = 0xfffffffffffffffful;
7024 * Determine whether the attributes specified by a page table entry match those
7025 * being tracked by the current range.
7028 sysctl_kmaps_match(struct pmap_kernel_map_range *range, pt_entry_t attrs)
7031 return (range->attrs == attrs);
7035 sysctl_kmaps_reinit(struct pmap_kernel_map_range *range, vm_offset_t va,
7039 memset(range, 0, sizeof(*range));
7041 range->attrs = attrs;
7045 * Given a leaf PTE, derive the mapping's attributes. If they do not match
7046 * those of the current run, dump the address range and its attributes, and
7050 sysctl_kmaps_check(struct sbuf *sb, struct pmap_kernel_map_range *range,
7051 vm_offset_t va, pd_entry_t l0e, pd_entry_t l1e, pd_entry_t l2e,
7056 attrs = l0e & (ATTR_S1_AP_MASK | ATTR_S1_XN);
7057 attrs |= l1e & (ATTR_S1_AP_MASK | ATTR_S1_XN);
7058 if ((l1e & ATTR_DESCR_MASK) == L1_BLOCK)
7059 attrs |= l1e & ATTR_S1_IDX_MASK;
7060 attrs |= l2e & (ATTR_S1_AP_MASK | ATTR_S1_XN);
7061 if ((l2e & ATTR_DESCR_MASK) == L2_BLOCK)
7062 attrs |= l2e & ATTR_S1_IDX_MASK;
7063 attrs |= l3e & (ATTR_S1_AP_MASK | ATTR_S1_XN | ATTR_S1_IDX_MASK);
7065 if (range->sva > va || !sysctl_kmaps_match(range, attrs)) {
7066 sysctl_kmaps_dump(sb, range, va);
7067 sysctl_kmaps_reinit(range, va, attrs);
7072 sysctl_kmaps(SYSCTL_HANDLER_ARGS)
7074 struct pmap_kernel_map_range range;
7075 struct sbuf sbuf, *sb;
7076 pd_entry_t l0e, *l1, l1e, *l2, l2e;
7077 pt_entry_t *l3, l3e;
7080 int error, i, j, k, l;
7082 error = sysctl_wire_old_buffer(req, 0);
7086 sbuf_new_for_sysctl(sb, NULL, PAGE_SIZE, req);
7088 /* Sentinel value. */
7089 range.sva = 0xfffffffffffffffful;
7092 * Iterate over the kernel page tables without holding the kernel pmap
7093 * lock. Kernel page table pages are never freed, so at worst we will
7094 * observe inconsistencies in the output.
7096 for (sva = 0xffff000000000000ul, i = pmap_l0_index(sva); i < Ln_ENTRIES;
7098 if (i == pmap_l0_index(DMAP_MIN_ADDRESS))
7099 sbuf_printf(sb, "\nDirect map:\n");
7100 else if (i == pmap_l0_index(VM_MIN_KERNEL_ADDRESS))
7101 sbuf_printf(sb, "\nKernel map:\n");
7103 l0e = kernel_pmap->pm_l0[i];
7104 if ((l0e & ATTR_DESCR_VALID) == 0) {
7105 sysctl_kmaps_dump(sb, &range, sva);
7109 pa = l0e & ~ATTR_MASK;
7110 l1 = (pd_entry_t *)PHYS_TO_DMAP(pa);
7112 for (j = pmap_l1_index(sva); j < Ln_ENTRIES; j++) {
7114 if ((l1e & ATTR_DESCR_VALID) == 0) {
7115 sysctl_kmaps_dump(sb, &range, sva);
7119 if ((l1e & ATTR_DESCR_MASK) == L1_BLOCK) {
7120 sysctl_kmaps_check(sb, &range, sva, l0e, l1e,
7126 pa = l1e & ~ATTR_MASK;
7127 l2 = (pd_entry_t *)PHYS_TO_DMAP(pa);
7129 for (k = pmap_l2_index(sva); k < Ln_ENTRIES; k++) {
7131 if ((l2e & ATTR_DESCR_VALID) == 0) {
7132 sysctl_kmaps_dump(sb, &range, sva);
7136 if ((l2e & ATTR_DESCR_MASK) == L2_BLOCK) {
7137 sysctl_kmaps_check(sb, &range, sva,
7143 pa = l2e & ~ATTR_MASK;
7144 l3 = (pt_entry_t *)PHYS_TO_DMAP(pa);
7146 for (l = pmap_l3_index(sva); l < Ln_ENTRIES;
7147 l++, sva += L3_SIZE) {
7149 if ((l3e & ATTR_DESCR_VALID) == 0) {
7150 sysctl_kmaps_dump(sb, &range,
7154 sysctl_kmaps_check(sb, &range, sva,
7155 l0e, l1e, l2e, l3e);
7156 if ((l3e & ATTR_CONTIGUOUS) != 0)
7157 range.l3contig += l % 16 == 0 ?
7166 error = sbuf_finish(sb);
7170 SYSCTL_OID(_vm_pmap, OID_AUTO, kernel_maps,
7171 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
7172 NULL, 0, sysctl_kmaps, "A",
7173 "Dump kernel address layout");