1 /*-
2 * SPDX-License-Identifier: BSD-4-Clause
3 *
4 * Copyright (c) 1991 Regents of the University of California.
5 * All rights reserved.
6 * Copyright (c) 1994 John S. Dyson
7 * All rights reserved.
8 * Copyright (c) 1994 David Greenman
9 * All rights reserved.
10 * Copyright (c) 2003 Peter Wemm
11 * All rights reserved.
12 * Copyright (c) 2005-2010 Alan L. Cox <alc@cs.rice.edu>
13 * All rights reserved.
14 *
15 * This code is derived from software contributed to Berkeley by
16 * the Systems Programming Group of the University of Utah Computer
17 * Science Department and William Jolitz of UUNET Technologies Inc.
18 *
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
21 * are met:
22 * 1. Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
24 * 2. Redistributions in binary form must reproduce the above copyright
25 * notice, this list of conditions and the following disclaimer in the
26 * documentation and/or other materials provided with the distribution.
27 * 3. All advertising materials mentioning features or use of this software
28 * must display the following acknowledgement:
29 * This product includes software developed by the University of
30 * California, Berkeley and its contributors.
31 * 4. Neither the name of the University nor the names of its contributors
32 * may be used to endorse or promote products derived from this software
33 * without specific prior written permission.
34 *
35 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
36 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
39 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
40 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
41 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
42 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
43 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
44 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
45 * SUCH DAMAGE.
46 */
47 /*-
48 * Copyright (c) 2003 Networks Associates Technology, Inc.
49 * Copyright (c) 2014-2020 The FreeBSD Foundation
50 * All rights reserved.
51 *
52 * This software was developed for the FreeBSD Project by Jake Burkholder,
53 * Safeport Network Services, and Network Associates Laboratories, the
54 * Security Research Division of Network Associates, Inc. under
55 * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
56 * CHATS research program.
57 *
58 * Portions of this software were developed by
59 * Konstantin Belousov <kib@FreeBSD.org> under sponsorship from
60 * the FreeBSD Foundation.
61 *
62 * Redistribution and use in source and binary forms, with or without
63 * modification, are permitted provided that the following conditions
64 * are met:
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
67 * 2. Redistributions in binary form must reproduce the above copyright
68 * notice, this list of conditions and the following disclaimer in the
69 * documentation and/or other materials provided with the distribution.
70 *
71 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
72 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
73 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
74 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
75 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
76 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
77 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
78 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
79 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
80 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
81 * SUCH DAMAGE.
82 */
83
84 #define AMD64_NPT_AWARE
85
86 #include <sys/cdefs.h>
87 /*
88 * Manages physical address maps.
89 *
90 * Since the information managed by this module is
91 * also stored by the logical address mapping module,
92 * this module may throw away valid virtual-to-physical
93 * mappings at almost any time. However, invalidations
94 * of virtual-to-physical mappings must be done as
95 * requested.
96 *
97 * In order to cope with hardware architectures which
98 * make virtual-to-physical map invalidates expensive,
99 * this module may delay invalidate or reduced protection
100 * operations until such time as they are actually
101 * necessary. This module is given full information as
102 * to which processors are currently using which maps,
103 * and to when physical maps must be made correct.
104 */
105
106 #include "opt_ddb.h"
107 #include "opt_pmap.h"
108 #include "opt_vm.h"
109
110 #include <sys/param.h>
111 #include <sys/asan.h>
112 #include <sys/bitstring.h>
113 #include <sys/bus.h>
114 #include <sys/systm.h>
115 #include <sys/counter.h>
116 #include <sys/kernel.h>
117 #include <sys/ktr.h>
118 #include <sys/lock.h>
119 #include <sys/malloc.h>
120 #include <sys/mman.h>
121 #include <sys/msan.h>
122 #include <sys/mutex.h>
123 #include <sys/proc.h>
124 #include <sys/rangeset.h>
125 #include <sys/rwlock.h>
126 #include <sys/sbuf.h>
127 #include <sys/smr.h>
128 #include <sys/sx.h>
129 #include <sys/turnstile.h>
130 #include <sys/vmem.h>
131 #include <sys/vmmeter.h>
132 #include <sys/sched.h>
133 #include <sys/sysctl.h>
134 #include <sys/smp.h>
135 #ifdef DDB
136 #include <sys/kdb.h>
137 #include <ddb/ddb.h>
138 #endif
139
140 #include <vm/vm.h>
141 #include <vm/vm_param.h>
142 #include <vm/vm_kern.h>
143 #include <vm/vm_page.h>
144 #include <vm/vm_map.h>
145 #include <vm/vm_object.h>
146 #include <vm/vm_extern.h>
147 #include <vm/vm_pageout.h>
148 #include <vm/vm_pager.h>
149 #include <vm/vm_phys.h>
150 #include <vm/vm_radix.h>
151 #include <vm/vm_reserv.h>
152 #include <vm/vm_dumpset.h>
153 #include <vm/uma.h>
154
155 #include <machine/asan.h>
156 #include <machine/intr_machdep.h>
157 #include <x86/apicvar.h>
158 #include <x86/ifunc.h>
159 #include <machine/cpu.h>
160 #include <machine/cputypes.h>
161 #include <machine/md_var.h>
162 #include <machine/msan.h>
163 #include <machine/pcb.h>
164 #include <machine/specialreg.h>
165 #ifdef SMP
166 #include <machine/smp.h>
167 #endif
168 #include <machine/sysarch.h>
169 #include <machine/tss.h>
170
171 #ifdef NUMA
172 #define PMAP_MEMDOM MAXMEMDOM
173 #else
174 #define PMAP_MEMDOM 1
175 #endif
176
177 static __inline bool
pmap_type_guest(pmap_t pmap)178 pmap_type_guest(pmap_t pmap)
179 {
180
181 return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
182 }
183
184 static __inline bool
pmap_emulate_ad_bits(pmap_t pmap)185 pmap_emulate_ad_bits(pmap_t pmap)
186 {
187
188 return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
189 }
190
191 static __inline pt_entry_t
pmap_valid_bit(pmap_t pmap)192 pmap_valid_bit(pmap_t pmap)
193 {
194 pt_entry_t mask;
195
196 switch (pmap->pm_type) {
197 case PT_X86:
198 case PT_RVI:
199 mask = X86_PG_V;
200 break;
201 case PT_EPT:
202 if (pmap_emulate_ad_bits(pmap))
203 mask = EPT_PG_EMUL_V;
204 else
205 mask = EPT_PG_READ;
206 break;
207 default:
208 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
209 }
210
211 return (mask);
212 }
213
214 static __inline pt_entry_t
pmap_rw_bit(pmap_t pmap)215 pmap_rw_bit(pmap_t pmap)
216 {
217 pt_entry_t mask;
218
219 switch (pmap->pm_type) {
220 case PT_X86:
221 case PT_RVI:
222 mask = X86_PG_RW;
223 break;
224 case PT_EPT:
225 if (pmap_emulate_ad_bits(pmap))
226 mask = EPT_PG_EMUL_RW;
227 else
228 mask = EPT_PG_WRITE;
229 break;
230 default:
231 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
232 }
233
234 return (mask);
235 }
236
237 static pt_entry_t pg_g;
238
239 static __inline pt_entry_t
pmap_global_bit(pmap_t pmap)240 pmap_global_bit(pmap_t pmap)
241 {
242 pt_entry_t mask;
243
244 switch (pmap->pm_type) {
245 case PT_X86:
246 mask = pg_g;
247 break;
248 case PT_RVI:
249 case PT_EPT:
250 mask = 0;
251 break;
252 default:
253 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
254 }
255
256 return (mask);
257 }
258
259 static __inline pt_entry_t
pmap_accessed_bit(pmap_t pmap)260 pmap_accessed_bit(pmap_t pmap)
261 {
262 pt_entry_t mask;
263
264 switch (pmap->pm_type) {
265 case PT_X86:
266 case PT_RVI:
267 mask = X86_PG_A;
268 break;
269 case PT_EPT:
270 if (pmap_emulate_ad_bits(pmap))
271 mask = EPT_PG_READ;
272 else
273 mask = EPT_PG_A;
274 break;
275 default:
276 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
277 }
278
279 return (mask);
280 }
281
282 static __inline pt_entry_t
pmap_modified_bit(pmap_t pmap)283 pmap_modified_bit(pmap_t pmap)
284 {
285 pt_entry_t mask;
286
287 switch (pmap->pm_type) {
288 case PT_X86:
289 case PT_RVI:
290 mask = X86_PG_M;
291 break;
292 case PT_EPT:
293 if (pmap_emulate_ad_bits(pmap))
294 mask = EPT_PG_WRITE;
295 else
296 mask = EPT_PG_M;
297 break;
298 default:
299 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
300 }
301
302 return (mask);
303 }
304
305 static __inline pt_entry_t
pmap_pku_mask_bit(pmap_t pmap)306 pmap_pku_mask_bit(pmap_t pmap)
307 {
308
309 return (pmap->pm_type == PT_X86 ? X86_PG_PKU_MASK : 0);
310 }
311
312 static __inline bool
safe_to_clear_referenced(pmap_t pmap,pt_entry_t pte)313 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
314 {
315
316 if (!pmap_emulate_ad_bits(pmap))
317 return (true);
318
319 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
320
321 /*
322 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
323 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
324 * if the EPT_PG_WRITE bit is set.
325 */
326 if ((pte & EPT_PG_WRITE) != 0)
327 return (false);
328
329 /*
330 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
331 */
332 if ((pte & EPT_PG_EXECUTE) == 0 ||
333 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
334 return (true);
335 else
336 return (false);
337 }
338
339 #ifdef PV_STATS
340 #define PV_STAT(x) do { x ; } while (0)
341 #else
342 #define PV_STAT(x) do { } while (0)
343 #endif
344
345 #undef pa_index
346 #ifdef NUMA
347 #define pa_index(pa) ({ \
348 KASSERT((pa) <= vm_phys_segs[vm_phys_nsegs - 1].end, \
349 ("address %lx beyond the last segment", (pa))); \
350 (pa) >> PDRSHIFT; \
351 })
352 #define pa_to_pmdp(pa) (&pv_table[pa_index(pa)])
353 #define pa_to_pvh(pa) (&(pa_to_pmdp(pa)->pv_page))
354 #define PHYS_TO_PV_LIST_LOCK(pa) ({ \
355 struct rwlock *_lock; \
356 if (__predict_false((pa) > pmap_last_pa)) \
357 _lock = &pv_dummy_large.pv_lock; \
358 else \
359 _lock = &(pa_to_pmdp(pa)->pv_lock); \
360 _lock; \
361 })
362 #else
363 #define pa_index(pa) ((pa) >> PDRSHIFT)
364 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
365
366 #define NPV_LIST_LOCKS MAXCPU
367
368 #define PHYS_TO_PV_LIST_LOCK(pa) \
369 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
370 #endif
371
372 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
373 struct rwlock **_lockp = (lockp); \
374 struct rwlock *_new_lock; \
375 \
376 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
377 if (_new_lock != *_lockp) { \
378 if (*_lockp != NULL) \
379 rw_wunlock(*_lockp); \
380 *_lockp = _new_lock; \
381 rw_wlock(*_lockp); \
382 } \
383 } while (0)
384
385 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
386 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
387
388 #define RELEASE_PV_LIST_LOCK(lockp) do { \
389 struct rwlock **_lockp = (lockp); \
390 \
391 if (*_lockp != NULL) { \
392 rw_wunlock(*_lockp); \
393 *_lockp = NULL; \
394 } \
395 } while (0)
396
397 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
398 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
399
400 /*
401 * Statically allocate kernel pmap memory. However, memory for
402 * pm_pcids is obtained after the dynamic allocator is operational.
403 * Initialize it with a non-canonical pointer to catch early accesses
404 * regardless of the active mapping.
405 */
406 struct pmap kernel_pmap_store = {
407 .pm_pcidp = (void *)0xdeadbeefdeadbeef,
408 };
409
410 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
411 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
412
413 int nkpt;
414 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
415 "Number of kernel page table pages allocated on bootup");
416
417 static int ndmpdp;
418 vm_paddr_t dmaplimit;
419 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
420 pt_entry_t pg_nx;
421
422 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
423 "VM/pmap parameters");
424
425 static int __read_frequently pg_ps_enabled = 1;
426 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
427 &pg_ps_enabled, 0, "Are large page mappings enabled?");
428
429 int __read_frequently la57 = 0;
430 SYSCTL_INT(_vm_pmap, OID_AUTO, la57, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
431 &la57, 0,
432 "5-level paging for host is enabled");
433
434 static bool
pmap_is_la57(pmap_t pmap)435 pmap_is_la57(pmap_t pmap)
436 {
437 if (pmap->pm_type == PT_X86)
438 return (la57);
439 return (false); /* XXXKIB handle EPT */
440 }
441
442 #define PAT_INDEX_SIZE 8
443 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
444
445 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
446 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
447 static u_int64_t KPDPphys; /* phys addr of kernel level 3 */
448 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
449 u_int64_t KPML5phys; /* phys addr of kernel level 5,
450 if supported */
451
452 #ifdef KASAN
453 static uint64_t KASANPDPphys;
454 #endif
455 #ifdef KMSAN
456 static uint64_t KMSANSHADPDPphys;
457 static uint64_t KMSANORIGPDPphys;
458
459 /*
460 * To support systems with large amounts of memory, it is necessary to extend
461 * the maximum size of the direct map. This could eat into the space reserved
462 * for the shadow map.
463 */
464 _Static_assert(DMPML4I + NDMPML4E <= KMSANSHADPML4I, "direct map overflow");
465 #endif
466
467 static pml4_entry_t *kernel_pml4;
468 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
469 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
470 static int ndmpdpphys; /* number of DMPDPphys pages */
471
472 vm_paddr_t kernphys; /* phys addr of start of bootstrap data */
473 vm_paddr_t KERNend; /* and the end */
474
475 /*
476 * pmap_mapdev support pre initialization (i.e. console)
477 */
478 #define PMAP_PREINIT_MAPPING_COUNT 8
479 static struct pmap_preinit_mapping {
480 vm_paddr_t pa;
481 vm_offset_t va;
482 vm_size_t sz;
483 int mode;
484 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
485 static int pmap_initialized;
486
487 /*
488 * Data for the pv entry allocation mechanism.
489 * Updates to pv_invl_gen are protected by the pv list lock but reads are not.
490 */
491 #ifdef NUMA
492 static __inline int
pc_to_domain(struct pv_chunk * pc)493 pc_to_domain(struct pv_chunk *pc)
494 {
495
496 return (vm_phys_domain(DMAP_TO_PHYS((vm_offset_t)pc)));
497 }
498 #else
499 static __inline int
pc_to_domain(struct pv_chunk * pc __unused)500 pc_to_domain(struct pv_chunk *pc __unused)
501 {
502
503 return (0);
504 }
505 #endif
506
507 struct pv_chunks_list {
508 struct mtx pvc_lock;
509 TAILQ_HEAD(pch, pv_chunk) pvc_list;
510 int active_reclaims;
511 } __aligned(CACHE_LINE_SIZE);
512
513 struct pv_chunks_list __exclusive_cache_line pv_chunks[PMAP_MEMDOM];
514
515 #ifdef NUMA
516 struct pmap_large_md_page {
517 struct rwlock pv_lock;
518 struct md_page pv_page;
519 u_long pv_invl_gen;
520 };
521 __exclusive_cache_line static struct pmap_large_md_page pv_dummy_large;
522 #define pv_dummy pv_dummy_large.pv_page
523 __read_mostly static struct pmap_large_md_page *pv_table;
524 __read_mostly vm_paddr_t pmap_last_pa;
525 #else
526 static struct rwlock __exclusive_cache_line pv_list_locks[NPV_LIST_LOCKS];
527 static u_long pv_invl_gen[NPV_LIST_LOCKS];
528 static struct md_page *pv_table;
529 static struct md_page pv_dummy;
530 #endif
531
532 /*
533 * All those kernel PT submaps that BSD is so fond of
534 */
535 pt_entry_t *CMAP1 = NULL;
536 caddr_t CADDR1 = 0;
537 static vm_offset_t qframe = 0;
538 static struct mtx qframe_mtx;
539
540 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
541
542 static vmem_t *large_vmem;
543 static u_int lm_ents;
544 #define PMAP_ADDRESS_IN_LARGEMAP(va) ((va) >= LARGEMAP_MIN_ADDRESS && \
545 (va) < LARGEMAP_MIN_ADDRESS + NBPML4 * (u_long)lm_ents)
546
547 int pmap_pcid_enabled = 1;
548 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
549 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
550 int invpcid_works = 0;
551 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
552 "Is the invpcid instruction available ?");
553 int invlpgb_works;
554 SYSCTL_INT(_vm_pmap, OID_AUTO, invlpgb_works, CTLFLAG_RD, &invlpgb_works, 0,
555 "Is the invlpgb instruction available?");
556 int invlpgb_maxcnt;
557 int pmap_pcid_invlpg_workaround = 0;
558 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_invlpg_workaround,
559 CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
560 &pmap_pcid_invlpg_workaround, 0,
561 "Enable small core PCID/INVLPG workaround");
562 int pmap_pcid_invlpg_workaround_uena = 1;
563
564 int __read_frequently pti = 0;
565 SYSCTL_INT(_vm_pmap, OID_AUTO, pti, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
566 &pti, 0,
567 "Page Table Isolation enabled");
568 static vm_object_t pti_obj;
569 static pml4_entry_t *pti_pml4;
570 static vm_pindex_t pti_pg_idx;
571 static bool pti_finalized;
572
573 struct pmap_pkru_range {
574 struct rs_el pkru_rs_el;
575 u_int pkru_keyidx;
576 int pkru_flags;
577 };
578
579 static uma_zone_t pmap_pkru_ranges_zone;
580 static bool pmap_pkru_same(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
581 pt_entry_t *pte);
582 static pt_entry_t pmap_pkru_get(pmap_t pmap, vm_offset_t va);
583 static void pmap_pkru_on_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
584 static void *pkru_dup_range(void *ctx, void *data);
585 static void pkru_free_range(void *ctx, void *node);
586 static int pmap_pkru_copy(pmap_t dst_pmap, pmap_t src_pmap);
587 static int pmap_pkru_deassign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva);
588 static void pmap_pkru_deassign_all(pmap_t pmap);
589
590 static COUNTER_U64_DEFINE_EARLY(pcid_save_cnt);
591 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLFLAG_RD,
592 &pcid_save_cnt, "Count of saved TLB context on switch");
593
594 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
595 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
596 static struct mtx invl_gen_mtx;
597 /* Fake lock object to satisfy turnstiles interface. */
598 static struct lock_object invl_gen_ts = {
599 .lo_name = "invlts",
600 };
601 static struct pmap_invl_gen pmap_invl_gen_head = {
602 .gen = 1,
603 .next = NULL,
604 };
605 static u_long pmap_invl_gen = 1;
606 static int pmap_invl_waiters;
607 static struct callout pmap_invl_callout;
608 static bool pmap_invl_callout_inited;
609
610 #define PMAP_ASSERT_NOT_IN_DI() \
611 KASSERT(pmap_not_in_di(), ("DI already started"))
612
613 static bool
pmap_di_locked(void)614 pmap_di_locked(void)
615 {
616 int tun;
617
618 if ((cpu_feature2 & CPUID2_CX16) == 0)
619 return (true);
620 tun = 0;
621 TUNABLE_INT_FETCH("vm.pmap.di_locked", &tun);
622 return (tun != 0);
623 }
624
625 static int
sysctl_pmap_di_locked(SYSCTL_HANDLER_ARGS)626 sysctl_pmap_di_locked(SYSCTL_HANDLER_ARGS)
627 {
628 int locked;
629
630 locked = pmap_di_locked();
631 return (sysctl_handle_int(oidp, &locked, 0, req));
632 }
633 SYSCTL_PROC(_vm_pmap, OID_AUTO, di_locked, CTLTYPE_INT | CTLFLAG_RDTUN |
634 CTLFLAG_MPSAFE, 0, 0, sysctl_pmap_di_locked, "",
635 "Locked delayed invalidation");
636
637 static bool pmap_not_in_di_l(void);
638 static bool pmap_not_in_di_u(void);
639 DEFINE_IFUNC(, bool, pmap_not_in_di, (void))
640 {
641
642 return (pmap_di_locked() ? pmap_not_in_di_l : pmap_not_in_di_u);
643 }
644
645 static bool
pmap_not_in_di_l(void)646 pmap_not_in_di_l(void)
647 {
648 struct pmap_invl_gen *invl_gen;
649
650 invl_gen = &curthread->td_md.md_invl_gen;
651 return (invl_gen->gen == 0);
652 }
653
654 static void
pmap_thread_init_invl_gen_l(struct thread * td)655 pmap_thread_init_invl_gen_l(struct thread *td)
656 {
657 struct pmap_invl_gen *invl_gen;
658
659 invl_gen = &td->td_md.md_invl_gen;
660 invl_gen->gen = 0;
661 }
662
663 static void
pmap_delayed_invl_wait_block(u_long * m_gen,u_long * invl_gen)664 pmap_delayed_invl_wait_block(u_long *m_gen, u_long *invl_gen)
665 {
666 struct turnstile *ts;
667
668 ts = turnstile_trywait(&invl_gen_ts);
669 if (*m_gen > atomic_load_long(invl_gen))
670 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
671 else
672 turnstile_cancel(ts);
673 }
674
675 static void
pmap_delayed_invl_finish_unblock(u_long new_gen)676 pmap_delayed_invl_finish_unblock(u_long new_gen)
677 {
678 struct turnstile *ts;
679
680 turnstile_chain_lock(&invl_gen_ts);
681 ts = turnstile_lookup(&invl_gen_ts);
682 if (new_gen != 0)
683 pmap_invl_gen = new_gen;
684 if (ts != NULL) {
685 turnstile_broadcast(ts, TS_SHARED_QUEUE);
686 turnstile_unpend(ts);
687 }
688 turnstile_chain_unlock(&invl_gen_ts);
689 }
690
691 /*
692 * Start a new Delayed Invalidation (DI) block of code, executed by
693 * the current thread. Within a DI block, the current thread may
694 * destroy both the page table and PV list entries for a mapping and
695 * then release the corresponding PV list lock before ensuring that
696 * the mapping is flushed from the TLBs of any processors with the
697 * pmap active.
698 */
699 static void
pmap_delayed_invl_start_l(void)700 pmap_delayed_invl_start_l(void)
701 {
702 struct pmap_invl_gen *invl_gen;
703 u_long currgen;
704
705 invl_gen = &curthread->td_md.md_invl_gen;
706 PMAP_ASSERT_NOT_IN_DI();
707 mtx_lock(&invl_gen_mtx);
708 if (LIST_EMPTY(&pmap_invl_gen_tracker))
709 currgen = pmap_invl_gen;
710 else
711 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
712 invl_gen->gen = currgen + 1;
713 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
714 mtx_unlock(&invl_gen_mtx);
715 }
716
717 /*
718 * Finish the DI block, previously started by the current thread. All
719 * required TLB flushes for the pages marked by
720 * pmap_delayed_invl_page() must be finished before this function is
721 * called.
722 *
723 * This function works by bumping the global DI generation number to
724 * the generation number of the current thread's DI, unless there is a
725 * pending DI that started earlier. In the latter case, bumping the
726 * global DI generation number would incorrectly signal that the
727 * earlier DI had finished. Instead, this function bumps the earlier
728 * DI's generation number to match the generation number of the
729 * current thread's DI.
730 */
731 static void
pmap_delayed_invl_finish_l(void)732 pmap_delayed_invl_finish_l(void)
733 {
734 struct pmap_invl_gen *invl_gen, *next;
735
736 invl_gen = &curthread->td_md.md_invl_gen;
737 KASSERT(invl_gen->gen != 0, ("missed invl_start"));
738 mtx_lock(&invl_gen_mtx);
739 next = LIST_NEXT(invl_gen, link);
740 if (next == NULL)
741 pmap_delayed_invl_finish_unblock(invl_gen->gen);
742 else
743 next->gen = invl_gen->gen;
744 LIST_REMOVE(invl_gen, link);
745 mtx_unlock(&invl_gen_mtx);
746 invl_gen->gen = 0;
747 }
748
749 static bool
pmap_not_in_di_u(void)750 pmap_not_in_di_u(void)
751 {
752 struct pmap_invl_gen *invl_gen;
753
754 invl_gen = &curthread->td_md.md_invl_gen;
755 return (((uintptr_t)invl_gen->next & PMAP_INVL_GEN_NEXT_INVALID) != 0);
756 }
757
758 static void
pmap_thread_init_invl_gen_u(struct thread * td)759 pmap_thread_init_invl_gen_u(struct thread *td)
760 {
761 struct pmap_invl_gen *invl_gen;
762
763 invl_gen = &td->td_md.md_invl_gen;
764 invl_gen->gen = 0;
765 invl_gen->next = (void *)PMAP_INVL_GEN_NEXT_INVALID;
766 }
767
768 static bool
pmap_di_load_invl(struct pmap_invl_gen * ptr,struct pmap_invl_gen * out)769 pmap_di_load_invl(struct pmap_invl_gen *ptr, struct pmap_invl_gen *out)
770 {
771 uint64_t new_high, new_low, old_high, old_low;
772 char res;
773
774 old_low = new_low = 0;
775 old_high = new_high = (uintptr_t)0;
776
777 __asm volatile("lock;cmpxchg16b\t%1"
778 : "=@cce" (res), "+m" (*ptr), "+a" (old_low), "+d" (old_high)
779 : "b"(new_low), "c" (new_high)
780 : "memory", "cc");
781 if (res == 0) {
782 if ((old_high & PMAP_INVL_GEN_NEXT_INVALID) != 0)
783 return (false);
784 out->gen = old_low;
785 out->next = (void *)old_high;
786 } else {
787 out->gen = new_low;
788 out->next = (void *)new_high;
789 }
790 return (true);
791 }
792
793 static bool
pmap_di_store_invl(struct pmap_invl_gen * ptr,struct pmap_invl_gen * old_val,struct pmap_invl_gen * new_val)794 pmap_di_store_invl(struct pmap_invl_gen *ptr, struct pmap_invl_gen *old_val,
795 struct pmap_invl_gen *new_val)
796 {
797 uint64_t new_high, new_low, old_high, old_low;
798 char res;
799
800 new_low = new_val->gen;
801 new_high = (uintptr_t)new_val->next;
802 old_low = old_val->gen;
803 old_high = (uintptr_t)old_val->next;
804
805 __asm volatile("lock;cmpxchg16b\t%1"
806 : "=@cce" (res), "+m" (*ptr), "+a" (old_low), "+d" (old_high)
807 : "b"(new_low), "c" (new_high)
808 : "memory", "cc");
809 return (res);
810 }
811
812 static COUNTER_U64_DEFINE_EARLY(pv_page_count);
813 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_page_count, CTLFLAG_RD,
814 &pv_page_count, "Current number of allocated pv pages");
815
816 static COUNTER_U64_DEFINE_EARLY(user_pt_page_count);
817 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, user_pt_page_count, CTLFLAG_RD,
818 &user_pt_page_count,
819 "Current number of allocated page table pages for userspace");
820
821 static COUNTER_U64_DEFINE_EARLY(kernel_pt_page_count);
822 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, kernel_pt_page_count, CTLFLAG_RD,
823 &kernel_pt_page_count,
824 "Current number of allocated page table pages for the kernel");
825
826 #ifdef PV_STATS
827
828 static COUNTER_U64_DEFINE_EARLY(invl_start_restart);
829 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_start_restart,
830 CTLFLAG_RD, &invl_start_restart,
831 "Number of delayed TLB invalidation request restarts");
832
833 static COUNTER_U64_DEFINE_EARLY(invl_finish_restart);
834 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_finish_restart, CTLFLAG_RD,
835 &invl_finish_restart,
836 "Number of delayed TLB invalidation completion restarts");
837
838 static int invl_max_qlen;
839 SYSCTL_INT(_vm_pmap, OID_AUTO, invl_max_qlen, CTLFLAG_RD,
840 &invl_max_qlen, 0,
841 "Maximum delayed TLB invalidation request queue length");
842 #endif
843
844 #define di_delay locks_delay
845
846 static void
pmap_delayed_invl_start_u(void)847 pmap_delayed_invl_start_u(void)
848 {
849 struct pmap_invl_gen *invl_gen, *p, prev, new_prev;
850 struct thread *td;
851 struct lock_delay_arg lda;
852 uintptr_t prevl;
853 u_char pri;
854 #ifdef PV_STATS
855 int i, ii;
856 #endif
857
858 td = curthread;
859 invl_gen = &td->td_md.md_invl_gen;
860 PMAP_ASSERT_NOT_IN_DI();
861 lock_delay_arg_init(&lda, &di_delay);
862 invl_gen->saved_pri = 0;
863 pri = td->td_base_pri;
864 if (pri > PVM) {
865 thread_lock(td);
866 pri = td->td_base_pri;
867 if (pri > PVM) {
868 invl_gen->saved_pri = pri;
869 sched_prio(td, PVM);
870 }
871 thread_unlock(td);
872 }
873 again:
874 PV_STAT(i = 0);
875 for (p = &pmap_invl_gen_head;; p = prev.next) {
876 PV_STAT(i++);
877 prevl = (uintptr_t)atomic_load_ptr(&p->next);
878 if ((prevl & PMAP_INVL_GEN_NEXT_INVALID) != 0) {
879 PV_STAT(counter_u64_add(invl_start_restart, 1));
880 lock_delay(&lda);
881 goto again;
882 }
883 if (prevl == 0)
884 break;
885 prev.next = (void *)prevl;
886 }
887 #ifdef PV_STATS
888 if ((ii = invl_max_qlen) < i)
889 atomic_cmpset_int(&invl_max_qlen, ii, i);
890 #endif
891
892 if (!pmap_di_load_invl(p, &prev) || prev.next != NULL) {
893 PV_STAT(counter_u64_add(invl_start_restart, 1));
894 lock_delay(&lda);
895 goto again;
896 }
897
898 new_prev.gen = prev.gen;
899 new_prev.next = invl_gen;
900 invl_gen->gen = prev.gen + 1;
901
902 /* Formal fence between store to invl->gen and updating *p. */
903 atomic_thread_fence_rel();
904
905 /*
906 * After inserting an invl_gen element with invalid bit set,
907 * this thread blocks any other thread trying to enter the
908 * delayed invalidation block. Do not allow to remove us from
909 * the CPU, because it causes starvation for other threads.
910 */
911 critical_enter();
912
913 /*
914 * ABA for *p is not possible there, since p->gen can only
915 * increase. So if the *p thread finished its di, then
916 * started a new one and got inserted into the list at the
917 * same place, its gen will appear greater than the previously
918 * read gen.
919 */
920 if (!pmap_di_store_invl(p, &prev, &new_prev)) {
921 critical_exit();
922 PV_STAT(counter_u64_add(invl_start_restart, 1));
923 lock_delay(&lda);
924 goto again;
925 }
926
927 /*
928 * There we clear PMAP_INVL_GEN_NEXT_INVALID in
929 * invl_gen->next, allowing other threads to iterate past us.
930 * pmap_di_store_invl() provides fence between the generation
931 * write and the update of next.
932 */
933 invl_gen->next = NULL;
934 critical_exit();
935 }
936
937 static bool
pmap_delayed_invl_finish_u_crit(struct pmap_invl_gen * invl_gen,struct pmap_invl_gen * p)938 pmap_delayed_invl_finish_u_crit(struct pmap_invl_gen *invl_gen,
939 struct pmap_invl_gen *p)
940 {
941 struct pmap_invl_gen prev, new_prev;
942 u_long mygen;
943
944 /*
945 * Load invl_gen->gen after setting invl_gen->next
946 * PMAP_INVL_GEN_NEXT_INVALID. This prevents larger
947 * generations to propagate to our invl_gen->gen. Lock prefix
948 * in atomic_set_ptr() worked as seq_cst fence.
949 */
950 mygen = atomic_load_long(&invl_gen->gen);
951
952 if (!pmap_di_load_invl(p, &prev) || prev.next != invl_gen)
953 return (false);
954
955 KASSERT(prev.gen < mygen,
956 ("invalid di gen sequence %lu %lu", prev.gen, mygen));
957 new_prev.gen = mygen;
958 new_prev.next = (void *)((uintptr_t)invl_gen->next &
959 ~PMAP_INVL_GEN_NEXT_INVALID);
960
961 /* Formal fence between load of prev and storing update to it. */
962 atomic_thread_fence_rel();
963
964 return (pmap_di_store_invl(p, &prev, &new_prev));
965 }
966
967 static void
pmap_delayed_invl_finish_u(void)968 pmap_delayed_invl_finish_u(void)
969 {
970 struct pmap_invl_gen *invl_gen, *p;
971 struct thread *td;
972 struct lock_delay_arg lda;
973 uintptr_t prevl;
974
975 td = curthread;
976 invl_gen = &td->td_md.md_invl_gen;
977 KASSERT(invl_gen->gen != 0, ("missed invl_start: gen 0"));
978 KASSERT(((uintptr_t)invl_gen->next & PMAP_INVL_GEN_NEXT_INVALID) == 0,
979 ("missed invl_start: INVALID"));
980 lock_delay_arg_init(&lda, &di_delay);
981
982 again:
983 for (p = &pmap_invl_gen_head; p != NULL; p = (void *)prevl) {
984 prevl = (uintptr_t)atomic_load_ptr(&p->next);
985 if ((prevl & PMAP_INVL_GEN_NEXT_INVALID) != 0) {
986 PV_STAT(counter_u64_add(invl_finish_restart, 1));
987 lock_delay(&lda);
988 goto again;
989 }
990 if ((void *)prevl == invl_gen)
991 break;
992 }
993
994 /*
995 * It is legitimate to not find ourself on the list if a
996 * thread before us finished its DI and started it again.
997 */
998 if (__predict_false(p == NULL)) {
999 PV_STAT(counter_u64_add(invl_finish_restart, 1));
1000 lock_delay(&lda);
1001 goto again;
1002 }
1003
1004 critical_enter();
1005 atomic_set_ptr((uintptr_t *)&invl_gen->next,
1006 PMAP_INVL_GEN_NEXT_INVALID);
1007 if (!pmap_delayed_invl_finish_u_crit(invl_gen, p)) {
1008 atomic_clear_ptr((uintptr_t *)&invl_gen->next,
1009 PMAP_INVL_GEN_NEXT_INVALID);
1010 critical_exit();
1011 PV_STAT(counter_u64_add(invl_finish_restart, 1));
1012 lock_delay(&lda);
1013 goto again;
1014 }
1015 critical_exit();
1016 if (atomic_load_int(&pmap_invl_waiters) > 0)
1017 pmap_delayed_invl_finish_unblock(0);
1018 if (invl_gen->saved_pri != 0) {
1019 thread_lock(td);
1020 sched_prio(td, invl_gen->saved_pri);
1021 thread_unlock(td);
1022 }
1023 }
1024
1025 #ifdef DDB
DB_SHOW_COMMAND(di_queue,pmap_di_queue)1026 DB_SHOW_COMMAND(di_queue, pmap_di_queue)
1027 {
1028 struct pmap_invl_gen *p, *pn;
1029 struct thread *td;
1030 uintptr_t nextl;
1031 bool first;
1032
1033 for (p = &pmap_invl_gen_head, first = true; p != NULL; p = pn,
1034 first = false) {
1035 nextl = (uintptr_t)atomic_load_ptr(&p->next);
1036 pn = (void *)(nextl & ~PMAP_INVL_GEN_NEXT_INVALID);
1037 td = first ? NULL : __containerof(p, struct thread,
1038 td_md.md_invl_gen);
1039 db_printf("gen %lu inv %d td %p tid %d\n", p->gen,
1040 (nextl & PMAP_INVL_GEN_NEXT_INVALID) != 0, td,
1041 td != NULL ? td->td_tid : -1);
1042 }
1043 }
1044 #endif
1045
1046 #ifdef PV_STATS
1047 static COUNTER_U64_DEFINE_EARLY(invl_wait);
1048 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_wait,
1049 CTLFLAG_RD, &invl_wait,
1050 "Number of times DI invalidation blocked pmap_remove_all/write");
1051
1052 static COUNTER_U64_DEFINE_EARLY(invl_wait_slow);
1053 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, invl_wait_slow, CTLFLAG_RD,
1054 &invl_wait_slow, "Number of slow invalidation waits for lockless DI");
1055
1056 #endif
1057
1058 #ifdef NUMA
1059 static u_long *
pmap_delayed_invl_genp(vm_page_t m)1060 pmap_delayed_invl_genp(vm_page_t m)
1061 {
1062 vm_paddr_t pa;
1063 u_long *gen;
1064
1065 pa = VM_PAGE_TO_PHYS(m);
1066 if (__predict_false((pa) > pmap_last_pa))
1067 gen = &pv_dummy_large.pv_invl_gen;
1068 else
1069 gen = &(pa_to_pmdp(pa)->pv_invl_gen);
1070
1071 return (gen);
1072 }
1073 #else
1074 static u_long *
pmap_delayed_invl_genp(vm_page_t m)1075 pmap_delayed_invl_genp(vm_page_t m)
1076 {
1077
1078 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
1079 }
1080 #endif
1081
1082 static void
pmap_delayed_invl_callout_func(void * arg __unused)1083 pmap_delayed_invl_callout_func(void *arg __unused)
1084 {
1085
1086 if (atomic_load_int(&pmap_invl_waiters) == 0)
1087 return;
1088 pmap_delayed_invl_finish_unblock(0);
1089 }
1090
1091 static void
pmap_delayed_invl_callout_init(void * arg __unused)1092 pmap_delayed_invl_callout_init(void *arg __unused)
1093 {
1094
1095 if (pmap_di_locked())
1096 return;
1097 callout_init(&pmap_invl_callout, 1);
1098 pmap_invl_callout_inited = true;
1099 }
1100 SYSINIT(pmap_di_callout, SI_SUB_CPU + 1, SI_ORDER_ANY,
1101 pmap_delayed_invl_callout_init, NULL);
1102
1103 /*
1104 * Ensure that all currently executing DI blocks, that need to flush
1105 * TLB for the given page m, actually flushed the TLB at the time the
1106 * function returned. If the page m has an empty PV list and we call
1107 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
1108 * valid mapping for the page m in either its page table or TLB.
1109 *
1110 * This function works by blocking until the global DI generation
1111 * number catches up with the generation number associated with the
1112 * given page m and its PV list. Since this function's callers
1113 * typically own an object lock and sometimes own a page lock, it
1114 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
1115 * processor.
1116 */
1117 static void
pmap_delayed_invl_wait_l(vm_page_t m)1118 pmap_delayed_invl_wait_l(vm_page_t m)
1119 {
1120 u_long *m_gen;
1121 #ifdef PV_STATS
1122 bool accounted = false;
1123 #endif
1124
1125 m_gen = pmap_delayed_invl_genp(m);
1126 while (*m_gen > pmap_invl_gen) {
1127 #ifdef PV_STATS
1128 if (!accounted) {
1129 counter_u64_add(invl_wait, 1);
1130 accounted = true;
1131 }
1132 #endif
1133 pmap_delayed_invl_wait_block(m_gen, &pmap_invl_gen);
1134 }
1135 }
1136
1137 static void
pmap_delayed_invl_wait_u(vm_page_t m)1138 pmap_delayed_invl_wait_u(vm_page_t m)
1139 {
1140 u_long *m_gen;
1141 struct lock_delay_arg lda;
1142 bool fast;
1143
1144 fast = true;
1145 m_gen = pmap_delayed_invl_genp(m);
1146 lock_delay_arg_init(&lda, &di_delay);
1147 while (*m_gen > atomic_load_long(&pmap_invl_gen_head.gen)) {
1148 if (fast || !pmap_invl_callout_inited) {
1149 PV_STAT(counter_u64_add(invl_wait, 1));
1150 lock_delay(&lda);
1151 fast = false;
1152 } else {
1153 /*
1154 * The page's invalidation generation number
1155 * is still below the current thread's number.
1156 * Prepare to block so that we do not waste
1157 * CPU cycles or worse, suffer livelock.
1158 *
1159 * Since it is impossible to block without
1160 * racing with pmap_delayed_invl_finish_u(),
1161 * prepare for the race by incrementing
1162 * pmap_invl_waiters and arming a 1-tick
1163 * callout which will unblock us if we lose
1164 * the race.
1165 */
1166 atomic_add_int(&pmap_invl_waiters, 1);
1167
1168 /*
1169 * Re-check the current thread's invalidation
1170 * generation after incrementing
1171 * pmap_invl_waiters, so that there is no race
1172 * with pmap_delayed_invl_finish_u() setting
1173 * the page generation and checking
1174 * pmap_invl_waiters. The only race allowed
1175 * is for a missed unblock, which is handled
1176 * by the callout.
1177 */
1178 if (*m_gen >
1179 atomic_load_long(&pmap_invl_gen_head.gen)) {
1180 callout_reset(&pmap_invl_callout, 1,
1181 pmap_delayed_invl_callout_func, NULL);
1182 PV_STAT(counter_u64_add(invl_wait_slow, 1));
1183 pmap_delayed_invl_wait_block(m_gen,
1184 &pmap_invl_gen_head.gen);
1185 }
1186 atomic_add_int(&pmap_invl_waiters, -1);
1187 }
1188 }
1189 }
1190
1191 DEFINE_IFUNC(, void, pmap_thread_init_invl_gen, (struct thread *))
1192 {
1193
1194 return (pmap_di_locked() ? pmap_thread_init_invl_gen_l :
1195 pmap_thread_init_invl_gen_u);
1196 }
1197
1198 DEFINE_IFUNC(static, void, pmap_delayed_invl_start, (void))
1199 {
1200
1201 return (pmap_di_locked() ? pmap_delayed_invl_start_l :
1202 pmap_delayed_invl_start_u);
1203 }
1204
1205 DEFINE_IFUNC(static, void, pmap_delayed_invl_finish, (void))
1206 {
1207
1208 return (pmap_di_locked() ? pmap_delayed_invl_finish_l :
1209 pmap_delayed_invl_finish_u);
1210 }
1211
1212 DEFINE_IFUNC(static, void, pmap_delayed_invl_wait, (vm_page_t))
1213 {
1214
1215 return (pmap_di_locked() ? pmap_delayed_invl_wait_l :
1216 pmap_delayed_invl_wait_u);
1217 }
1218
1219 /*
1220 * Mark the page m's PV list as participating in the current thread's
1221 * DI block. Any threads concurrently using m's PV list to remove or
1222 * restrict all mappings to m will wait for the current thread's DI
1223 * block to complete before proceeding.
1224 *
1225 * The function works by setting the DI generation number for m's PV
1226 * list to at least the DI generation number of the current thread.
1227 * This forces a caller of pmap_delayed_invl_wait() to block until
1228 * current thread calls pmap_delayed_invl_finish().
1229 */
1230 static void
pmap_delayed_invl_page(vm_page_t m)1231 pmap_delayed_invl_page(vm_page_t m)
1232 {
1233 u_long gen, *m_gen;
1234
1235 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
1236 gen = curthread->td_md.md_invl_gen.gen;
1237 if (gen == 0)
1238 return;
1239 m_gen = pmap_delayed_invl_genp(m);
1240 if (*m_gen < gen)
1241 *m_gen = gen;
1242 }
1243
1244 /*
1245 * Crashdump maps.
1246 */
1247 static caddr_t crashdumpmap;
1248
1249 /*
1250 * Internal flags for pmap_enter()'s helper functions.
1251 */
1252 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
1253 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
1254
1255 /*
1256 * Internal flags for pmap_mapdev_internal() and
1257 * pmap_change_props_locked().
1258 */
1259 #define MAPDEV_FLUSHCACHE 0x00000001 /* Flush cache after mapping. */
1260 #define MAPDEV_SETATTR 0x00000002 /* Modify existing attrs. */
1261 #define MAPDEV_ASSERTVALID 0x00000004 /* Assert mapping validity. */
1262
1263 TAILQ_HEAD(pv_chunklist, pv_chunk);
1264
1265 static void free_pv_chunk(struct pv_chunk *pc);
1266 static void free_pv_chunk_batch(struct pv_chunklist *batch);
1267 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
1268 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
1269 static int popcnt_pc_map_pq(uint64_t *map);
1270 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
1271 static void reserve_pv_entries(pmap_t pmap, int needed,
1272 struct rwlock **lockp);
1273 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
1274 struct rwlock **lockp);
1275 static bool pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
1276 u_int flags, struct rwlock **lockp);
1277 #if VM_NRESERVLEVEL > 0
1278 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
1279 struct rwlock **lockp);
1280 #endif
1281 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
1282 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
1283 vm_offset_t va);
1284
1285 static void pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte);
1286 static int pmap_change_props_locked(vm_offset_t va, vm_size_t size,
1287 vm_prot_t prot, int mode, int flags);
1288 static bool pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
1289 static bool pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
1290 vm_offset_t va, struct rwlock **lockp);
1291 static bool pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
1292 vm_offset_t va);
1293 static int pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
1294 vm_prot_t prot, struct rwlock **lockp);
1295 static int pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
1296 u_int flags, vm_page_t m, struct rwlock **lockp);
1297 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
1298 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
1299 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
1300 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted,
1301 bool allpte_PG_A_set);
1302 static void pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva,
1303 vm_offset_t eva);
1304 static void pmap_invalidate_cache_range_all(vm_offset_t sva,
1305 vm_offset_t eva);
1306 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
1307 pd_entry_t pde);
1308 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
1309 static vm_page_t pmap_large_map_getptp_unlocked(void);
1310 static vm_paddr_t pmap_large_map_kextract(vm_offset_t va);
1311 #if VM_NRESERVLEVEL > 0
1312 static bool pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
1313 vm_page_t mpte, struct rwlock **lockp);
1314 #endif
1315 static bool pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
1316 vm_prot_t prot);
1317 static void pmap_pte_props(pt_entry_t *pte, u_long bits, u_long mask);
1318 static void pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva,
1319 bool exec);
1320 static pdp_entry_t *pmap_pti_pdpe(vm_offset_t va);
1321 static pd_entry_t *pmap_pti_pde(vm_offset_t va);
1322 static void pmap_pti_wire_pte(void *pte);
1323 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
1324 struct spglist *free, struct rwlock **lockp);
1325 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
1326 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
1327 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
1328 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
1329 struct spglist *free);
1330 static bool pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
1331 pd_entry_t *pde, struct spglist *free,
1332 struct rwlock **lockp);
1333 static bool pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
1334 vm_page_t m, struct rwlock **lockp);
1335 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
1336 pd_entry_t newpde);
1337 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
1338
1339 static pd_entry_t *pmap_alloc_pde(pmap_t pmap, vm_offset_t va, vm_page_t *pdpgp,
1340 struct rwlock **lockp);
1341 static vm_page_t pmap_allocpte_alloc(pmap_t pmap, vm_pindex_t ptepindex,
1342 struct rwlock **lockp, vm_offset_t va);
1343 static vm_page_t pmap_allocpte_nosleep(pmap_t pmap, vm_pindex_t ptepindex,
1344 struct rwlock **lockp, vm_offset_t va);
1345 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
1346 struct rwlock **lockp);
1347
1348 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
1349 struct spglist *free);
1350 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
1351
1352 static vm_page_t pmap_alloc_pt_page(pmap_t, vm_pindex_t, int);
1353 static void pmap_free_pt_page(pmap_t, vm_page_t, bool);
1354
1355 /********************/
1356 /* Inline functions */
1357 /********************/
1358
1359 /*
1360 * Return a non-clipped indexes for a given VA, which are page table
1361 * pages indexes at the corresponding level.
1362 */
1363 static __inline vm_pindex_t
pmap_pde_pindex(vm_offset_t va)1364 pmap_pde_pindex(vm_offset_t va)
1365 {
1366 return (va >> PDRSHIFT);
1367 }
1368
1369 static __inline vm_pindex_t
pmap_pdpe_pindex(vm_offset_t va)1370 pmap_pdpe_pindex(vm_offset_t va)
1371 {
1372 return (NUPDE + (va >> PDPSHIFT));
1373 }
1374
1375 static __inline vm_pindex_t
pmap_pml4e_pindex(vm_offset_t va)1376 pmap_pml4e_pindex(vm_offset_t va)
1377 {
1378 return (NUPDE + NUPDPE + (va >> PML4SHIFT));
1379 }
1380
1381 static __inline vm_pindex_t
pmap_pml5e_pindex(vm_offset_t va)1382 pmap_pml5e_pindex(vm_offset_t va)
1383 {
1384 return (NUPDE + NUPDPE + NUPML4E + (va >> PML5SHIFT));
1385 }
1386
1387 static __inline pml4_entry_t *
pmap_pml5e(pmap_t pmap,vm_offset_t va)1388 pmap_pml5e(pmap_t pmap, vm_offset_t va)
1389 {
1390
1391 MPASS(pmap_is_la57(pmap));
1392 return (&pmap->pm_pmltop[pmap_pml5e_index(va)]);
1393 }
1394
1395 static __inline pml4_entry_t *
pmap_pml5e_u(pmap_t pmap,vm_offset_t va)1396 pmap_pml5e_u(pmap_t pmap, vm_offset_t va)
1397 {
1398
1399 MPASS(pmap_is_la57(pmap));
1400 return (&pmap->pm_pmltopu[pmap_pml5e_index(va)]);
1401 }
1402
1403 static __inline pml4_entry_t *
pmap_pml5e_to_pml4e(pml5_entry_t * pml5e,vm_offset_t va)1404 pmap_pml5e_to_pml4e(pml5_entry_t *pml5e, vm_offset_t va)
1405 {
1406 pml4_entry_t *pml4e;
1407
1408 /* XXX MPASS(pmap_is_la57(pmap); */
1409 pml4e = (pml4_entry_t *)PHYS_TO_DMAP(*pml5e & PG_FRAME);
1410 return (&pml4e[pmap_pml4e_index(va)]);
1411 }
1412
1413 /* Return a pointer to the PML4 slot that corresponds to a VA */
1414 static __inline pml4_entry_t *
pmap_pml4e(pmap_t pmap,vm_offset_t va)1415 pmap_pml4e(pmap_t pmap, vm_offset_t va)
1416 {
1417 pml5_entry_t *pml5e;
1418 pml4_entry_t *pml4e;
1419 pt_entry_t PG_V;
1420
1421 if (pmap_is_la57(pmap)) {
1422 pml5e = pmap_pml5e(pmap, va);
1423 PG_V = pmap_valid_bit(pmap);
1424 if ((*pml5e & PG_V) == 0)
1425 return (NULL);
1426 pml4e = (pml4_entry_t *)PHYS_TO_DMAP(*pml5e & PG_FRAME);
1427 } else {
1428 pml4e = pmap->pm_pmltop;
1429 }
1430 return (&pml4e[pmap_pml4e_index(va)]);
1431 }
1432
1433 static __inline pml4_entry_t *
pmap_pml4e_u(pmap_t pmap,vm_offset_t va)1434 pmap_pml4e_u(pmap_t pmap, vm_offset_t va)
1435 {
1436 MPASS(!pmap_is_la57(pmap));
1437 return (&pmap->pm_pmltopu[pmap_pml4e_index(va)]);
1438 }
1439
1440 /* Return a pointer to the PDP slot that corresponds to a VA */
1441 static __inline pdp_entry_t *
pmap_pml4e_to_pdpe(pml4_entry_t * pml4e,vm_offset_t va)1442 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
1443 {
1444 pdp_entry_t *pdpe;
1445
1446 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
1447 return (&pdpe[pmap_pdpe_index(va)]);
1448 }
1449
1450 /* Return a pointer to the PDP slot that corresponds to a VA */
1451 static __inline pdp_entry_t *
pmap_pdpe(pmap_t pmap,vm_offset_t va)1452 pmap_pdpe(pmap_t pmap, vm_offset_t va)
1453 {
1454 pml4_entry_t *pml4e;
1455 pt_entry_t PG_V;
1456
1457 PG_V = pmap_valid_bit(pmap);
1458 pml4e = pmap_pml4e(pmap, va);
1459 if (pml4e == NULL || (*pml4e & PG_V) == 0)
1460 return (NULL);
1461 return (pmap_pml4e_to_pdpe(pml4e, va));
1462 }
1463
1464 /* Return a pointer to the PD slot that corresponds to a VA */
1465 static __inline pd_entry_t *
pmap_pdpe_to_pde(pdp_entry_t * pdpe,vm_offset_t va)1466 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
1467 {
1468 pd_entry_t *pde;
1469
1470 KASSERT((*pdpe & PG_PS) == 0,
1471 ("%s: pdpe %#lx is a leaf", __func__, *pdpe));
1472 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
1473 return (&pde[pmap_pde_index(va)]);
1474 }
1475
1476 /* Return a pointer to the PD slot that corresponds to a VA */
1477 static __inline pd_entry_t *
pmap_pde(pmap_t pmap,vm_offset_t va)1478 pmap_pde(pmap_t pmap, vm_offset_t va)
1479 {
1480 pdp_entry_t *pdpe;
1481 pt_entry_t PG_V;
1482
1483 PG_V = pmap_valid_bit(pmap);
1484 pdpe = pmap_pdpe(pmap, va);
1485 if (pdpe == NULL || (*pdpe & PG_V) == 0)
1486 return (NULL);
1487 KASSERT((*pdpe & PG_PS) == 0,
1488 ("pmap_pde for 1G page, pmap %p va %#lx", pmap, va));
1489 return (pmap_pdpe_to_pde(pdpe, va));
1490 }
1491
1492 /* Return a pointer to the PT slot that corresponds to a VA */
1493 static __inline pt_entry_t *
pmap_pde_to_pte(pd_entry_t * pde,vm_offset_t va)1494 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
1495 {
1496 pt_entry_t *pte;
1497
1498 KASSERT((*pde & PG_PS) == 0,
1499 ("%s: pde %#lx is a leaf", __func__, *pde));
1500 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
1501 return (&pte[pmap_pte_index(va)]);
1502 }
1503
1504 /* Return a pointer to the PT slot that corresponds to a VA */
1505 static __inline pt_entry_t *
pmap_pte(pmap_t pmap,vm_offset_t va)1506 pmap_pte(pmap_t pmap, vm_offset_t va)
1507 {
1508 pd_entry_t *pde;
1509 pt_entry_t PG_V;
1510
1511 PG_V = pmap_valid_bit(pmap);
1512 pde = pmap_pde(pmap, va);
1513 if (pde == NULL || (*pde & PG_V) == 0)
1514 return (NULL);
1515 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
1516 return ((pt_entry_t *)pde);
1517 return (pmap_pde_to_pte(pde, va));
1518 }
1519
1520 static __inline void
pmap_resident_count_adj(pmap_t pmap,int count)1521 pmap_resident_count_adj(pmap_t pmap, int count)
1522 {
1523
1524 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1525 KASSERT(pmap->pm_stats.resident_count + count >= 0,
1526 ("pmap %p resident count underflow %ld %d", pmap,
1527 pmap->pm_stats.resident_count, count));
1528 pmap->pm_stats.resident_count += count;
1529 }
1530
1531 static __inline void
pmap_pt_page_count_pinit(pmap_t pmap,int count)1532 pmap_pt_page_count_pinit(pmap_t pmap, int count)
1533 {
1534 KASSERT(pmap->pm_stats.resident_count + count >= 0,
1535 ("pmap %p resident count underflow %ld %d", pmap,
1536 pmap->pm_stats.resident_count, count));
1537 pmap->pm_stats.resident_count += count;
1538 }
1539
1540 static __inline void
pmap_pt_page_count_adj(pmap_t pmap,int count)1541 pmap_pt_page_count_adj(pmap_t pmap, int count)
1542 {
1543 if (pmap == kernel_pmap)
1544 counter_u64_add(kernel_pt_page_count, count);
1545 else {
1546 if (pmap != NULL)
1547 pmap_resident_count_adj(pmap, count);
1548 counter_u64_add(user_pt_page_count, count);
1549 }
1550 }
1551
1552 pt_entry_t vtoptem __read_mostly = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT +
1553 NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1) << 3;
1554 vm_offset_t PTmap __read_mostly = (vm_offset_t)P4Tmap;
1555
1556 pt_entry_t *
vtopte(vm_offset_t va)1557 vtopte(vm_offset_t va)
1558 {
1559 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
1560
1561 return ((pt_entry_t *)(PTmap + ((va >> (PAGE_SHIFT - 3)) & vtoptem)));
1562 }
1563
1564 pd_entry_t vtopdem __read_mostly = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
1565 NPML4EPGSHIFT)) - 1) << 3;
1566 vm_offset_t PDmap __read_mostly = (vm_offset_t)P4Dmap;
1567
1568 static __inline pd_entry_t *
vtopde(vm_offset_t va)1569 vtopde(vm_offset_t va)
1570 {
1571 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
1572
1573 return ((pt_entry_t *)(PDmap + ((va >> (PDRSHIFT - 3)) & vtopdem)));
1574 }
1575
1576 static u_int64_t
allocpages(vm_paddr_t * firstaddr,int n)1577 allocpages(vm_paddr_t *firstaddr, int n)
1578 {
1579 u_int64_t ret;
1580
1581 ret = *firstaddr;
1582 bzero((void *)ret, n * PAGE_SIZE);
1583 *firstaddr += n * PAGE_SIZE;
1584 return (ret);
1585 }
1586
1587 CTASSERT(powerof2(NDMPML4E));
1588
1589 /* number of kernel PDP slots */
1590 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
1591
1592 static void
nkpt_init(vm_paddr_t addr)1593 nkpt_init(vm_paddr_t addr)
1594 {
1595 int pt_pages;
1596
1597 #ifdef NKPT
1598 pt_pages = NKPT;
1599 #else
1600 pt_pages = howmany(addr - kernphys, NBPDR) + 1; /* +1 for 2M hole @0 */
1601 pt_pages += NKPDPE(pt_pages);
1602
1603 /*
1604 * Add some slop beyond the bare minimum required for bootstrapping
1605 * the kernel.
1606 *
1607 * This is quite important when allocating KVA for kernel modules.
1608 * The modules are required to be linked in the negative 2GB of
1609 * the address space. If we run out of KVA in this region then
1610 * pmap_growkernel() will need to allocate page table pages to map
1611 * the entire 512GB of KVA space which is an unnecessary tax on
1612 * physical memory.
1613 *
1614 * Secondly, device memory mapped as part of setting up the low-
1615 * level console(s) is taken from KVA, starting at virtual_avail.
1616 * This is because cninit() is called after pmap_bootstrap() but
1617 * before vm_mem_init() and pmap_init(). 20MB for a frame buffer
1618 * is not uncommon.
1619 */
1620 pt_pages += 32; /* 64MB additional slop. */
1621 #endif
1622 nkpt = pt_pages;
1623 }
1624
1625 /*
1626 * Returns the proper write/execute permission for a physical page that is
1627 * part of the initial boot allocations.
1628 *
1629 * If the page has kernel text, it is marked as read-only. If the page has
1630 * kernel read-only data, it is marked as read-only/not-executable. If the
1631 * page has only read-write data, it is marked as read-write/not-executable.
1632 * If the page is below/above the kernel range, it is marked as read-write.
1633 *
1634 * This function operates on 2M pages, since we map the kernel space that
1635 * way.
1636 */
1637 static inline pt_entry_t
bootaddr_rwx(vm_paddr_t pa)1638 bootaddr_rwx(vm_paddr_t pa)
1639 {
1640 /*
1641 * The kernel is loaded at a 2MB-aligned address, and memory below that
1642 * need not be executable. The .bss section is padded to a 2MB
1643 * boundary, so memory following the kernel need not be executable
1644 * either. Preloaded kernel modules have their mapping permissions
1645 * fixed up by the linker.
1646 */
1647 if (pa < trunc_2mpage(kernphys + btext - KERNSTART) ||
1648 pa >= trunc_2mpage(kernphys + _end - KERNSTART))
1649 return (X86_PG_RW | pg_nx);
1650
1651 /*
1652 * The linker should ensure that the read-only and read-write
1653 * portions don't share the same 2M page, so this shouldn't
1654 * impact read-only data. However, in any case, any page with
1655 * read-write data needs to be read-write.
1656 */
1657 if (pa >= trunc_2mpage(kernphys + brwsection - KERNSTART))
1658 return (X86_PG_RW | pg_nx);
1659
1660 /*
1661 * Mark any 2M page containing kernel text as read-only. Mark
1662 * other pages with read-only data as read-only and not executable.
1663 * (It is likely a small portion of the read-only data section will
1664 * be marked as read-only, but executable. This should be acceptable
1665 * since the read-only protection will keep the data from changing.)
1666 * Note that fixups to the .text section will still work until we
1667 * set CR0.WP.
1668 */
1669 if (pa < round_2mpage(kernphys + etext - KERNSTART))
1670 return (0);
1671 return (pg_nx);
1672 }
1673
1674 static void
create_pagetables(vm_paddr_t * firstaddr)1675 create_pagetables(vm_paddr_t *firstaddr)
1676 {
1677 pd_entry_t *pd_p;
1678 pdp_entry_t *pdp_p;
1679 pml4_entry_t *p4_p;
1680 uint64_t DMPDkernphys;
1681 vm_paddr_t pax;
1682 #ifdef KASAN
1683 pt_entry_t *pt_p;
1684 uint64_t KASANPDphys, KASANPTphys, KASANphys;
1685 vm_offset_t kasankernbase;
1686 int kasankpdpi, kasankpdi, nkasanpte;
1687 #endif
1688 int i, j, ndm1g, nkpdpe, nkdmpde;
1689
1690 TSENTER();
1691 /* Allocate page table pages for the direct map */
1692 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
1693 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
1694 ndmpdp = 4;
1695 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
1696 if (ndmpdpphys > NDMPML4E) {
1697 /*
1698 * Each NDMPML4E allows 512 GB, so limit to that,
1699 * and then readjust ndmpdp and ndmpdpphys.
1700 */
1701 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
1702 Maxmem = atop(NDMPML4E * NBPML4);
1703 ndmpdpphys = NDMPML4E;
1704 ndmpdp = NDMPML4E * NPDEPG;
1705 }
1706 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
1707 ndm1g = 0;
1708 if ((amd_feature & AMDID_PAGE1GB) != 0) {
1709 /*
1710 * Calculate the number of 1G pages that will fully fit in
1711 * Maxmem.
1712 */
1713 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
1714
1715 /*
1716 * Allocate 2M pages for the kernel. These will be used in
1717 * place of the one or more 1G pages from ndm1g that maps
1718 * kernel memory into DMAP.
1719 */
1720 nkdmpde = howmany((vm_offset_t)brwsection - KERNSTART +
1721 kernphys - rounddown2(kernphys, NBPDP), NBPDP);
1722 DMPDkernphys = allocpages(firstaddr, nkdmpde);
1723 }
1724 if (ndm1g < ndmpdp)
1725 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
1726 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
1727
1728 /* Allocate pages. */
1729 KPML4phys = allocpages(firstaddr, 1);
1730 KPDPphys = allocpages(firstaddr, NKPML4E);
1731 #ifdef KASAN
1732 KASANPDPphys = allocpages(firstaddr, NKASANPML4E);
1733 KASANPDphys = allocpages(firstaddr, 1);
1734 #endif
1735 #ifdef KMSAN
1736 /*
1737 * The KMSAN shadow maps are initially left unpopulated, since there is
1738 * no need to shadow memory above KERNBASE.
1739 */
1740 KMSANSHADPDPphys = allocpages(firstaddr, NKMSANSHADPML4E);
1741 KMSANORIGPDPphys = allocpages(firstaddr, NKMSANORIGPML4E);
1742 #endif
1743
1744 /*
1745 * Allocate the initial number of kernel page table pages required to
1746 * bootstrap. We defer this until after all memory-size dependent
1747 * allocations are done (e.g. direct map), so that we don't have to
1748 * build in too much slop in our estimate.
1749 *
1750 * Note that when NKPML4E > 1, we have an empty page underneath
1751 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
1752 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
1753 */
1754 nkpt_init(*firstaddr);
1755 nkpdpe = NKPDPE(nkpt);
1756
1757 KPTphys = allocpages(firstaddr, nkpt);
1758 KPDphys = allocpages(firstaddr, nkpdpe);
1759
1760 #ifdef KASAN
1761 nkasanpte = howmany(nkpt, KASAN_SHADOW_SCALE);
1762 KASANPTphys = allocpages(firstaddr, nkasanpte);
1763 KASANphys = allocpages(firstaddr, nkasanpte * NPTEPG);
1764 #endif
1765
1766 /*
1767 * Connect the zero-filled PT pages to their PD entries. This
1768 * implicitly maps the PT pages at their correct locations within
1769 * the PTmap.
1770 */
1771 pd_p = (pd_entry_t *)KPDphys;
1772 for (i = 0; i < nkpt; i++)
1773 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
1774
1775 /*
1776 * Map from start of the kernel in physical memory (staging
1777 * area) to the end of loader preallocated memory using 2MB
1778 * pages. This replaces some of the PD entries created above.
1779 * For compatibility, identity map 2M at the start.
1780 */
1781 pd_p[0] = X86_PG_V | PG_PS | pg_g | X86_PG_M | X86_PG_A |
1782 X86_PG_RW | pg_nx;
1783 for (i = 1, pax = kernphys; pax < KERNend; i++, pax += NBPDR) {
1784 /* Preset PG_M and PG_A because demotion expects it. */
1785 pd_p[i] = pax | X86_PG_V | PG_PS | pg_g | X86_PG_M |
1786 X86_PG_A | bootaddr_rwx(pax);
1787 }
1788
1789 /*
1790 * Because we map the physical blocks in 2M pages, adjust firstaddr
1791 * to record the physical blocks we've actually mapped into kernel
1792 * virtual address space.
1793 */
1794 if (*firstaddr < round_2mpage(KERNend))
1795 *firstaddr = round_2mpage(KERNend);
1796
1797 /* And connect up the PD to the PDP (leaving room for L4 pages) */
1798 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
1799 for (i = 0; i < nkpdpe; i++)
1800 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
1801
1802 #ifdef KASAN
1803 kasankernbase = kasan_md_addr_to_shad(KERNBASE);
1804 kasankpdpi = pmap_pdpe_index(kasankernbase);
1805 kasankpdi = pmap_pde_index(kasankernbase);
1806
1807 pdp_p = (pdp_entry_t *)KASANPDPphys;
1808 pdp_p[kasankpdpi] = (KASANPDphys | X86_PG_RW | X86_PG_V | pg_nx);
1809
1810 pd_p = (pd_entry_t *)KASANPDphys;
1811 for (i = 0; i < nkasanpte; i++)
1812 pd_p[i + kasankpdi] = (KASANPTphys + ptoa(i)) | X86_PG_RW |
1813 X86_PG_V | pg_nx;
1814
1815 pt_p = (pt_entry_t *)KASANPTphys;
1816 for (i = 0; i < nkasanpte * NPTEPG; i++)
1817 pt_p[i] = (KASANphys + ptoa(i)) | X86_PG_RW | X86_PG_V |
1818 X86_PG_M | X86_PG_A | pg_nx;
1819 #endif
1820
1821 /*
1822 * Now, set up the direct map region using 2MB and/or 1GB pages. If
1823 * the end of physical memory is not aligned to a 1GB page boundary,
1824 * then the residual physical memory is mapped with 2MB pages. Later,
1825 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
1826 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
1827 * that are partially used.
1828 */
1829 pd_p = (pd_entry_t *)DMPDphys;
1830 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
1831 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
1832 /* Preset PG_M and PG_A because demotion expects it. */
1833 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1834 X86_PG_M | X86_PG_A | pg_nx;
1835 }
1836 pdp_p = (pdp_entry_t *)DMPDPphys;
1837 for (i = 0; i < ndm1g; i++) {
1838 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
1839 /* Preset PG_M and PG_A because demotion expects it. */
1840 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
1841 X86_PG_M | X86_PG_A | pg_nx;
1842 }
1843 for (j = 0; i < ndmpdp; i++, j++) {
1844 pdp_p[i] = DMPDphys + ptoa(j);
1845 pdp_p[i] |= X86_PG_RW | X86_PG_V | pg_nx;
1846 }
1847
1848 /*
1849 * Instead of using a 1G page for the memory containing the kernel,
1850 * use 2M pages with read-only and no-execute permissions. (If using 1G
1851 * pages, this will partially overwrite the PDPEs above.)
1852 */
1853 if (ndm1g > 0) {
1854 pd_p = (pd_entry_t *)DMPDkernphys;
1855 for (i = 0, pax = rounddown2(kernphys, NBPDP);
1856 i < NPDEPG * nkdmpde; i++, pax += NBPDR) {
1857 pd_p[i] = pax | X86_PG_V | PG_PS | pg_g | X86_PG_M |
1858 X86_PG_A | pg_nx | bootaddr_rwx(pax);
1859 }
1860 j = rounddown2(kernphys, NBPDP) >> PDPSHIFT;
1861 for (i = 0; i < nkdmpde; i++) {
1862 pdp_p[i + j] = (DMPDkernphys + ptoa(i)) |
1863 X86_PG_RW | X86_PG_V | pg_nx;
1864 }
1865 }
1866
1867 /* And recursively map PML4 to itself in order to get PTmap */
1868 p4_p = (pml4_entry_t *)KPML4phys;
1869 p4_p[PML4PML4I] = KPML4phys;
1870 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | pg_nx;
1871
1872 #ifdef KASAN
1873 /* Connect the KASAN shadow map slots up to the PML4. */
1874 for (i = 0; i < NKASANPML4E; i++) {
1875 p4_p[KASANPML4I + i] = KASANPDPphys + ptoa(i);
1876 p4_p[KASANPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1877 }
1878 #endif
1879
1880 #ifdef KMSAN
1881 /* Connect the KMSAN shadow map slots up to the PML4. */
1882 for (i = 0; i < NKMSANSHADPML4E; i++) {
1883 p4_p[KMSANSHADPML4I + i] = KMSANSHADPDPphys + ptoa(i);
1884 p4_p[KMSANSHADPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1885 }
1886
1887 /* Connect the KMSAN origin map slots up to the PML4. */
1888 for (i = 0; i < NKMSANORIGPML4E; i++) {
1889 p4_p[KMSANORIGPML4I + i] = KMSANORIGPDPphys + ptoa(i);
1890 p4_p[KMSANORIGPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1891 }
1892 #endif
1893
1894 /* Connect the Direct Map slots up to the PML4. */
1895 for (i = 0; i < ndmpdpphys; i++) {
1896 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
1897 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V | pg_nx;
1898 }
1899
1900 /* Connect the KVA slots up to the PML4 */
1901 for (i = 0; i < NKPML4E; i++) {
1902 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
1903 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V;
1904 }
1905
1906 kernel_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
1907 TSEXIT();
1908 }
1909
1910 /*
1911 * Bootstrap the system enough to run with virtual memory.
1912 *
1913 * On amd64 this is called after mapping has already been enabled
1914 * and just syncs the pmap module with what has already been done.
1915 * [We can't call it easily with mapping off since the kernel is not
1916 * mapped with PA == VA, hence we would have to relocate every address
1917 * from the linked base (virtual) address "KERNBASE" to the actual
1918 * (physical) address starting relative to 0]
1919 */
1920 void
pmap_bootstrap(vm_paddr_t * firstaddr)1921 pmap_bootstrap(vm_paddr_t *firstaddr)
1922 {
1923 vm_offset_t va;
1924 pt_entry_t *pte, *pcpu_pte;
1925 struct region_descriptor r_gdt;
1926 uint64_t cr4, pcpu0_phys;
1927 u_long res;
1928 int i;
1929
1930 TSENTER();
1931 KERNend = *firstaddr;
1932 res = atop(KERNend - (vm_paddr_t)kernphys);
1933
1934 if (!pti)
1935 pg_g = X86_PG_G;
1936
1937 /*
1938 * Create an initial set of page tables to run the kernel in.
1939 */
1940 create_pagetables(firstaddr);
1941
1942 pcpu0_phys = allocpages(firstaddr, 1);
1943
1944 /*
1945 * Add a physical memory segment (vm_phys_seg) corresponding to the
1946 * preallocated kernel page table pages so that vm_page structures
1947 * representing these pages will be created. The vm_page structures
1948 * are required for promotion of the corresponding kernel virtual
1949 * addresses to superpage mappings.
1950 */
1951 vm_phys_early_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1952
1953 /*
1954 * Account for the virtual addresses mapped by create_pagetables().
1955 */
1956 virtual_avail = (vm_offset_t)KERNSTART + round_2mpage(KERNend -
1957 (vm_paddr_t)kernphys);
1958 virtual_end = VM_MAX_KERNEL_ADDRESS;
1959
1960 /*
1961 * Enable PG_G global pages, then switch to the kernel page
1962 * table from the bootstrap page table. After the switch, it
1963 * is possible to enable SMEP and SMAP since PG_U bits are
1964 * correct now.
1965 */
1966 cr4 = rcr4();
1967 cr4 |= CR4_PGE;
1968 load_cr4(cr4);
1969 load_cr3(KPML4phys);
1970 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1971 cr4 |= CR4_SMEP;
1972 if (cpu_stdext_feature & CPUID_STDEXT_SMAP)
1973 cr4 |= CR4_SMAP;
1974 load_cr4(cr4);
1975
1976 /*
1977 * Initialize the kernel pmap (which is statically allocated).
1978 * Count bootstrap data as being resident in case any of this data is
1979 * later unmapped (using pmap_remove()) and freed.
1980 */
1981 PMAP_LOCK_INIT(kernel_pmap);
1982 kernel_pmap->pm_pmltop = kernel_pml4;
1983 kernel_pmap->pm_cr3 = KPML4phys;
1984 kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
1985 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1986 kernel_pmap->pm_stats.resident_count = res;
1987 vm_radix_init(&kernel_pmap->pm_root);
1988 kernel_pmap->pm_flags = pmap_flags;
1989 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
1990 rangeset_init(&kernel_pmap->pm_pkru, pkru_dup_range,
1991 pkru_free_range, kernel_pmap, M_NOWAIT);
1992 }
1993
1994 /*
1995 * The kernel pmap is always active on all CPUs. Once CPUs are
1996 * enumerated, the mask will be set equal to all_cpus.
1997 */
1998 CPU_FILL(&kernel_pmap->pm_active);
1999
2000 /*
2001 * Initialize the TLB invalidations generation number lock.
2002 */
2003 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
2004
2005 /*
2006 * Reserve some special page table entries/VA space for temporary
2007 * mapping of pages.
2008 */
2009 #define SYSMAP(c, p, v, n) \
2010 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
2011
2012 va = virtual_avail;
2013 pte = vtopte(va);
2014
2015 /*
2016 * Crashdump maps. The first page is reused as CMAP1 for the
2017 * memory test.
2018 */
2019 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
2020 CADDR1 = crashdumpmap;
2021
2022 SYSMAP(struct pcpu *, pcpu_pte, __pcpu, MAXCPU);
2023 virtual_avail = va;
2024
2025 /*
2026 * Map the BSP PCPU now, the rest of the PCPUs are mapped by
2027 * amd64_mp_alloc_pcpu()/start_all_aps() when we know the
2028 * number of CPUs and NUMA affinity.
2029 */
2030 pcpu_pte[0] = pcpu0_phys | X86_PG_V | X86_PG_RW | pg_g | pg_nx |
2031 X86_PG_M | X86_PG_A;
2032 for (i = 1; i < MAXCPU; i++)
2033 pcpu_pte[i] = 0;
2034
2035 /*
2036 * Re-initialize PCPU area for BSP after switching.
2037 * Make hardware use gdt and common_tss from the new PCPU.
2038 */
2039 STAILQ_INIT(&cpuhead);
2040 wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
2041 pcpu_init(&__pcpu[0], 0, sizeof(struct pcpu));
2042 amd64_bsp_pcpu_init1(&__pcpu[0]);
2043 amd64_bsp_ist_init(&__pcpu[0]);
2044 __pcpu[0].pc_common_tss.tss_iobase = sizeof(struct amd64tss) +
2045 IOPERM_BITMAP_SIZE;
2046 memcpy(__pcpu[0].pc_gdt, temp_bsp_pcpu.pc_gdt, NGDT *
2047 sizeof(struct user_segment_descriptor));
2048 gdt_segs[GPROC0_SEL].ssd_base = (uintptr_t)&__pcpu[0].pc_common_tss;
2049 ssdtosyssd(&gdt_segs[GPROC0_SEL],
2050 (struct system_segment_descriptor *)&__pcpu[0].pc_gdt[GPROC0_SEL]);
2051 r_gdt.rd_limit = NGDT * sizeof(struct user_segment_descriptor) - 1;
2052 r_gdt.rd_base = (long)__pcpu[0].pc_gdt;
2053 lgdt(&r_gdt);
2054 wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
2055 ltr(GSEL(GPROC0_SEL, SEL_KPL));
2056 __pcpu[0].pc_dynamic = temp_bsp_pcpu.pc_dynamic;
2057 __pcpu[0].pc_acpi_id = temp_bsp_pcpu.pc_acpi_id;
2058
2059 /*
2060 * Initialize the PAT MSR.
2061 * pmap_init_pat() clears and sets CR4_PGE, which, as a
2062 * side-effect, invalidates stale PG_G TLB entries that might
2063 * have been created in our pre-boot environment.
2064 */
2065 pmap_init_pat();
2066
2067 /* Initialize TLB Context Id. */
2068 if (pmap_pcid_enabled) {
2069 kernel_pmap->pm_pcidp = (void *)(uintptr_t)
2070 offsetof(struct pcpu, pc_kpmap_store);
2071
2072 PCPU_SET(kpmap_store.pm_pcid, PMAP_PCID_KERN);
2073 PCPU_SET(kpmap_store.pm_gen, 1);
2074
2075 /*
2076 * PMAP_PCID_KERN + 1 is used for initialization of
2077 * proc0 pmap. The pmap' pcid state might be used by
2078 * EFIRT entry before first context switch, so it
2079 * needs to be valid.
2080 */
2081 PCPU_SET(pcid_next, PMAP_PCID_KERN + 2);
2082 PCPU_SET(pcid_gen, 1);
2083
2084 /*
2085 * pcpu area for APs is zeroed during AP startup.
2086 * pc_pcid_next and pc_pcid_gen are initialized by AP
2087 * during pcpu setup.
2088 */
2089 load_cr4(rcr4() | CR4_PCIDE);
2090 }
2091 TSEXIT();
2092 }
2093
2094 /*
2095 * Setup the PAT MSR.
2096 */
2097 void
pmap_init_pat(void)2098 pmap_init_pat(void)
2099 {
2100 uint64_t pat_msr;
2101 u_long cr0, cr4;
2102 int i;
2103
2104 /* Bail if this CPU doesn't implement PAT. */
2105 if ((cpu_feature & CPUID_PAT) == 0)
2106 panic("no PAT??");
2107
2108 /* Set default PAT index table. */
2109 for (i = 0; i < PAT_INDEX_SIZE; i++)
2110 pat_index[i] = -1;
2111 pat_index[PAT_WRITE_BACK] = 0;
2112 pat_index[PAT_WRITE_THROUGH] = 1;
2113 pat_index[PAT_UNCACHEABLE] = 3;
2114 pat_index[PAT_WRITE_COMBINING] = 6;
2115 pat_index[PAT_WRITE_PROTECTED] = 5;
2116 pat_index[PAT_UNCACHED] = 2;
2117
2118 /*
2119 * Initialize default PAT entries.
2120 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
2121 * Program 5 and 6 as WP and WC.
2122 *
2123 * Leave 4 and 7 as WB and UC. Note that a recursive page table
2124 * mapping for a 2M page uses a PAT value with the bit 3 set due
2125 * to its overload with PG_PS.
2126 */
2127 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
2128 PAT_VALUE(1, PAT_WRITE_THROUGH) |
2129 PAT_VALUE(2, PAT_UNCACHED) |
2130 PAT_VALUE(3, PAT_UNCACHEABLE) |
2131 PAT_VALUE(4, PAT_WRITE_BACK) |
2132 PAT_VALUE(5, PAT_WRITE_PROTECTED) |
2133 PAT_VALUE(6, PAT_WRITE_COMBINING) |
2134 PAT_VALUE(7, PAT_UNCACHEABLE);
2135
2136 /* Disable PGE. */
2137 cr4 = rcr4();
2138 load_cr4(cr4 & ~CR4_PGE);
2139
2140 /* Disable caches (CD = 1, NW = 0). */
2141 cr0 = rcr0();
2142 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
2143
2144 /* Flushes caches and TLBs. */
2145 wbinvd();
2146 invltlb();
2147
2148 /* Update PAT and index table. */
2149 wrmsr(MSR_PAT, pat_msr);
2150
2151 /* Flush caches and TLBs again. */
2152 wbinvd();
2153 invltlb();
2154
2155 /* Restore caches and PGE. */
2156 load_cr0(cr0);
2157 load_cr4(cr4);
2158 }
2159
2160 vm_page_t
pmap_page_alloc_below_4g(bool zeroed)2161 pmap_page_alloc_below_4g(bool zeroed)
2162 {
2163 return (vm_page_alloc_noobj_contig((zeroed ? VM_ALLOC_ZERO : 0),
2164 1, 0, (1ULL << 32), PAGE_SIZE, 0, VM_MEMATTR_DEFAULT));
2165 }
2166
2167 extern const char la57_trampoline[], la57_trampoline_gdt_desc[],
2168 la57_trampoline_gdt[], la57_trampoline_end[];
2169
2170 static void
pmap_bootstrap_la57(void * arg __unused)2171 pmap_bootstrap_la57(void *arg __unused)
2172 {
2173 char *v_code;
2174 pml5_entry_t *v_pml5;
2175 pml4_entry_t *v_pml4;
2176 pdp_entry_t *v_pdp;
2177 pd_entry_t *v_pd;
2178 pt_entry_t *v_pt;
2179 vm_page_t m_code, m_pml4, m_pdp, m_pd, m_pt, m_pml5;
2180 void (*la57_tramp)(uint64_t pml5);
2181 struct region_descriptor r_gdt;
2182
2183 if ((cpu_stdext_feature2 & CPUID_STDEXT2_LA57) == 0)
2184 return;
2185 TUNABLE_INT_FETCH("vm.pmap.la57", &la57);
2186 if (!la57)
2187 return;
2188
2189 r_gdt.rd_limit = NGDT * sizeof(struct user_segment_descriptor) - 1;
2190 r_gdt.rd_base = (long)__pcpu[0].pc_gdt;
2191
2192 m_code = pmap_page_alloc_below_4g(true);
2193 v_code = (char *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_code));
2194 m_pml5 = pmap_page_alloc_below_4g(true);
2195 KPML5phys = VM_PAGE_TO_PHYS(m_pml5);
2196 v_pml5 = (pml5_entry_t *)PHYS_TO_DMAP(KPML5phys);
2197 m_pml4 = pmap_page_alloc_below_4g(true);
2198 v_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pml4));
2199 m_pdp = pmap_page_alloc_below_4g(true);
2200 v_pdp = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pdp));
2201 m_pd = pmap_page_alloc_below_4g(true);
2202 v_pd = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pd));
2203 m_pt = pmap_page_alloc_below_4g(true);
2204 v_pt = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m_pt));
2205
2206 /*
2207 * Map m_code 1:1, it appears below 4G in KVA due to physical
2208 * address being below 4G. Since kernel KVA is in upper half,
2209 * the pml4e should be zero and free for temporary use.
2210 */
2211 kernel_pmap->pm_pmltop[pmap_pml4e_index(VM_PAGE_TO_PHYS(m_code))] =
2212 VM_PAGE_TO_PHYS(m_pdp) | X86_PG_V | X86_PG_RW | X86_PG_A |
2213 X86_PG_M;
2214 v_pdp[pmap_pdpe_index(VM_PAGE_TO_PHYS(m_code))] =
2215 VM_PAGE_TO_PHYS(m_pd) | X86_PG_V | X86_PG_RW | X86_PG_A |
2216 X86_PG_M;
2217 v_pd[pmap_pde_index(VM_PAGE_TO_PHYS(m_code))] =
2218 VM_PAGE_TO_PHYS(m_pt) | X86_PG_V | X86_PG_RW | X86_PG_A |
2219 X86_PG_M;
2220 v_pt[pmap_pte_index(VM_PAGE_TO_PHYS(m_code))] =
2221 VM_PAGE_TO_PHYS(m_code) | X86_PG_V | X86_PG_RW | X86_PG_A |
2222 X86_PG_M;
2223
2224 /*
2225 * Add pml5 entry at top of KVA pointing to existing pml4 table,
2226 * entering all existing kernel mappings into level 5 table.
2227 */
2228 v_pml5[pmap_pml5e_index(UPT_MAX_ADDRESS)] = KPML4phys | X86_PG_V |
2229 X86_PG_RW | X86_PG_A | X86_PG_M;
2230
2231 /*
2232 * Add pml5 entry for 1:1 trampoline mapping after LA57 is turned on.
2233 */
2234 v_pml5[pmap_pml5e_index(VM_PAGE_TO_PHYS(m_code))] =
2235 VM_PAGE_TO_PHYS(m_pml4) | X86_PG_V | X86_PG_RW | X86_PG_A |
2236 X86_PG_M;
2237 v_pml4[pmap_pml4e_index(VM_PAGE_TO_PHYS(m_code))] =
2238 VM_PAGE_TO_PHYS(m_pdp) | X86_PG_V | X86_PG_RW | X86_PG_A |
2239 X86_PG_M;
2240
2241 /*
2242 * Copy and call the 48->57 trampoline, hope we return there, alive.
2243 */
2244 bcopy(la57_trampoline, v_code, la57_trampoline_end - la57_trampoline);
2245 *(u_long *)(v_code + 2 + (la57_trampoline_gdt_desc - la57_trampoline)) =
2246 la57_trampoline_gdt - la57_trampoline + VM_PAGE_TO_PHYS(m_code);
2247 la57_tramp = (void (*)(uint64_t))VM_PAGE_TO_PHYS(m_code);
2248 pmap_invalidate_all(kernel_pmap);
2249 if (bootverbose) {
2250 printf("entering LA57 trampoline at %#lx\n",
2251 (vm_offset_t)la57_tramp);
2252 }
2253 la57_tramp(KPML5phys);
2254
2255 /*
2256 * gdt was necessary reset, switch back to our gdt.
2257 */
2258 lgdt(&r_gdt);
2259 wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[0]);
2260 load_ds(_udatasel);
2261 load_es(_udatasel);
2262 load_fs(_ufssel);
2263 ssdtosyssd(&gdt_segs[GPROC0_SEL],
2264 (struct system_segment_descriptor *)&__pcpu[0].pc_gdt[GPROC0_SEL]);
2265 ltr(GSEL(GPROC0_SEL, SEL_KPL));
2266 lidt(&r_idt);
2267
2268 if (bootverbose)
2269 printf("LA57 trampoline returned, CR4 %#lx\n", rcr4());
2270
2271 /*
2272 * Now unmap the trampoline, and free the pages.
2273 * Clear pml5 entry used for 1:1 trampoline mapping.
2274 */
2275 pte_clear(&v_pml5[pmap_pml5e_index(VM_PAGE_TO_PHYS(m_code))]);
2276 invlpg((vm_offset_t)v_code);
2277 vm_page_free(m_code);
2278 vm_page_free(m_pdp);
2279 vm_page_free(m_pd);
2280 vm_page_free(m_pt);
2281
2282 /*
2283 * Recursively map PML5 to itself in order to get PTmap and
2284 * PDmap.
2285 */
2286 v_pml5[PML5PML5I] = KPML5phys | X86_PG_RW | X86_PG_V | pg_nx;
2287
2288 vtoptem = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT +
2289 NPML4EPGSHIFT + NPML5EPGSHIFT)) - 1) << 3;
2290 PTmap = (vm_offset_t)P5Tmap;
2291 vtopdem = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT +
2292 NPML4EPGSHIFT + NPML5EPGSHIFT)) - 1) << 3;
2293 PDmap = (vm_offset_t)P5Dmap;
2294
2295 kernel_pmap->pm_cr3 = KPML5phys;
2296 kernel_pmap->pm_pmltop = v_pml5;
2297 pmap_pt_page_count_adj(kernel_pmap, 1);
2298 }
2299 SYSINIT(la57, SI_SUB_KMEM, SI_ORDER_ANY, pmap_bootstrap_la57, NULL);
2300
2301 /*
2302 * Initialize a vm_page's machine-dependent fields.
2303 */
2304 void
pmap_page_init(vm_page_t m)2305 pmap_page_init(vm_page_t m)
2306 {
2307
2308 TAILQ_INIT(&m->md.pv_list);
2309 m->md.pat_mode = PAT_WRITE_BACK;
2310 }
2311
2312 static int pmap_allow_2m_x_ept;
2313 SYSCTL_INT(_vm_pmap, OID_AUTO, allow_2m_x_ept, CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
2314 &pmap_allow_2m_x_ept, 0,
2315 "Allow executable superpage mappings in EPT");
2316
2317 void
pmap_allow_2m_x_ept_recalculate(void)2318 pmap_allow_2m_x_ept_recalculate(void)
2319 {
2320 /*
2321 * SKL002, SKL012S. Since the EPT format is only used by
2322 * Intel CPUs, the vendor check is merely a formality.
2323 */
2324 if (!(cpu_vendor_id != CPU_VENDOR_INTEL ||
2325 (cpu_ia32_arch_caps & IA32_ARCH_CAP_IF_PSCHANGE_MC_NO) != 0 ||
2326 (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
2327 (CPUID_TO_MODEL(cpu_id) == 0x26 || /* Atoms */
2328 CPUID_TO_MODEL(cpu_id) == 0x27 ||
2329 CPUID_TO_MODEL(cpu_id) == 0x35 ||
2330 CPUID_TO_MODEL(cpu_id) == 0x36 ||
2331 CPUID_TO_MODEL(cpu_id) == 0x37 ||
2332 CPUID_TO_MODEL(cpu_id) == 0x86 ||
2333 CPUID_TO_MODEL(cpu_id) == 0x1c ||
2334 CPUID_TO_MODEL(cpu_id) == 0x4a ||
2335 CPUID_TO_MODEL(cpu_id) == 0x4c ||
2336 CPUID_TO_MODEL(cpu_id) == 0x4d ||
2337 CPUID_TO_MODEL(cpu_id) == 0x5a ||
2338 CPUID_TO_MODEL(cpu_id) == 0x5c ||
2339 CPUID_TO_MODEL(cpu_id) == 0x5d ||
2340 CPUID_TO_MODEL(cpu_id) == 0x5f ||
2341 CPUID_TO_MODEL(cpu_id) == 0x6e ||
2342 CPUID_TO_MODEL(cpu_id) == 0x7a ||
2343 CPUID_TO_MODEL(cpu_id) == 0x57 || /* Knights */
2344 CPUID_TO_MODEL(cpu_id) == 0x85))))
2345 pmap_allow_2m_x_ept = 1;
2346 #ifndef BURN_BRIDGES
2347 TUNABLE_INT_FETCH("hw.allow_2m_x_ept", &pmap_allow_2m_x_ept);
2348 #endif
2349 TUNABLE_INT_FETCH("vm.pmap.allow_2m_x_ept", &pmap_allow_2m_x_ept);
2350 }
2351
2352 static bool
pmap_allow_2m_x_page(pmap_t pmap,bool executable)2353 pmap_allow_2m_x_page(pmap_t pmap, bool executable)
2354 {
2355
2356 return (pmap->pm_type != PT_EPT || !executable ||
2357 !pmap_allow_2m_x_ept);
2358 }
2359
2360 #ifdef NUMA
2361 static void
pmap_init_pv_table(void)2362 pmap_init_pv_table(void)
2363 {
2364 struct pmap_large_md_page *pvd;
2365 vm_size_t s;
2366 long start, end, highest, pv_npg;
2367 int domain, i, j, pages;
2368
2369 /*
2370 * For correctness we depend on the size being evenly divisible into a
2371 * page. As a tradeoff between performance and total memory use, the
2372 * entry is 64 bytes (aka one cacheline) in size. Not being smaller
2373 * avoids false-sharing, but not being 128 bytes potentially allows for
2374 * avoidable traffic due to adjacent cacheline prefetcher.
2375 *
2376 * Assert the size so that accidental changes fail to compile.
2377 */
2378 CTASSERT((sizeof(*pvd) == 64));
2379
2380 /*
2381 * Calculate the size of the array.
2382 */
2383 pmap_last_pa = vm_phys_segs[vm_phys_nsegs - 1].end;
2384 pv_npg = howmany(pmap_last_pa, NBPDR);
2385 s = (vm_size_t)pv_npg * sizeof(struct pmap_large_md_page);
2386 s = round_page(s);
2387 pv_table = (struct pmap_large_md_page *)kva_alloc(s);
2388 if (pv_table == NULL)
2389 panic("%s: kva_alloc failed\n", __func__);
2390
2391 /*
2392 * Iterate physical segments to allocate space for respective pages.
2393 */
2394 highest = -1;
2395 s = 0;
2396 for (i = 0; i < vm_phys_nsegs; i++) {
2397 end = vm_phys_segs[i].end / NBPDR;
2398 domain = vm_phys_segs[i].domain;
2399
2400 if (highest >= end)
2401 continue;
2402
2403 start = highest + 1;
2404 pvd = &pv_table[start];
2405
2406 pages = end - start + 1;
2407 s = round_page(pages * sizeof(*pvd));
2408 highest = start + (s / sizeof(*pvd)) - 1;
2409
2410 for (j = 0; j < s; j += PAGE_SIZE) {
2411 vm_page_t m = vm_page_alloc_noobj_domain(domain, 0);
2412 if (m == NULL)
2413 panic("failed to allocate PV table page");
2414 pmap_qenter((vm_offset_t)pvd + j, &m, 1);
2415 }
2416
2417 for (j = 0; j < s / sizeof(*pvd); j++) {
2418 rw_init_flags(&pvd->pv_lock, "pmap pv list", RW_NEW);
2419 TAILQ_INIT(&pvd->pv_page.pv_list);
2420 pvd->pv_page.pv_gen = 0;
2421 pvd->pv_page.pat_mode = 0;
2422 pvd->pv_invl_gen = 0;
2423 pvd++;
2424 }
2425 }
2426 pvd = &pv_dummy_large;
2427 rw_init_flags(&pvd->pv_lock, "pmap pv list dummy", RW_NEW);
2428 TAILQ_INIT(&pvd->pv_page.pv_list);
2429 pvd->pv_page.pv_gen = 0;
2430 pvd->pv_page.pat_mode = 0;
2431 pvd->pv_invl_gen = 0;
2432 }
2433 #else
2434 static void
pmap_init_pv_table(void)2435 pmap_init_pv_table(void)
2436 {
2437 vm_size_t s;
2438 long i, pv_npg;
2439
2440 /*
2441 * Initialize the pool of pv list locks.
2442 */
2443 for (i = 0; i < NPV_LIST_LOCKS; i++)
2444 rw_init(&pv_list_locks[i], "pmap pv list");
2445
2446 /*
2447 * Calculate the size of the pv head table for superpages.
2448 */
2449 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
2450
2451 /*
2452 * Allocate memory for the pv head table for superpages.
2453 */
2454 s = (vm_size_t)pv_npg * sizeof(struct md_page);
2455 s = round_page(s);
2456 pv_table = kmem_malloc(s, M_WAITOK | M_ZERO);
2457 for (i = 0; i < pv_npg; i++)
2458 TAILQ_INIT(&pv_table[i].pv_list);
2459 TAILQ_INIT(&pv_dummy.pv_list);
2460 }
2461 #endif
2462
2463 /*
2464 * Initialize the pmap module.
2465 *
2466 * Called by vm_mem_init(), to initialize any structures that the pmap
2467 * system needs to map virtual memory.
2468 */
2469 void
pmap_init(void)2470 pmap_init(void)
2471 {
2472 struct pmap_preinit_mapping *ppim;
2473 vm_page_t m, mpte;
2474 int error, i, ret, skz63;
2475
2476 /* L1TF, reserve page @0 unconditionally */
2477 vm_page_blacklist_add(0, bootverbose);
2478
2479 /* Detect bare-metal Skylake Server and Skylake-X. */
2480 if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
2481 CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
2482 /*
2483 * Skylake-X errata SKZ63. Processor May Hang When
2484 * Executing Code In an HLE Transaction Region between
2485 * 40000000H and 403FFFFFH.
2486 *
2487 * Mark the pages in the range as preallocated. It
2488 * seems to be impossible to distinguish between
2489 * Skylake Server and Skylake X.
2490 */
2491 skz63 = 1;
2492 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
2493 if (skz63 != 0) {
2494 if (bootverbose)
2495 printf("SKZ63: skipping 4M RAM starting "
2496 "at physical 1G\n");
2497 for (i = 0; i < atop(0x400000); i++) {
2498 ret = vm_page_blacklist_add(0x40000000 +
2499 ptoa(i), false);
2500 if (!ret && bootverbose)
2501 printf("page at %#lx already used\n",
2502 0x40000000 + ptoa(i));
2503 }
2504 }
2505 }
2506
2507 /* IFU */
2508 pmap_allow_2m_x_ept_recalculate();
2509
2510 /*
2511 * Initialize the vm page array entries for the kernel pmap's
2512 * page table pages.
2513 */
2514 PMAP_LOCK(kernel_pmap);
2515 for (i = 0; i < nkpt; i++) {
2516 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
2517 KASSERT(mpte >= vm_page_array &&
2518 mpte < &vm_page_array[vm_page_array_size],
2519 ("pmap_init: page table page is out of range"));
2520 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
2521 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
2522 mpte->ref_count = 1;
2523
2524 /*
2525 * Collect the page table pages that were replaced by a 2MB
2526 * page in create_pagetables(). They are zero filled.
2527 */
2528 if ((i == 0 ||
2529 kernphys + ((vm_paddr_t)(i - 1) << PDRSHIFT) < KERNend) &&
2530 pmap_insert_pt_page(kernel_pmap, mpte, false, false))
2531 panic("pmap_init: pmap_insert_pt_page failed");
2532 }
2533 PMAP_UNLOCK(kernel_pmap);
2534 vm_wire_add(nkpt);
2535
2536 /*
2537 * If the kernel is running on a virtual machine, then it must assume
2538 * that MCA is enabled by the hypervisor. Moreover, the kernel must
2539 * be prepared for the hypervisor changing the vendor and family that
2540 * are reported by CPUID. Consequently, the workaround for AMD Family
2541 * 10h Erratum 383 is enabled if the processor's feature set does not
2542 * include at least one feature that is only supported by older Intel
2543 * or newer AMD processors.
2544 */
2545 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
2546 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
2547 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
2548 AMDID2_FMA4)) == 0)
2549 workaround_erratum383 = 1;
2550
2551 /*
2552 * Are large page mappings enabled?
2553 */
2554 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
2555 if (pg_ps_enabled) {
2556 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
2557 ("pmap_init: can't assign to pagesizes[1]"));
2558 pagesizes[1] = NBPDR;
2559 if ((amd_feature & AMDID_PAGE1GB) != 0) {
2560 KASSERT(MAXPAGESIZES > 2 && pagesizes[2] == 0,
2561 ("pmap_init: can't assign to pagesizes[2]"));
2562 pagesizes[2] = NBPDP;
2563 }
2564 }
2565
2566 /*
2567 * Initialize pv chunk lists.
2568 */
2569 for (i = 0; i < PMAP_MEMDOM; i++) {
2570 mtx_init(&pv_chunks[i].pvc_lock, "pmap pv chunk list", NULL, MTX_DEF);
2571 TAILQ_INIT(&pv_chunks[i].pvc_list);
2572 }
2573 pmap_init_pv_table();
2574
2575 pmap_initialized = 1;
2576 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
2577 ppim = pmap_preinit_mapping + i;
2578 if (ppim->va == 0)
2579 continue;
2580 /* Make the direct map consistent */
2581 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz <= dmaplimit) {
2582 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
2583 ppim->sz, ppim->mode);
2584 }
2585 if (!bootverbose)
2586 continue;
2587 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
2588 ppim->pa, ppim->va, ppim->sz, ppim->mode);
2589 }
2590
2591 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
2592 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
2593 (vmem_addr_t *)&qframe);
2594 if (error != 0)
2595 panic("qframe allocation failed");
2596
2597 lm_ents = 8;
2598 TUNABLE_INT_FETCH("vm.pmap.large_map_pml4_entries", &lm_ents);
2599 if (lm_ents > LMEPML4I - LMSPML4I + 1)
2600 lm_ents = LMEPML4I - LMSPML4I + 1;
2601 #ifdef KMSAN
2602 if (lm_ents > KMSANORIGPML4I - LMSPML4I) {
2603 printf(
2604 "pmap: shrinking large map for KMSAN (%d slots to %ld slots)\n",
2605 lm_ents, KMSANORIGPML4I - LMSPML4I);
2606 lm_ents = KMSANORIGPML4I - LMSPML4I;
2607 }
2608 #endif
2609 if (bootverbose)
2610 printf("pmap: large map %u PML4 slots (%lu GB)\n",
2611 lm_ents, (u_long)lm_ents * (NBPML4 / 1024 / 1024 / 1024));
2612 if (lm_ents != 0) {
2613 large_vmem = vmem_create("large", LARGEMAP_MIN_ADDRESS,
2614 (vmem_size_t)lm_ents * NBPML4, PAGE_SIZE, 0, M_WAITOK);
2615 if (large_vmem == NULL) {
2616 printf("pmap: cannot create large map\n");
2617 lm_ents = 0;
2618 }
2619 for (i = 0; i < lm_ents; i++) {
2620 m = pmap_large_map_getptp_unlocked();
2621 /* XXXKIB la57 */
2622 kernel_pml4[LMSPML4I + i] = X86_PG_V |
2623 X86_PG_RW | X86_PG_A | X86_PG_M | pg_nx |
2624 VM_PAGE_TO_PHYS(m);
2625 }
2626 }
2627 }
2628
2629 SYSCTL_UINT(_vm_pmap, OID_AUTO, large_map_pml4_entries,
2630 CTLFLAG_RDTUN | CTLFLAG_NOFETCH, &lm_ents, 0,
2631 "Maximum number of PML4 entries for use by large map (tunable). "
2632 "Each entry corresponds to 512GB of address space.");
2633
2634 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2635 "2MB page mapping counters");
2636
2637 static COUNTER_U64_DEFINE_EARLY(pmap_pde_demotions);
2638 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, demotions,
2639 CTLFLAG_RD, &pmap_pde_demotions, "2MB page demotions");
2640
2641 static COUNTER_U64_DEFINE_EARLY(pmap_pde_mappings);
2642 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
2643 &pmap_pde_mappings, "2MB page mappings");
2644
2645 static COUNTER_U64_DEFINE_EARLY(pmap_pde_p_failures);
2646 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
2647 &pmap_pde_p_failures, "2MB page promotion failures");
2648
2649 static COUNTER_U64_DEFINE_EARLY(pmap_pde_promotions);
2650 SYSCTL_COUNTER_U64(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
2651 &pmap_pde_promotions, "2MB page promotions");
2652
2653 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
2654 "1GB page mapping counters");
2655
2656 static COUNTER_U64_DEFINE_EARLY(pmap_pdpe_demotions);
2657 SYSCTL_COUNTER_U64(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
2658 &pmap_pdpe_demotions, "1GB page demotions");
2659
2660 /***************************************************
2661 * Low level helper routines.....
2662 ***************************************************/
2663
2664 static pt_entry_t
pmap_swap_pat(pmap_t pmap,pt_entry_t entry)2665 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
2666 {
2667 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
2668
2669 switch (pmap->pm_type) {
2670 case PT_X86:
2671 case PT_RVI:
2672 /* Verify that both PAT bits are not set at the same time */
2673 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
2674 ("Invalid PAT bits in entry %#lx", entry));
2675
2676 /* Swap the PAT bits if one of them is set */
2677 if ((entry & x86_pat_bits) != 0)
2678 entry ^= x86_pat_bits;
2679 break;
2680 case PT_EPT:
2681 /*
2682 * Nothing to do - the memory attributes are represented
2683 * the same way for regular pages and superpages.
2684 */
2685 break;
2686 default:
2687 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
2688 }
2689
2690 return (entry);
2691 }
2692
2693 bool
pmap_is_valid_memattr(pmap_t pmap __unused,vm_memattr_t mode)2694 pmap_is_valid_memattr(pmap_t pmap __unused, vm_memattr_t mode)
2695 {
2696
2697 return (mode >= 0 && mode < PAT_INDEX_SIZE &&
2698 pat_index[(int)mode] >= 0);
2699 }
2700
2701 /*
2702 * Determine the appropriate bits to set in a PTE or PDE for a specified
2703 * caching mode.
2704 */
2705 int
pmap_cache_bits(pmap_t pmap,int mode,bool is_pde)2706 pmap_cache_bits(pmap_t pmap, int mode, bool is_pde)
2707 {
2708 int cache_bits, pat_flag, pat_idx;
2709
2710 if (!pmap_is_valid_memattr(pmap, mode))
2711 panic("Unknown caching mode %d\n", mode);
2712
2713 switch (pmap->pm_type) {
2714 case PT_X86:
2715 case PT_RVI:
2716 /* The PAT bit is different for PTE's and PDE's. */
2717 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
2718
2719 /* Map the caching mode to a PAT index. */
2720 pat_idx = pat_index[mode];
2721
2722 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
2723 cache_bits = 0;
2724 if (pat_idx & 0x4)
2725 cache_bits |= pat_flag;
2726 if (pat_idx & 0x2)
2727 cache_bits |= PG_NC_PCD;
2728 if (pat_idx & 0x1)
2729 cache_bits |= PG_NC_PWT;
2730 break;
2731
2732 case PT_EPT:
2733 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
2734 break;
2735
2736 default:
2737 panic("unsupported pmap type %d", pmap->pm_type);
2738 }
2739
2740 return (cache_bits);
2741 }
2742
2743 static int
pmap_cache_mask(pmap_t pmap,bool is_pde)2744 pmap_cache_mask(pmap_t pmap, bool is_pde)
2745 {
2746 int mask;
2747
2748 switch (pmap->pm_type) {
2749 case PT_X86:
2750 case PT_RVI:
2751 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
2752 break;
2753 case PT_EPT:
2754 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
2755 break;
2756 default:
2757 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
2758 }
2759
2760 return (mask);
2761 }
2762
2763 static int
pmap_pat_index(pmap_t pmap,pt_entry_t pte,bool is_pde)2764 pmap_pat_index(pmap_t pmap, pt_entry_t pte, bool is_pde)
2765 {
2766 int pat_flag, pat_idx;
2767
2768 pat_idx = 0;
2769 switch (pmap->pm_type) {
2770 case PT_X86:
2771 case PT_RVI:
2772 /* The PAT bit is different for PTE's and PDE's. */
2773 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
2774
2775 if ((pte & pat_flag) != 0)
2776 pat_idx |= 0x4;
2777 if ((pte & PG_NC_PCD) != 0)
2778 pat_idx |= 0x2;
2779 if ((pte & PG_NC_PWT) != 0)
2780 pat_idx |= 0x1;
2781 break;
2782 case PT_EPT:
2783 if ((pte & EPT_PG_IGNORE_PAT) != 0)
2784 panic("EPT PTE %#lx has no PAT memory type", pte);
2785 pat_idx = (pte & EPT_PG_MEMORY_TYPE(0x7)) >> 3;
2786 break;
2787 }
2788
2789 /* See pmap_init_pat(). */
2790 if (pat_idx == 4)
2791 pat_idx = 0;
2792 if (pat_idx == 7)
2793 pat_idx = 3;
2794
2795 return (pat_idx);
2796 }
2797
2798 bool
pmap_ps_enabled(pmap_t pmap)2799 pmap_ps_enabled(pmap_t pmap)
2800 {
2801
2802 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
2803 }
2804
2805 static void
pmap_update_pde_store(pmap_t pmap,pd_entry_t * pde,pd_entry_t newpde)2806 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
2807 {
2808
2809 switch (pmap->pm_type) {
2810 case PT_X86:
2811 break;
2812 case PT_RVI:
2813 case PT_EPT:
2814 /*
2815 * XXX
2816 * This is a little bogus since the generation number is
2817 * supposed to be bumped up when a region of the address
2818 * space is invalidated in the page tables.
2819 *
2820 * In this case the old PDE entry is valid but yet we want
2821 * to make sure that any mappings using the old entry are
2822 * invalidated in the TLB.
2823 *
2824 * The reason this works as expected is because we rendezvous
2825 * "all" host cpus and force any vcpu context to exit as a
2826 * side-effect.
2827 */
2828 atomic_add_long(&pmap->pm_eptgen, 1);
2829 break;
2830 default:
2831 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
2832 }
2833 pde_store(pde, newpde);
2834 }
2835
2836 /*
2837 * After changing the page size for the specified virtual address in the page
2838 * table, flush the corresponding entries from the processor's TLB. Only the
2839 * calling processor's TLB is affected.
2840 *
2841 * The calling thread must be pinned to a processor.
2842 */
2843 static void
pmap_update_pde_invalidate(pmap_t pmap,vm_offset_t va,pd_entry_t newpde)2844 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
2845 {
2846 pt_entry_t PG_G;
2847
2848 if (pmap_type_guest(pmap))
2849 return;
2850
2851 KASSERT(pmap->pm_type == PT_X86,
2852 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
2853
2854 PG_G = pmap_global_bit(pmap);
2855
2856 if ((newpde & PG_PS) == 0)
2857 /* Demotion: flush a specific 2MB page mapping. */
2858 pmap_invlpg(pmap, va);
2859 else if ((newpde & PG_G) == 0)
2860 /*
2861 * Promotion: flush every 4KB page mapping from the TLB
2862 * because there are too many to flush individually.
2863 */
2864 invltlb();
2865 else {
2866 /*
2867 * Promotion: flush every 4KB page mapping from the TLB,
2868 * including any global (PG_G) mappings.
2869 */
2870 invltlb_glob();
2871 }
2872 }
2873
2874 /*
2875 * The amd64 pmap uses different approaches to TLB invalidation
2876 * depending on the kernel configuration, available hardware features,
2877 * and known hardware errata. The kernel configuration option that
2878 * has the greatest operational impact on TLB invalidation is PTI,
2879 * which is enabled automatically on affected Intel CPUs. The most
2880 * impactful hardware features are first PCID, and then INVPCID
2881 * instruction presence. PCID usage is quite different for PTI
2882 * vs. non-PTI.
2883 *
2884 * * Kernel Page Table Isolation (PTI or KPTI) is used to mitigate
2885 * the Meltdown bug in some Intel CPUs. Under PTI, each user address
2886 * space is served by two page tables, user and kernel. The user
2887 * page table only maps user space and a kernel trampoline. The
2888 * kernel trampoline includes the entirety of the kernel text but
2889 * only the kernel data that is needed to switch from user to kernel
2890 * mode. The kernel page table maps the user and kernel address
2891 * spaces in their entirety. It is identical to the per-process
2892 * page table used in non-PTI mode.
2893 *
2894 * User page tables are only used when the CPU is in user mode.
2895 * Consequently, some TLB invalidations can be postponed until the
2896 * switch from kernel to user mode. In contrast, the user
2897 * space part of the kernel page table is used for copyout(9), so
2898 * TLB invalidations on this page table cannot be similarly postponed.
2899 *
2900 * The existence of a user mode page table for the given pmap is
2901 * indicated by a pm_ucr3 value that differs from PMAP_NO_CR3, in
2902 * which case pm_ucr3 contains the %cr3 register value for the user
2903 * mode page table's root.
2904 *
2905 * * The pm_active bitmask indicates which CPUs currently have the
2906 * pmap active. A CPU's bit is set on context switch to the pmap, and
2907 * cleared on switching off this CPU. For the kernel page table,
2908 * the pm_active field is immutable and contains all CPUs. The
2909 * kernel page table is always logically active on every processor,
2910 * but not necessarily in use by the hardware, e.g., in PTI mode.
2911 *
2912 * When requesting invalidation of virtual addresses with
2913 * pmap_invalidate_XXX() functions, the pmap sends shootdown IPIs to
2914 * all CPUs recorded as active in pm_active. Updates to and reads
2915 * from pm_active are not synchronized, and so they may race with
2916 * each other. Shootdown handlers are prepared to handle the race.
2917 *
2918 * * PCID is an optional feature of the long mode x86 MMU where TLB
2919 * entries are tagged with the 'Process ID' of the address space
2920 * they belong to. This feature provides a limited namespace for
2921 * process identifiers, 12 bits, supporting 4095 simultaneous IDs
2922 * total.
2923 *
2924 * Allocation of a PCID to a pmap is done by an algorithm described
2925 * in section 15.12, "Other TLB Consistency Algorithms", of
2926 * Vahalia's book "Unix Internals". A PCID cannot be allocated for
2927 * the whole lifetime of a pmap in pmap_pinit() due to the limited
2928 * namespace. Instead, a per-CPU, per-pmap PCID is assigned when
2929 * the CPU is about to start caching TLB entries from a pmap,
2930 * i.e., on the context switch that activates the pmap on the CPU.
2931 *
2932 * The PCID allocator maintains a per-CPU, per-pmap generation
2933 * count, pm_gen, which is incremented each time a new PCID is
2934 * allocated. On TLB invalidation, the generation counters for the
2935 * pmap are zeroed, which signals the context switch code that the
2936 * previously allocated PCID is no longer valid. Effectively,
2937 * zeroing any of these counters triggers a TLB shootdown for the
2938 * given CPU/address space, due to the allocation of a new PCID.
2939 *
2940 * Zeroing can be performed remotely. Consequently, if a pmap is
2941 * inactive on a CPU, then a TLB shootdown for that pmap and CPU can
2942 * be initiated by an ordinary memory access to reset the target
2943 * CPU's generation count within the pmap. The CPU initiating the
2944 * TLB shootdown does not need to send an IPI to the target CPU.
2945 *
2946 * * PTI + PCID. The available PCIDs are divided into two sets: PCIDs
2947 * for complete (kernel) page tables, and PCIDs for user mode page
2948 * tables. A user PCID value is obtained from the kernel PCID value
2949 * by setting the highest bit, 11, to 1 (0x800 == PMAP_PCID_USER_PT).
2950 *
2951 * User space page tables are activated on return to user mode, by
2952 * loading pm_ucr3 into %cr3. If the PCPU(ucr3_load_mask) requests
2953 * clearing bit 63 of the loaded ucr3, this effectively causes
2954 * complete invalidation of the user mode TLB entries for the
2955 * current pmap. In which case, local invalidations of individual
2956 * pages in the user page table are skipped.
2957 *
2958 * * Local invalidation, all modes. If the requested invalidation is
2959 * for a specific address or the total invalidation of a currently
2960 * active pmap, then the TLB is flushed using INVLPG for a kernel
2961 * page table, and INVPCID(INVPCID_CTXGLOB)/invltlb_glob() for a
2962 * user space page table(s).
2963 *
2964 * If the INVPCID instruction is available, it is used to flush user
2965 * entries from the kernel page table.
2966 *
2967 * When PCID is enabled, the INVLPG instruction invalidates all TLB
2968 * entries for the given page that either match the current PCID or
2969 * are global. Since TLB entries for the same page under different
2970 * PCIDs are unaffected, kernel pages which reside in all address
2971 * spaces could be problematic. We avoid the problem by creating
2972 * all kernel PTEs with the global flag (PG_G) set, when PTI is
2973 * disabled.
2974 *
2975 * * mode: PTI disabled, PCID present. The kernel reserves PCID 0 for its
2976 * address space, all other 4095 PCIDs are used for user mode spaces
2977 * as described above. A context switch allocates a new PCID if
2978 * the recorded PCID is zero or the recorded generation does not match
2979 * the CPU's generation, effectively flushing the TLB for this address space.
2980 * Total remote invalidation is performed by zeroing pm_gen for all CPUs.
2981 * local user page: INVLPG
2982 * local kernel page: INVLPG
2983 * local user total: INVPCID(CTX)
2984 * local kernel total: INVPCID(CTXGLOB) or invltlb_glob()
2985 * remote user page, inactive pmap: zero pm_gen
2986 * remote user page, active pmap: zero pm_gen + IPI:INVLPG
2987 * (Both actions are required to handle the aforementioned pm_active races.)
2988 * remote kernel page: IPI:INVLPG
2989 * remote user total, inactive pmap: zero pm_gen
2990 * remote user total, active pmap: zero pm_gen + IPI:(INVPCID(CTX) or
2991 * reload %cr3)
2992 * (See note above about pm_active races.)
2993 * remote kernel total: IPI:(INVPCID(CTXGLOB) or invltlb_glob())
2994 *
2995 * PTI enabled, PCID present.
2996 * local user page: INVLPG for kpt, INVPCID(ADDR) or (INVLPG for ucr3)
2997 * for upt
2998 * local kernel page: INVLPG
2999 * local user total: INVPCID(CTX) or reload %cr3 for kpt, clear PCID_SAVE
3000 * on loading UCR3 into %cr3 for upt
3001 * local kernel total: INVPCID(CTXGLOB) or invltlb_glob()
3002 * remote user page, inactive pmap: zero pm_gen
3003 * remote user page, active pmap: zero pm_gen + IPI:(INVLPG for kpt,
3004 * INVPCID(ADDR) for upt)
3005 * remote kernel page: IPI:INVLPG
3006 * remote user total, inactive pmap: zero pm_gen
3007 * remote user total, active pmap: zero pm_gen + IPI:(INVPCID(CTX) for kpt,
3008 * clear PCID_SAVE on loading UCR3 into $cr3 for upt)
3009 * remote kernel total: IPI:(INVPCID(CTXGLOB) or invltlb_glob())
3010 *
3011 * No PCID.
3012 * local user page: INVLPG
3013 * local kernel page: INVLPG
3014 * local user total: reload %cr3
3015 * local kernel total: invltlb_glob()
3016 * remote user page, inactive pmap: -
3017 * remote user page, active pmap: IPI:INVLPG
3018 * remote kernel page: IPI:INVLPG
3019 * remote user total, inactive pmap: -
3020 * remote user total, active pmap: IPI:(reload %cr3)
3021 * remote kernel total: IPI:invltlb_glob()
3022 * Since on return to user mode, the reload of %cr3 with ucr3 causes
3023 * TLB invalidation, no specific action is required for user page table.
3024 *
3025 * EPT. EPT pmaps do not map KVA, all mappings are userspace.
3026 * XXX TODO
3027 */
3028
3029 #ifdef SMP
3030 /*
3031 * Interrupt the cpus that are executing in the guest context.
3032 * This will force the vcpu to exit and the cached EPT mappings
3033 * will be invalidated by the host before the next vmresume.
3034 */
3035 static __inline void
pmap_invalidate_ept(pmap_t pmap)3036 pmap_invalidate_ept(pmap_t pmap)
3037 {
3038 smr_seq_t goal;
3039 int ipinum;
3040
3041 sched_pin();
3042 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
3043 ("pmap_invalidate_ept: absurd pm_active"));
3044
3045 /*
3046 * The TLB mappings associated with a vcpu context are not
3047 * flushed each time a different vcpu is chosen to execute.
3048 *
3049 * This is in contrast with a process's vtop mappings that
3050 * are flushed from the TLB on each context switch.
3051 *
3052 * Therefore we need to do more than just a TLB shootdown on
3053 * the active cpus in 'pmap->pm_active'. To do this we keep
3054 * track of the number of invalidations performed on this pmap.
3055 *
3056 * Each vcpu keeps a cache of this counter and compares it
3057 * just before a vmresume. If the counter is out-of-date an
3058 * invept will be done to flush stale mappings from the TLB.
3059 *
3060 * To ensure that all vCPU threads have observed the new counter
3061 * value before returning, we use SMR. Ordering is important here:
3062 * the VMM enters an SMR read section before loading the counter
3063 * and after updating the pm_active bit set. Thus, pm_active is
3064 * a superset of active readers, and any reader that has observed
3065 * the goal has observed the new counter value.
3066 */
3067 atomic_add_long(&pmap->pm_eptgen, 1);
3068
3069 goal = smr_advance(pmap->pm_eptsmr);
3070
3071 /*
3072 * Force the vcpu to exit and trap back into the hypervisor.
3073 */
3074 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
3075 ipi_selected(pmap->pm_active, ipinum);
3076 sched_unpin();
3077
3078 /*
3079 * Ensure that all active vCPUs will observe the new generation counter
3080 * value before executing any more guest instructions.
3081 */
3082 smr_wait(pmap->pm_eptsmr, goal);
3083 }
3084
3085 static inline void
pmap_invalidate_preipi_pcid(pmap_t pmap)3086 pmap_invalidate_preipi_pcid(pmap_t pmap)
3087 {
3088 struct pmap_pcid *pcidp;
3089 u_int cpuid, i;
3090
3091 sched_pin();
3092
3093 cpuid = PCPU_GET(cpuid);
3094 if (pmap != PCPU_GET(curpmap))
3095 cpuid = 0xffffffff; /* An impossible value */
3096
3097 CPU_FOREACH(i) {
3098 if (cpuid != i) {
3099 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, i);
3100 pcidp->pm_gen = 0;
3101 }
3102 }
3103
3104 /*
3105 * The fence is between stores to pm_gen and the read of the
3106 * pm_active mask. We need to ensure that it is impossible
3107 * for us to miss the bit update in pm_active and
3108 * simultaneously observe a non-zero pm_gen in
3109 * pmap_activate_sw(), otherwise TLB update is missed.
3110 * Without the fence, IA32 allows such an outcome. Note that
3111 * pm_active is updated by a locked operation, which provides
3112 * the reciprocal fence.
3113 */
3114 atomic_thread_fence_seq_cst();
3115 }
3116
3117 static void
pmap_invalidate_preipi_nopcid(pmap_t pmap __unused)3118 pmap_invalidate_preipi_nopcid(pmap_t pmap __unused)
3119 {
3120 sched_pin();
3121 }
3122
3123 DEFINE_IFUNC(static, void, pmap_invalidate_preipi, (pmap_t))
3124 {
3125 return (pmap_pcid_enabled ? pmap_invalidate_preipi_pcid :
3126 pmap_invalidate_preipi_nopcid);
3127 }
3128
3129 static inline void
pmap_invalidate_page_pcid_cb(pmap_t pmap,vm_offset_t va,const bool invpcid_works1)3130 pmap_invalidate_page_pcid_cb(pmap_t pmap, vm_offset_t va,
3131 const bool invpcid_works1)
3132 {
3133 struct invpcid_descr d;
3134 uint64_t kcr3, ucr3;
3135 uint32_t pcid;
3136
3137 /*
3138 * Because pm_pcid is recalculated on a context switch, we
3139 * must ensure there is no preemption, not just pinning.
3140 * Otherwise, we might use a stale value below.
3141 */
3142 CRITICAL_ASSERT(curthread);
3143
3144 /*
3145 * No need to do anything with user page tables invalidation
3146 * if there is no user page table, or invalidation is deferred
3147 * until the return to userspace. ucr3_load_mask is stable
3148 * because we have preemption disabled.
3149 */
3150 if (pmap->pm_ucr3 == PMAP_NO_CR3 ||
3151 PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK)
3152 return;
3153
3154 pcid = pmap_get_pcid(pmap);
3155 if (invpcid_works1) {
3156 d.pcid = pcid | PMAP_PCID_USER_PT;
3157 d.pad = 0;
3158 d.addr = va;
3159 invpcid(&d, INVPCID_ADDR);
3160 } else {
3161 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3162 ucr3 = pmap->pm_ucr3 | pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3163 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
3164 }
3165 }
3166
3167 static void
pmap_invalidate_page_pcid_invpcid_cb(pmap_t pmap,vm_offset_t va)3168 pmap_invalidate_page_pcid_invpcid_cb(pmap_t pmap, vm_offset_t va)
3169 {
3170 pmap_invalidate_page_pcid_cb(pmap, va, true);
3171 }
3172
3173 static void
pmap_invalidate_page_pcid_noinvpcid_cb(pmap_t pmap,vm_offset_t va)3174 pmap_invalidate_page_pcid_noinvpcid_cb(pmap_t pmap, vm_offset_t va)
3175 {
3176 pmap_invalidate_page_pcid_cb(pmap, va, false);
3177 }
3178
3179 static void
pmap_invalidate_page_nopcid_cb(pmap_t pmap __unused,vm_offset_t va __unused)3180 pmap_invalidate_page_nopcid_cb(pmap_t pmap __unused, vm_offset_t va __unused)
3181 {
3182 }
3183
3184 DEFINE_IFUNC(static, void, pmap_invalidate_page_cb, (pmap_t, vm_offset_t))
3185 {
3186 if (pmap_pcid_enabled)
3187 return (invpcid_works ? pmap_invalidate_page_pcid_invpcid_cb :
3188 pmap_invalidate_page_pcid_noinvpcid_cb);
3189 return (pmap_invalidate_page_nopcid_cb);
3190 }
3191
3192 static void
pmap_invalidate_page_curcpu_cb(pmap_t pmap,vm_offset_t va,vm_offset_t addr2 __unused)3193 pmap_invalidate_page_curcpu_cb(pmap_t pmap, vm_offset_t va,
3194 vm_offset_t addr2 __unused)
3195 {
3196 if (pmap == kernel_pmap) {
3197 pmap_invlpg(kernel_pmap, va);
3198 } else if (pmap == PCPU_GET(curpmap)) {
3199 invlpg(va);
3200 pmap_invalidate_page_cb(pmap, va);
3201 }
3202 }
3203
3204 void
pmap_invalidate_page(pmap_t pmap,vm_offset_t va)3205 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
3206 {
3207 if (pmap_type_guest(pmap)) {
3208 pmap_invalidate_ept(pmap);
3209 return;
3210 }
3211
3212 KASSERT(pmap->pm_type == PT_X86,
3213 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
3214
3215 pmap_invalidate_preipi(pmap);
3216 smp_masked_invlpg(va, pmap, pmap_invalidate_page_curcpu_cb);
3217 }
3218
3219 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
3220 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
3221
3222 static void
pmap_invalidate_range_pcid_cb(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,const bool invpcid_works1)3223 pmap_invalidate_range_pcid_cb(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
3224 const bool invpcid_works1)
3225 {
3226 struct invpcid_descr d;
3227 uint64_t kcr3, ucr3;
3228 uint32_t pcid;
3229
3230 CRITICAL_ASSERT(curthread);
3231
3232 if (pmap != PCPU_GET(curpmap) ||
3233 pmap->pm_ucr3 == PMAP_NO_CR3 ||
3234 PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK)
3235 return;
3236
3237 pcid = pmap_get_pcid(pmap);
3238 if (invpcid_works1) {
3239 d.pcid = pcid | PMAP_PCID_USER_PT;
3240 d.pad = 0;
3241 for (d.addr = sva; d.addr < eva; d.addr += PAGE_SIZE)
3242 invpcid(&d, INVPCID_ADDR);
3243 } else {
3244 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3245 ucr3 = pmap->pm_ucr3 | pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3246 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
3247 }
3248 }
3249
3250 static void
pmap_invalidate_range_pcid_invpcid_cb(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)3251 pmap_invalidate_range_pcid_invpcid_cb(pmap_t pmap, vm_offset_t sva,
3252 vm_offset_t eva)
3253 {
3254 pmap_invalidate_range_pcid_cb(pmap, sva, eva, true);
3255 }
3256
3257 static void
pmap_invalidate_range_pcid_noinvpcid_cb(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)3258 pmap_invalidate_range_pcid_noinvpcid_cb(pmap_t pmap, vm_offset_t sva,
3259 vm_offset_t eva)
3260 {
3261 pmap_invalidate_range_pcid_cb(pmap, sva, eva, false);
3262 }
3263
3264 static void
pmap_invalidate_range_nopcid_cb(pmap_t pmap __unused,vm_offset_t sva __unused,vm_offset_t eva __unused)3265 pmap_invalidate_range_nopcid_cb(pmap_t pmap __unused, vm_offset_t sva __unused,
3266 vm_offset_t eva __unused)
3267 {
3268 }
3269
3270 DEFINE_IFUNC(static, void, pmap_invalidate_range_cb, (pmap_t, vm_offset_t,
3271 vm_offset_t))
3272 {
3273 if (pmap_pcid_enabled)
3274 return (invpcid_works ? pmap_invalidate_range_pcid_invpcid_cb :
3275 pmap_invalidate_range_pcid_noinvpcid_cb);
3276 return (pmap_invalidate_range_nopcid_cb);
3277 }
3278
3279 static void
pmap_invalidate_range_curcpu_cb(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)3280 pmap_invalidate_range_curcpu_cb(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3281 {
3282 vm_offset_t addr;
3283
3284 if (pmap == kernel_pmap) {
3285 if (PCPU_GET(pcid_invlpg_workaround)) {
3286 struct invpcid_descr d = { 0 };
3287
3288 invpcid(&d, INVPCID_CTXGLOB);
3289 } else {
3290 for (addr = sva; addr < eva; addr += PAGE_SIZE)
3291 invlpg(addr);
3292 }
3293 } else if (pmap == PCPU_GET(curpmap)) {
3294 for (addr = sva; addr < eva; addr += PAGE_SIZE)
3295 invlpg(addr);
3296 pmap_invalidate_range_cb(pmap, sva, eva);
3297 }
3298 }
3299
3300 void
pmap_invalidate_range(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)3301 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3302 {
3303 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
3304 pmap_invalidate_all(pmap);
3305 return;
3306 }
3307
3308 if (pmap_type_guest(pmap)) {
3309 pmap_invalidate_ept(pmap);
3310 return;
3311 }
3312
3313 KASSERT(pmap->pm_type == PT_X86,
3314 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
3315
3316 pmap_invalidate_preipi(pmap);
3317 smp_masked_invlpg_range(sva, eva, pmap,
3318 pmap_invalidate_range_curcpu_cb);
3319 }
3320
3321 static inline void
pmap_invalidate_all_pcid_cb(pmap_t pmap,bool invpcid_works1)3322 pmap_invalidate_all_pcid_cb(pmap_t pmap, bool invpcid_works1)
3323 {
3324 struct invpcid_descr d;
3325 uint64_t kcr3;
3326 uint32_t pcid;
3327
3328 if (pmap == kernel_pmap) {
3329 if (invpcid_works1) {
3330 bzero(&d, sizeof(d));
3331 invpcid(&d, INVPCID_CTXGLOB);
3332 } else {
3333 invltlb_glob();
3334 }
3335 } else if (pmap == PCPU_GET(curpmap)) {
3336 CRITICAL_ASSERT(curthread);
3337
3338 pcid = pmap_get_pcid(pmap);
3339 if (invpcid_works1) {
3340 d.pcid = pcid;
3341 d.pad = 0;
3342 d.addr = 0;
3343 invpcid(&d, INVPCID_CTX);
3344 } else {
3345 kcr3 = pmap->pm_cr3 | pcid;
3346 load_cr3(kcr3);
3347 }
3348 if (pmap->pm_ucr3 != PMAP_NO_CR3)
3349 PCPU_SET(ucr3_load_mask, ~CR3_PCID_SAVE);
3350 }
3351 }
3352
3353 static void
pmap_invalidate_all_pcid_invpcid_cb(pmap_t pmap)3354 pmap_invalidate_all_pcid_invpcid_cb(pmap_t pmap)
3355 {
3356 pmap_invalidate_all_pcid_cb(pmap, true);
3357 }
3358
3359 static void
pmap_invalidate_all_pcid_noinvpcid_cb(pmap_t pmap)3360 pmap_invalidate_all_pcid_noinvpcid_cb(pmap_t pmap)
3361 {
3362 pmap_invalidate_all_pcid_cb(pmap, false);
3363 }
3364
3365 static void
pmap_invalidate_all_nopcid_cb(pmap_t pmap)3366 pmap_invalidate_all_nopcid_cb(pmap_t pmap)
3367 {
3368 if (pmap == kernel_pmap)
3369 invltlb_glob();
3370 else if (pmap == PCPU_GET(curpmap))
3371 invltlb();
3372 }
3373
3374 DEFINE_IFUNC(static, void, pmap_invalidate_all_cb, (pmap_t))
3375 {
3376 if (pmap_pcid_enabled)
3377 return (invpcid_works ? pmap_invalidate_all_pcid_invpcid_cb :
3378 pmap_invalidate_all_pcid_noinvpcid_cb);
3379 return (pmap_invalidate_all_nopcid_cb);
3380 }
3381
3382 static void
pmap_invalidate_all_curcpu_cb(pmap_t pmap,vm_offset_t addr1 __unused,vm_offset_t addr2 __unused)3383 pmap_invalidate_all_curcpu_cb(pmap_t pmap, vm_offset_t addr1 __unused,
3384 vm_offset_t addr2 __unused)
3385 {
3386 pmap_invalidate_all_cb(pmap);
3387 }
3388
3389 void
pmap_invalidate_all(pmap_t pmap)3390 pmap_invalidate_all(pmap_t pmap)
3391 {
3392 if (pmap_type_guest(pmap)) {
3393 pmap_invalidate_ept(pmap);
3394 return;
3395 }
3396
3397 KASSERT(pmap->pm_type == PT_X86,
3398 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
3399
3400 pmap_invalidate_preipi(pmap);
3401 smp_masked_invltlb(pmap, pmap_invalidate_all_curcpu_cb);
3402 }
3403
3404 static void
pmap_invalidate_cache_curcpu_cb(pmap_t pmap __unused,vm_offset_t va __unused,vm_offset_t addr2 __unused)3405 pmap_invalidate_cache_curcpu_cb(pmap_t pmap __unused, vm_offset_t va __unused,
3406 vm_offset_t addr2 __unused)
3407 {
3408 wbinvd();
3409 }
3410
3411 void
pmap_invalidate_cache(void)3412 pmap_invalidate_cache(void)
3413 {
3414 sched_pin();
3415 smp_cache_flush(pmap_invalidate_cache_curcpu_cb);
3416 }
3417
3418 struct pde_action {
3419 cpuset_t invalidate; /* processors that invalidate their TLB */
3420 pmap_t pmap;
3421 vm_offset_t va;
3422 pd_entry_t *pde;
3423 pd_entry_t newpde;
3424 u_int store; /* processor that updates the PDE */
3425 };
3426
3427 static void
pmap_update_pde_action(void * arg)3428 pmap_update_pde_action(void *arg)
3429 {
3430 struct pde_action *act = arg;
3431
3432 if (act->store == PCPU_GET(cpuid))
3433 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
3434 }
3435
3436 static void
pmap_update_pde_teardown(void * arg)3437 pmap_update_pde_teardown(void *arg)
3438 {
3439 struct pde_action *act = arg;
3440
3441 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
3442 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
3443 }
3444
3445 /*
3446 * Change the page size for the specified virtual address in a way that
3447 * prevents any possibility of the TLB ever having two entries that map the
3448 * same virtual address using different page sizes. This is the recommended
3449 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
3450 * machine check exception for a TLB state that is improperly diagnosed as a
3451 * hardware error.
3452 */
3453 static void
pmap_update_pde(pmap_t pmap,vm_offset_t va,pd_entry_t * pde,pd_entry_t newpde)3454 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
3455 {
3456 struct pde_action act;
3457 cpuset_t active, other_cpus;
3458 u_int cpuid;
3459
3460 sched_pin();
3461 cpuid = PCPU_GET(cpuid);
3462 other_cpus = all_cpus;
3463 CPU_CLR(cpuid, &other_cpus);
3464 if (pmap == kernel_pmap || pmap_type_guest(pmap))
3465 active = all_cpus;
3466 else {
3467 active = pmap->pm_active;
3468 }
3469 if (CPU_OVERLAP(&active, &other_cpus)) {
3470 act.store = cpuid;
3471 act.invalidate = active;
3472 act.va = va;
3473 act.pmap = pmap;
3474 act.pde = pde;
3475 act.newpde = newpde;
3476 CPU_SET(cpuid, &active);
3477 smp_rendezvous_cpus(active,
3478 smp_no_rendezvous_barrier, pmap_update_pde_action,
3479 pmap_update_pde_teardown, &act);
3480 } else {
3481 pmap_update_pde_store(pmap, pde, newpde);
3482 if (CPU_ISSET(cpuid, &active))
3483 pmap_update_pde_invalidate(pmap, va, newpde);
3484 }
3485 sched_unpin();
3486 }
3487 #else /* !SMP */
3488 /*
3489 * Normal, non-SMP, invalidation functions.
3490 */
3491 void
pmap_invalidate_page(pmap_t pmap,vm_offset_t va)3492 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
3493 {
3494 struct invpcid_descr d;
3495 struct pmap_pcid *pcidp;
3496 uint64_t kcr3, ucr3;
3497 uint32_t pcid;
3498
3499 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3500 pmap->pm_eptgen++;
3501 return;
3502 }
3503 KASSERT(pmap->pm_type == PT_X86,
3504 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
3505
3506 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
3507 invlpg(va);
3508 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
3509 pmap->pm_ucr3 != PMAP_NO_CR3) {
3510 critical_enter();
3511 pcid = pmap_get_pcid(pmap);
3512 if (invpcid_works) {
3513 d.pcid = pcid | PMAP_PCID_USER_PT;
3514 d.pad = 0;
3515 d.addr = va;
3516 invpcid(&d, INVPCID_ADDR);
3517 } else {
3518 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3519 ucr3 = pmap->pm_ucr3 | pcid |
3520 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3521 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
3522 }
3523 critical_exit();
3524 }
3525 } else if (pmap_pcid_enabled) {
3526 pcidp = zpcpu_get(pmap->pm_pcidp);
3527 pcidp->pm_gen = 0;
3528 }
3529 }
3530
3531 void
pmap_invalidate_range(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)3532 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3533 {
3534 struct invpcid_descr d;
3535 struct pmap_pcid *pcidp;
3536 vm_offset_t addr;
3537 uint64_t kcr3, ucr3;
3538 uint32_t pcid;
3539
3540 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3541 pmap->pm_eptgen++;
3542 return;
3543 }
3544 KASSERT(pmap->pm_type == PT_X86,
3545 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
3546
3547 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
3548 for (addr = sva; addr < eva; addr += PAGE_SIZE)
3549 invlpg(addr);
3550 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
3551 pmap->pm_ucr3 != PMAP_NO_CR3) {
3552 critical_enter();
3553 pcid = pmap_get_pcid(pmap);
3554 if (invpcid_works) {
3555 d.pcid = pcid | PMAP_PCID_USER_PT;
3556 d.pad = 0;
3557 d.addr = sva;
3558 for (; d.addr < eva; d.addr += PAGE_SIZE)
3559 invpcid(&d, INVPCID_ADDR);
3560 } else {
3561 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
3562 ucr3 = pmap->pm_ucr3 | pcid |
3563 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
3564 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
3565 }
3566 critical_exit();
3567 }
3568 } else if (pmap_pcid_enabled) {
3569 pcidp = zpcpu_get(pmap->pm_pcidp);
3570 pcidp->pm_gen = 0;
3571 }
3572 }
3573
3574 void
pmap_invalidate_all(pmap_t pmap)3575 pmap_invalidate_all(pmap_t pmap)
3576 {
3577 struct invpcid_descr d;
3578 struct pmap_pcid *pcidp;
3579 uint64_t kcr3, ucr3;
3580 uint32_t pcid;
3581
3582 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
3583 pmap->pm_eptgen++;
3584 return;
3585 }
3586 KASSERT(pmap->pm_type == PT_X86,
3587 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
3588
3589 if (pmap == kernel_pmap) {
3590 if (pmap_pcid_enabled && invpcid_works) {
3591 bzero(&d, sizeof(d));
3592 invpcid(&d, INVPCID_CTXGLOB);
3593 } else {
3594 invltlb_glob();
3595 }
3596 } else if (pmap == PCPU_GET(curpmap)) {
3597 if (pmap_pcid_enabled) {
3598 critical_enter();
3599 pcid = pmap_get_pcid(pmap);
3600 if (invpcid_works) {
3601 d.pcid = pcid;
3602 d.pad = 0;
3603 d.addr = 0;
3604 invpcid(&d, INVPCID_CTX);
3605 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
3606 d.pcid |= PMAP_PCID_USER_PT;
3607 invpcid(&d, INVPCID_CTX);
3608 }
3609 } else {
3610 kcr3 = pmap->pm_cr3 | pcid;
3611 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
3612 ucr3 = pmap->pm_ucr3 | pcid |
3613 PMAP_PCID_USER_PT;
3614 pmap_pti_pcid_invalidate(ucr3, kcr3);
3615 } else
3616 load_cr3(kcr3);
3617 }
3618 critical_exit();
3619 } else {
3620 invltlb();
3621 }
3622 } else if (pmap_pcid_enabled) {
3623 pcidp = zpcpu_get(pmap->pm_pcidp);
3624 pcidp->pm_gen = 0;
3625 }
3626 }
3627
3628 void
pmap_invalidate_cache(void)3629 pmap_invalidate_cache(void)
3630 {
3631
3632 wbinvd();
3633 }
3634
3635 static void
pmap_update_pde(pmap_t pmap,vm_offset_t va,pd_entry_t * pde,pd_entry_t newpde)3636 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
3637 {
3638 struct pmap_pcid *pcidp;
3639
3640 pmap_update_pde_store(pmap, pde, newpde);
3641 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
3642 pmap_update_pde_invalidate(pmap, va, newpde);
3643 else {
3644 pcidp = zpcpu_get(pmap->pm_pcidp);
3645 pcidp->pm_gen = 0;
3646 }
3647 }
3648 #endif /* !SMP */
3649
3650 static void
pmap_invalidate_pde_page(pmap_t pmap,vm_offset_t va,pd_entry_t pde)3651 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
3652 {
3653
3654 /*
3655 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
3656 * by a promotion that did not invalidate the 512 4KB page mappings
3657 * that might exist in the TLB. Consequently, at this point, the TLB
3658 * may hold both 4KB and 2MB page mappings for the address range [va,
3659 * va + NBPDR). Therefore, the entire range must be invalidated here.
3660 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
3661 * 4KB page mappings for the address range [va, va + NBPDR), and so a
3662 * single INVLPG suffices to invalidate the 2MB page mapping from the
3663 * TLB.
3664 */
3665 if ((pde & PG_PROMOTED) != 0)
3666 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
3667 else
3668 pmap_invalidate_page(pmap, va);
3669 }
3670
3671 DEFINE_IFUNC(, void, pmap_invalidate_cache_range,
3672 (vm_offset_t sva, vm_offset_t eva))
3673 {
3674
3675 if ((cpu_feature & CPUID_SS) != 0)
3676 return (pmap_invalidate_cache_range_selfsnoop);
3677 if ((cpu_feature & CPUID_CLFSH) != 0)
3678 return (pmap_force_invalidate_cache_range);
3679 return (pmap_invalidate_cache_range_all);
3680 }
3681
3682 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
3683
3684 static void
pmap_invalidate_cache_range_check_align(vm_offset_t sva,vm_offset_t eva)3685 pmap_invalidate_cache_range_check_align(vm_offset_t sva, vm_offset_t eva)
3686 {
3687
3688 KASSERT((sva & PAGE_MASK) == 0,
3689 ("pmap_invalidate_cache_range: sva not page-aligned"));
3690 KASSERT((eva & PAGE_MASK) == 0,
3691 ("pmap_invalidate_cache_range: eva not page-aligned"));
3692 }
3693
3694 static void
pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva,vm_offset_t eva)3695 pmap_invalidate_cache_range_selfsnoop(vm_offset_t sva, vm_offset_t eva)
3696 {
3697
3698 pmap_invalidate_cache_range_check_align(sva, eva);
3699 }
3700
3701 void
pmap_force_invalidate_cache_range(vm_offset_t sva,vm_offset_t eva)3702 pmap_force_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
3703 {
3704
3705 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
3706
3707 /*
3708 * XXX: Some CPUs fault, hang, or trash the local APIC
3709 * registers if we use CLFLUSH on the local APIC range. The
3710 * local APIC is always uncached, so we don't need to flush
3711 * for that range anyway.
3712 */
3713 if (pmap_kextract(sva) == lapic_paddr)
3714 return;
3715
3716 if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0) {
3717 /*
3718 * Do per-cache line flush. Use a locked
3719 * instruction to insure that previous stores are
3720 * included in the write-back. The processor
3721 * propagates flush to other processors in the cache
3722 * coherence domain.
3723 */
3724 atomic_thread_fence_seq_cst();
3725 for (; sva < eva; sva += cpu_clflush_line_size)
3726 clflushopt(sva);
3727 atomic_thread_fence_seq_cst();
3728 } else {
3729 /*
3730 * Writes are ordered by CLFLUSH on Intel CPUs.
3731 */
3732 if (cpu_vendor_id != CPU_VENDOR_INTEL)
3733 mfence();
3734 for (; sva < eva; sva += cpu_clflush_line_size)
3735 clflush(sva);
3736 if (cpu_vendor_id != CPU_VENDOR_INTEL)
3737 mfence();
3738 }
3739 }
3740
3741 static void
pmap_invalidate_cache_range_all(vm_offset_t sva,vm_offset_t eva)3742 pmap_invalidate_cache_range_all(vm_offset_t sva, vm_offset_t eva)
3743 {
3744
3745 pmap_invalidate_cache_range_check_align(sva, eva);
3746 pmap_invalidate_cache();
3747 }
3748
3749 /*
3750 * Remove the specified set of pages from the data and instruction caches.
3751 *
3752 * In contrast to pmap_invalidate_cache_range(), this function does not
3753 * rely on the CPU's self-snoop feature, because it is intended for use
3754 * when moving pages into a different cache domain.
3755 */
3756 void
pmap_invalidate_cache_pages(vm_page_t * pages,int count)3757 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
3758 {
3759 vm_offset_t daddr, eva;
3760 int i;
3761 bool useclflushopt;
3762
3763 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
3764 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
3765 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
3766 pmap_invalidate_cache();
3767 else {
3768 if (useclflushopt)
3769 atomic_thread_fence_seq_cst();
3770 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
3771 mfence();
3772 for (i = 0; i < count; i++) {
3773 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
3774 eva = daddr + PAGE_SIZE;
3775 for (; daddr < eva; daddr += cpu_clflush_line_size) {
3776 if (useclflushopt)
3777 clflushopt(daddr);
3778 else
3779 clflush(daddr);
3780 }
3781 }
3782 if (useclflushopt)
3783 atomic_thread_fence_seq_cst();
3784 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
3785 mfence();
3786 }
3787 }
3788
3789 void
pmap_flush_cache_range(vm_offset_t sva,vm_offset_t eva)3790 pmap_flush_cache_range(vm_offset_t sva, vm_offset_t eva)
3791 {
3792
3793 pmap_invalidate_cache_range_check_align(sva, eva);
3794
3795 if ((cpu_stdext_feature & CPUID_STDEXT_CLWB) == 0) {
3796 pmap_force_invalidate_cache_range(sva, eva);
3797 return;
3798 }
3799
3800 /* See comment in pmap_force_invalidate_cache_range(). */
3801 if (pmap_kextract(sva) == lapic_paddr)
3802 return;
3803
3804 atomic_thread_fence_seq_cst();
3805 for (; sva < eva; sva += cpu_clflush_line_size)
3806 clwb(sva);
3807 atomic_thread_fence_seq_cst();
3808 }
3809
3810 void
pmap_flush_cache_phys_range(vm_paddr_t spa,vm_paddr_t epa,vm_memattr_t mattr)3811 pmap_flush_cache_phys_range(vm_paddr_t spa, vm_paddr_t epa, vm_memattr_t mattr)
3812 {
3813 pt_entry_t *pte;
3814 vm_offset_t vaddr;
3815 int error __diagused;
3816 int pte_bits;
3817
3818 KASSERT((spa & PAGE_MASK) == 0,
3819 ("pmap_flush_cache_phys_range: spa not page-aligned"));
3820 KASSERT((epa & PAGE_MASK) == 0,
3821 ("pmap_flush_cache_phys_range: epa not page-aligned"));
3822
3823 if (spa < dmaplimit) {
3824 pmap_flush_cache_range(PHYS_TO_DMAP(spa), PHYS_TO_DMAP(MIN(
3825 dmaplimit, epa)));
3826 if (dmaplimit >= epa)
3827 return;
3828 spa = dmaplimit;
3829 }
3830
3831 pte_bits = pmap_cache_bits(kernel_pmap, mattr, false) | X86_PG_RW |
3832 X86_PG_V;
3833 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
3834 &vaddr);
3835 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
3836 pte = vtopte(vaddr);
3837 for (; spa < epa; spa += PAGE_SIZE) {
3838 sched_pin();
3839 pte_store(pte, spa | pte_bits);
3840 pmap_invlpg(kernel_pmap, vaddr);
3841 /* XXXKIB atomic inside flush_cache_range are excessive */
3842 pmap_flush_cache_range(vaddr, vaddr + PAGE_SIZE);
3843 sched_unpin();
3844 }
3845 vmem_free(kernel_arena, vaddr, PAGE_SIZE);
3846 }
3847
3848 /*
3849 * Routine: pmap_extract
3850 * Function:
3851 * Extract the physical page address associated
3852 * with the given map/virtual_address pair.
3853 */
3854 vm_paddr_t
pmap_extract(pmap_t pmap,vm_offset_t va)3855 pmap_extract(pmap_t pmap, vm_offset_t va)
3856 {
3857 pdp_entry_t *pdpe;
3858 pd_entry_t *pde;
3859 pt_entry_t *pte, PG_V;
3860 vm_paddr_t pa;
3861
3862 pa = 0;
3863 PG_V = pmap_valid_bit(pmap);
3864 PMAP_LOCK(pmap);
3865 pdpe = pmap_pdpe(pmap, va);
3866 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
3867 if ((*pdpe & PG_PS) != 0)
3868 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
3869 else {
3870 pde = pmap_pdpe_to_pde(pdpe, va);
3871 if ((*pde & PG_V) != 0) {
3872 if ((*pde & PG_PS) != 0) {
3873 pa = (*pde & PG_PS_FRAME) |
3874 (va & PDRMASK);
3875 } else {
3876 pte = pmap_pde_to_pte(pde, va);
3877 pa = (*pte & PG_FRAME) |
3878 (va & PAGE_MASK);
3879 }
3880 }
3881 }
3882 }
3883 PMAP_UNLOCK(pmap);
3884 return (pa);
3885 }
3886
3887 /*
3888 * Routine: pmap_extract_and_hold
3889 * Function:
3890 * Atomically extract and hold the physical page
3891 * with the given pmap and virtual address pair
3892 * if that mapping permits the given protection.
3893 */
3894 vm_page_t
pmap_extract_and_hold(pmap_t pmap,vm_offset_t va,vm_prot_t prot)3895 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
3896 {
3897 pdp_entry_t pdpe, *pdpep;
3898 pd_entry_t pde, *pdep;
3899 pt_entry_t pte, PG_RW, PG_V;
3900 vm_page_t m;
3901
3902 m = NULL;
3903 PG_RW = pmap_rw_bit(pmap);
3904 PG_V = pmap_valid_bit(pmap);
3905 PMAP_LOCK(pmap);
3906
3907 pdpep = pmap_pdpe(pmap, va);
3908 if (pdpep == NULL || ((pdpe = *pdpep) & PG_V) == 0)
3909 goto out;
3910 if ((pdpe & PG_PS) != 0) {
3911 if ((pdpe & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0)
3912 goto out;
3913 m = PHYS_TO_VM_PAGE((pdpe & PG_PS_FRAME) | (va & PDPMASK));
3914 goto check_page;
3915 }
3916
3917 pdep = pmap_pdpe_to_pde(pdpep, va);
3918 if (pdep == NULL || ((pde = *pdep) & PG_V) == 0)
3919 goto out;
3920 if ((pde & PG_PS) != 0) {
3921 if ((pde & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0)
3922 goto out;
3923 m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) | (va & PDRMASK));
3924 goto check_page;
3925 }
3926
3927 pte = *pmap_pde_to_pte(pdep, va);
3928 if ((pte & PG_V) == 0 ||
3929 ((pte & PG_RW) == 0 && (prot & VM_PROT_WRITE) != 0))
3930 goto out;
3931 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
3932
3933 check_page:
3934 if (m != NULL && !vm_page_wire_mapped(m))
3935 m = NULL;
3936 out:
3937 PMAP_UNLOCK(pmap);
3938 return (m);
3939 }
3940
3941 /*
3942 * Routine: pmap_kextract
3943 * Function:
3944 * Extract the physical page address associated with the given kernel
3945 * virtual address.
3946 */
3947 vm_paddr_t
pmap_kextract(vm_offset_t va)3948 pmap_kextract(vm_offset_t va)
3949 {
3950 pd_entry_t pde;
3951 vm_paddr_t pa;
3952
3953 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
3954 pa = DMAP_TO_PHYS(va);
3955 } else if (PMAP_ADDRESS_IN_LARGEMAP(va)) {
3956 pa = pmap_large_map_kextract(va);
3957 } else {
3958 pde = *vtopde(va);
3959 if (pde & PG_PS) {
3960 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
3961 } else {
3962 /*
3963 * Beware of a concurrent promotion that changes the
3964 * PDE at this point! For example, vtopte() must not
3965 * be used to access the PTE because it would use the
3966 * new PDE. It is, however, safe to use the old PDE
3967 * because the page table page is preserved by the
3968 * promotion.
3969 */
3970 pa = *pmap_pde_to_pte(&pde, va);
3971 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
3972 }
3973 }
3974 return (pa);
3975 }
3976
3977 /***************************************************
3978 * Low level mapping routines.....
3979 ***************************************************/
3980
3981 /*
3982 * Add a wired page to the kva.
3983 * Note: not SMP coherent.
3984 */
3985 void
pmap_kenter(vm_offset_t va,vm_paddr_t pa)3986 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
3987 {
3988 pt_entry_t *pte;
3989
3990 pte = vtopte(va);
3991 pte_store(pte, pa | pg_g | pg_nx | X86_PG_A | X86_PG_M |
3992 X86_PG_RW | X86_PG_V);
3993 }
3994
3995 static __inline void
pmap_kenter_attr(vm_offset_t va,vm_paddr_t pa,int mode)3996 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
3997 {
3998 pt_entry_t *pte;
3999 int cache_bits;
4000
4001 pte = vtopte(va);
4002 cache_bits = pmap_cache_bits(kernel_pmap, mode, false);
4003 pte_store(pte, pa | pg_g | pg_nx | X86_PG_A | X86_PG_M |
4004 X86_PG_RW | X86_PG_V | cache_bits);
4005 }
4006
4007 /*
4008 * Remove a page from the kernel pagetables.
4009 * Note: not SMP coherent.
4010 */
4011 void
pmap_kremove(vm_offset_t va)4012 pmap_kremove(vm_offset_t va)
4013 {
4014 pt_entry_t *pte;
4015
4016 pte = vtopte(va);
4017 pte_clear(pte);
4018 }
4019
4020 /*
4021 * Used to map a range of physical addresses into kernel
4022 * virtual address space.
4023 *
4024 * The value passed in '*virt' is a suggested virtual address for
4025 * the mapping. Architectures which can support a direct-mapped
4026 * physical to virtual region can return the appropriate address
4027 * within that region, leaving '*virt' unchanged. Other
4028 * architectures should map the pages starting at '*virt' and
4029 * update '*virt' with the first usable address after the mapped
4030 * region.
4031 */
4032 vm_offset_t
pmap_map(vm_offset_t * virt,vm_paddr_t start,vm_paddr_t end,int prot)4033 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
4034 {
4035 return PHYS_TO_DMAP(start);
4036 }
4037
4038 /*
4039 * Add a list of wired pages to the kva
4040 * this routine is only used for temporary
4041 * kernel mappings that do not need to have
4042 * page modification or references recorded.
4043 * Note that old mappings are simply written
4044 * over. The page *must* be wired.
4045 * Note: SMP coherent. Uses a ranged shootdown IPI.
4046 */
4047 void
pmap_qenter(vm_offset_t sva,vm_page_t * ma,int count)4048 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
4049 {
4050 pt_entry_t *endpte, oldpte, pa, *pte;
4051 vm_page_t m;
4052 int cache_bits;
4053
4054 oldpte = 0;
4055 pte = vtopte(sva);
4056 endpte = pte + count;
4057 while (pte < endpte) {
4058 m = *ma++;
4059 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, false);
4060 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
4061 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
4062 oldpte |= *pte;
4063 pte_store(pte, pa | pg_g | pg_nx | X86_PG_A |
4064 X86_PG_M | X86_PG_RW | X86_PG_V);
4065 }
4066 pte++;
4067 }
4068 if (__predict_false((oldpte & X86_PG_V) != 0))
4069 pmap_invalidate_range(kernel_pmap, sva, sva + count *
4070 PAGE_SIZE);
4071 }
4072
4073 /*
4074 * This routine tears out page mappings from the
4075 * kernel -- it is meant only for temporary mappings.
4076 * Note: SMP coherent. Uses a ranged shootdown IPI.
4077 */
4078 void
pmap_qremove(vm_offset_t sva,int count)4079 pmap_qremove(vm_offset_t sva, int count)
4080 {
4081 vm_offset_t va;
4082
4083 va = sva;
4084 while (count-- > 0) {
4085 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
4086 pmap_kremove(va);
4087 va += PAGE_SIZE;
4088 }
4089 pmap_invalidate_range(kernel_pmap, sva, va);
4090 }
4091
4092 /***************************************************
4093 * Page table page management routines.....
4094 ***************************************************/
4095 /*
4096 * Schedule the specified unused page table page to be freed. Specifically,
4097 * add the page to the specified list of pages that will be released to the
4098 * physical memory manager after the TLB has been updated.
4099 */
4100 static __inline void
pmap_add_delayed_free_list(vm_page_t m,struct spglist * free,bool set_PG_ZERO)4101 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free, bool set_PG_ZERO)
4102 {
4103
4104 if (set_PG_ZERO)
4105 m->flags |= PG_ZERO;
4106 else
4107 m->flags &= ~PG_ZERO;
4108 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
4109 }
4110
4111 /*
4112 * Inserts the specified page table page into the specified pmap's collection
4113 * of idle page table pages. Each of a pmap's page table pages is responsible
4114 * for mapping a distinct range of virtual addresses. The pmap's collection is
4115 * ordered by this virtual address range.
4116 *
4117 * If "promoted" is false, then the page table page "mpte" must be zero filled;
4118 * "mpte"'s valid field will be set to 0.
4119 *
4120 * If "promoted" is true and "allpte_PG_A_set" is false, then "mpte" must
4121 * contain valid mappings with identical attributes except for PG_A; "mpte"'s
4122 * valid field will be set to 1.
4123 *
4124 * If "promoted" and "allpte_PG_A_set" are both true, then "mpte" must contain
4125 * valid mappings with identical attributes including PG_A; "mpte"'s valid
4126 * field will be set to VM_PAGE_BITS_ALL.
4127 */
4128 static __inline int
pmap_insert_pt_page(pmap_t pmap,vm_page_t mpte,bool promoted,bool allpte_PG_A_set)4129 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte, bool promoted,
4130 bool allpte_PG_A_set)
4131 {
4132
4133 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4134 KASSERT(promoted || !allpte_PG_A_set,
4135 ("a zero-filled PTP can't have PG_A set in every PTE"));
4136 mpte->valid = promoted ? (allpte_PG_A_set ? VM_PAGE_BITS_ALL : 1) : 0;
4137 return (vm_radix_insert(&pmap->pm_root, mpte));
4138 }
4139
4140 /*
4141 * Removes the page table page mapping the specified virtual address from the
4142 * specified pmap's collection of idle page table pages, and returns it.
4143 * Otherwise, returns NULL if there is no page table page corresponding to the
4144 * specified virtual address.
4145 */
4146 static __inline vm_page_t
pmap_remove_pt_page(pmap_t pmap,vm_offset_t va)4147 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
4148 {
4149
4150 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4151 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
4152 }
4153
4154 /*
4155 * Decrements a page table page's reference count, which is used to record the
4156 * number of valid page table entries within the page. If the reference count
4157 * drops to zero, then the page table page is unmapped. Returns true if the
4158 * page table page was unmapped and false otherwise.
4159 */
4160 static inline bool
pmap_unwire_ptp(pmap_t pmap,vm_offset_t va,vm_page_t m,struct spglist * free)4161 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
4162 {
4163
4164 --m->ref_count;
4165 if (m->ref_count == 0) {
4166 _pmap_unwire_ptp(pmap, va, m, free);
4167 return (true);
4168 } else
4169 return (false);
4170 }
4171
4172 static void
_pmap_unwire_ptp(pmap_t pmap,vm_offset_t va,vm_page_t m,struct spglist * free)4173 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
4174 {
4175 pml5_entry_t *pml5;
4176 pml4_entry_t *pml4;
4177 pdp_entry_t *pdp;
4178 pd_entry_t *pd;
4179 vm_page_t pdpg, pdppg, pml4pg;
4180
4181 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4182
4183 /*
4184 * unmap the page table page
4185 */
4186 if (m->pindex >= NUPDE + NUPDPE + NUPML4E) {
4187 /* PML4 page */
4188 MPASS(pmap_is_la57(pmap));
4189 pml5 = pmap_pml5e(pmap, va);
4190 *pml5 = 0;
4191 if (pmap->pm_pmltopu != NULL && va <= VM_MAXUSER_ADDRESS) {
4192 pml5 = pmap_pml5e_u(pmap, va);
4193 *pml5 = 0;
4194 }
4195 } else if (m->pindex >= NUPDE + NUPDPE) {
4196 /* PDP page */
4197 pml4 = pmap_pml4e(pmap, va);
4198 *pml4 = 0;
4199 if (!pmap_is_la57(pmap) && pmap->pm_pmltopu != NULL &&
4200 va <= VM_MAXUSER_ADDRESS) {
4201 pml4 = pmap_pml4e_u(pmap, va);
4202 *pml4 = 0;
4203 }
4204 } else if (m->pindex >= NUPDE) {
4205 /* PD page */
4206 pdp = pmap_pdpe(pmap, va);
4207 *pdp = 0;
4208 } else {
4209 /* PTE page */
4210 pd = pmap_pde(pmap, va);
4211 *pd = 0;
4212 }
4213 if (m->pindex < NUPDE) {
4214 /* We just released a PT, unhold the matching PD */
4215 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
4216 pmap_unwire_ptp(pmap, va, pdpg, free);
4217 } else if (m->pindex < NUPDE + NUPDPE) {
4218 /* We just released a PD, unhold the matching PDP */
4219 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
4220 pmap_unwire_ptp(pmap, va, pdppg, free);
4221 } else if (m->pindex < NUPDE + NUPDPE + NUPML4E && pmap_is_la57(pmap)) {
4222 /* We just released a PDP, unhold the matching PML4 */
4223 pml4pg = PHYS_TO_VM_PAGE(*pmap_pml5e(pmap, va) & PG_FRAME);
4224 pmap_unwire_ptp(pmap, va, pml4pg, free);
4225 }
4226
4227 pmap_pt_page_count_adj(pmap, -1);
4228
4229 /*
4230 * Put page on a list so that it is released after
4231 * *ALL* TLB shootdown is done
4232 */
4233 pmap_add_delayed_free_list(m, free, true);
4234 }
4235
4236 /*
4237 * After removing a page table entry, this routine is used to
4238 * conditionally free the page, and manage the reference count.
4239 */
4240 static int
pmap_unuse_pt(pmap_t pmap,vm_offset_t va,pd_entry_t ptepde,struct spglist * free)4241 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
4242 struct spglist *free)
4243 {
4244 vm_page_t mpte;
4245
4246 if (va >= VM_MAXUSER_ADDRESS)
4247 return (0);
4248 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
4249 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
4250 return (pmap_unwire_ptp(pmap, va, mpte, free));
4251 }
4252
4253 /*
4254 * Release a page table page reference after a failed attempt to create a
4255 * mapping.
4256 */
4257 static void
pmap_abort_ptp(pmap_t pmap,vm_offset_t va,vm_page_t mpte)4258 pmap_abort_ptp(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
4259 {
4260 struct spglist free;
4261
4262 SLIST_INIT(&free);
4263 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
4264 /*
4265 * Although "va" was never mapped, paging-structure caches
4266 * could nonetheless have entries that refer to the freed
4267 * page table pages. Invalidate those entries.
4268 */
4269 pmap_invalidate_page(pmap, va);
4270 vm_page_free_pages_toq(&free, true);
4271 }
4272 }
4273
4274 static void
pmap_pinit_pcids(pmap_t pmap,uint32_t pcid,int gen)4275 pmap_pinit_pcids(pmap_t pmap, uint32_t pcid, int gen)
4276 {
4277 struct pmap_pcid *pcidp;
4278 int i;
4279
4280 CPU_FOREACH(i) {
4281 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, i);
4282 pcidp->pm_pcid = pcid;
4283 pcidp->pm_gen = gen;
4284 }
4285 }
4286
4287 void
pmap_pinit0(pmap_t pmap)4288 pmap_pinit0(pmap_t pmap)
4289 {
4290 struct proc *p;
4291 struct thread *td;
4292
4293 PMAP_LOCK_INIT(pmap);
4294 pmap->pm_pmltop = kernel_pmap->pm_pmltop;
4295 pmap->pm_pmltopu = NULL;
4296 pmap->pm_cr3 = kernel_pmap->pm_cr3;
4297 /* hack to keep pmap_pti_pcid_invalidate() alive */
4298 pmap->pm_ucr3 = PMAP_NO_CR3;
4299 vm_radix_init(&pmap->pm_root);
4300 CPU_ZERO(&pmap->pm_active);
4301 TAILQ_INIT(&pmap->pm_pvchunk);
4302 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
4303 pmap->pm_flags = pmap_flags;
4304 pmap->pm_pcidp = uma_zalloc_pcpu(pcpu_zone_8, M_WAITOK);
4305 pmap_pinit_pcids(pmap, PMAP_PCID_KERN + 1, 1);
4306 pmap_activate_boot(pmap);
4307 td = curthread;
4308 if (pti) {
4309 p = td->td_proc;
4310 PROC_LOCK(p);
4311 p->p_md.md_flags |= P_MD_KPTI;
4312 PROC_UNLOCK(p);
4313 }
4314 pmap_thread_init_invl_gen(td);
4315
4316 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
4317 pmap_pkru_ranges_zone = uma_zcreate("pkru ranges",
4318 sizeof(struct pmap_pkru_range), NULL, NULL, NULL, NULL,
4319 UMA_ALIGN_PTR, 0);
4320 }
4321 }
4322
4323 void
pmap_pinit_pml4(vm_page_t pml4pg)4324 pmap_pinit_pml4(vm_page_t pml4pg)
4325 {
4326 pml4_entry_t *pm_pml4;
4327 int i;
4328
4329 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
4330
4331 /* Wire in kernel global address entries. */
4332 for (i = 0; i < NKPML4E; i++) {
4333 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
4334 X86_PG_V;
4335 }
4336 #ifdef KASAN
4337 for (i = 0; i < NKASANPML4E; i++) {
4338 pm_pml4[KASANPML4I + i] = (KASANPDPphys + ptoa(i)) | X86_PG_RW |
4339 X86_PG_V | pg_nx;
4340 }
4341 #endif
4342 #ifdef KMSAN
4343 for (i = 0; i < NKMSANSHADPML4E; i++) {
4344 pm_pml4[KMSANSHADPML4I + i] = (KMSANSHADPDPphys + ptoa(i)) |
4345 X86_PG_RW | X86_PG_V | pg_nx;
4346 }
4347 for (i = 0; i < NKMSANORIGPML4E; i++) {
4348 pm_pml4[KMSANORIGPML4I + i] = (KMSANORIGPDPphys + ptoa(i)) |
4349 X86_PG_RW | X86_PG_V | pg_nx;
4350 }
4351 #endif
4352 for (i = 0; i < ndmpdpphys; i++) {
4353 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
4354 X86_PG_V;
4355 }
4356
4357 /* install self-referential address mapping entry(s) */
4358 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
4359 X86_PG_A | X86_PG_M;
4360
4361 /* install large map entries if configured */
4362 for (i = 0; i < lm_ents; i++)
4363 pm_pml4[LMSPML4I + i] = kernel_pmap->pm_pmltop[LMSPML4I + i];
4364 }
4365
4366 void
pmap_pinit_pml5(vm_page_t pml5pg)4367 pmap_pinit_pml5(vm_page_t pml5pg)
4368 {
4369 pml5_entry_t *pm_pml5;
4370
4371 pm_pml5 = (pml5_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml5pg));
4372
4373 /*
4374 * Add pml5 entry at top of KVA pointing to existing pml4 table,
4375 * entering all existing kernel mappings into level 5 table.
4376 */
4377 pm_pml5[pmap_pml5e_index(UPT_MAX_ADDRESS)] = KPML4phys | X86_PG_V |
4378 X86_PG_RW | X86_PG_A | X86_PG_M;
4379
4380 /*
4381 * Install self-referential address mapping entry.
4382 */
4383 pm_pml5[PML5PML5I] = VM_PAGE_TO_PHYS(pml5pg) |
4384 X86_PG_RW | X86_PG_V | X86_PG_M | X86_PG_A;
4385 }
4386
4387 static void
pmap_pinit_pml4_pti(vm_page_t pml4pgu)4388 pmap_pinit_pml4_pti(vm_page_t pml4pgu)
4389 {
4390 pml4_entry_t *pm_pml4u;
4391 int i;
4392
4393 pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pgu));
4394 for (i = 0; i < NPML4EPG; i++)
4395 pm_pml4u[i] = pti_pml4[i];
4396 }
4397
4398 static void
pmap_pinit_pml5_pti(vm_page_t pml5pgu)4399 pmap_pinit_pml5_pti(vm_page_t pml5pgu)
4400 {
4401 pml5_entry_t *pm_pml5u;
4402
4403 pm_pml5u = (pml5_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml5pgu));
4404 pagezero(pm_pml5u);
4405
4406 /*
4407 * Add pml5 entry at top of KVA pointing to existing pml4 pti
4408 * table, entering all kernel mappings needed for usermode
4409 * into level 5 table.
4410 */
4411 pm_pml5u[pmap_pml5e_index(UPT_MAX_ADDRESS)] =
4412 pmap_kextract((vm_offset_t)pti_pml4) |
4413 X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
4414 }
4415
4416 /* Allocate a page table page and do related bookkeeping */
4417 static vm_page_t
pmap_alloc_pt_page(pmap_t pmap,vm_pindex_t pindex,int flags)4418 pmap_alloc_pt_page(pmap_t pmap, vm_pindex_t pindex, int flags)
4419 {
4420 vm_page_t m;
4421
4422 m = vm_page_alloc_noobj(flags);
4423 if (__predict_false(m == NULL))
4424 return (NULL);
4425 m->pindex = pindex;
4426 pmap_pt_page_count_adj(pmap, 1);
4427 return (m);
4428 }
4429
4430 static void
pmap_free_pt_page(pmap_t pmap,vm_page_t m,bool zerofilled)4431 pmap_free_pt_page(pmap_t pmap, vm_page_t m, bool zerofilled)
4432 {
4433 /*
4434 * This function assumes the page will need to be unwired,
4435 * even though the counterpart allocation in pmap_alloc_pt_page()
4436 * doesn't enforce VM_ALLOC_WIRED. However, all current uses
4437 * of pmap_free_pt_page() require unwiring. The case in which
4438 * a PT page doesn't require unwiring because its ref_count has
4439 * naturally reached 0 is handled through _pmap_unwire_ptp().
4440 */
4441 vm_page_unwire_noq(m);
4442 if (zerofilled)
4443 vm_page_free_zero(m);
4444 else
4445 vm_page_free(m);
4446
4447 pmap_pt_page_count_adj(pmap, -1);
4448 }
4449
4450 _Static_assert(sizeof(struct pmap_pcid) == 8, "Fix pcpu zone for pm_pcidp");
4451
4452 /*
4453 * Initialize a preallocated and zeroed pmap structure,
4454 * such as one in a vmspace structure.
4455 */
4456 int
pmap_pinit_type(pmap_t pmap,enum pmap_type pm_type,int flags)4457 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
4458 {
4459 vm_page_t pmltop_pg, pmltop_pgu;
4460 vm_paddr_t pmltop_phys;
4461
4462 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
4463
4464 /*
4465 * Allocate the page directory page. Pass NULL instead of a
4466 * pointer to the pmap here to avoid calling
4467 * pmap_resident_count_adj() through pmap_pt_page_count_adj(),
4468 * since that requires pmap lock. Instead do the accounting
4469 * manually.
4470 *
4471 * Note that final call to pmap_remove() optimization that
4472 * checks for zero resident_count is basically disabled by
4473 * accounting for top-level page. But the optimization was
4474 * not effective since we started using non-managed mapping of
4475 * the shared page.
4476 */
4477 pmltop_pg = pmap_alloc_pt_page(NULL, 0, VM_ALLOC_WIRED | VM_ALLOC_ZERO |
4478 VM_ALLOC_WAITOK);
4479 pmap_pt_page_count_pinit(pmap, 1);
4480
4481 pmltop_phys = VM_PAGE_TO_PHYS(pmltop_pg);
4482 pmap->pm_pmltop = (pml5_entry_t *)PHYS_TO_DMAP(pmltop_phys);
4483
4484 if (pmap_pcid_enabled) {
4485 if (pmap->pm_pcidp == NULL)
4486 pmap->pm_pcidp = uma_zalloc_pcpu(pcpu_zone_8,
4487 M_WAITOK);
4488 pmap_pinit_pcids(pmap, PMAP_PCID_NONE, 0);
4489 }
4490 pmap->pm_cr3 = PMAP_NO_CR3; /* initialize to an invalid value */
4491 pmap->pm_ucr3 = PMAP_NO_CR3;
4492 pmap->pm_pmltopu = NULL;
4493
4494 pmap->pm_type = pm_type;
4495
4496 /*
4497 * Do not install the host kernel mappings in the nested page
4498 * tables. These mappings are meaningless in the guest physical
4499 * address space.
4500 * Install minimal kernel mappings in PTI case.
4501 */
4502 switch (pm_type) {
4503 case PT_X86:
4504 pmap->pm_cr3 = pmltop_phys;
4505 if (pmap_is_la57(pmap))
4506 pmap_pinit_pml5(pmltop_pg);
4507 else
4508 pmap_pinit_pml4(pmltop_pg);
4509 if ((curproc->p_md.md_flags & P_MD_KPTI) != 0) {
4510 /*
4511 * As with pmltop_pg, pass NULL instead of a
4512 * pointer to the pmap to ensure that the PTI
4513 * page counted explicitly.
4514 */
4515 pmltop_pgu = pmap_alloc_pt_page(NULL, 0,
4516 VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
4517 pmap_pt_page_count_pinit(pmap, 1);
4518 pmap->pm_pmltopu = (pml4_entry_t *)PHYS_TO_DMAP(
4519 VM_PAGE_TO_PHYS(pmltop_pgu));
4520 if (pmap_is_la57(pmap))
4521 pmap_pinit_pml5_pti(pmltop_pgu);
4522 else
4523 pmap_pinit_pml4_pti(pmltop_pgu);
4524 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pmltop_pgu);
4525 }
4526 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
4527 rangeset_init(&pmap->pm_pkru, pkru_dup_range,
4528 pkru_free_range, pmap, M_NOWAIT);
4529 }
4530 break;
4531 case PT_EPT:
4532 case PT_RVI:
4533 pmap->pm_eptsmr = smr_create("pmap", 0, 0);
4534 break;
4535 }
4536
4537 vm_radix_init(&pmap->pm_root);
4538 CPU_ZERO(&pmap->pm_active);
4539 TAILQ_INIT(&pmap->pm_pvchunk);
4540 pmap->pm_flags = flags;
4541 pmap->pm_eptgen = 0;
4542
4543 return (1);
4544 }
4545
4546 int
pmap_pinit(pmap_t pmap)4547 pmap_pinit(pmap_t pmap)
4548 {
4549
4550 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
4551 }
4552
4553 static void
pmap_allocpte_free_unref(pmap_t pmap,vm_offset_t va,pt_entry_t * pte)4554 pmap_allocpte_free_unref(pmap_t pmap, vm_offset_t va, pt_entry_t *pte)
4555 {
4556 vm_page_t mpg;
4557 struct spglist free;
4558
4559 mpg = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
4560 if (mpg->ref_count != 0)
4561 return;
4562 SLIST_INIT(&free);
4563 _pmap_unwire_ptp(pmap, va, mpg, &free);
4564 pmap_invalidate_page(pmap, va);
4565 vm_page_free_pages_toq(&free, true);
4566 }
4567
4568 static pml4_entry_t *
pmap_allocpte_getpml4(pmap_t pmap,struct rwlock ** lockp,vm_offset_t va,bool addref)4569 pmap_allocpte_getpml4(pmap_t pmap, struct rwlock **lockp, vm_offset_t va,
4570 bool addref)
4571 {
4572 vm_pindex_t pml5index;
4573 pml5_entry_t *pml5;
4574 pml4_entry_t *pml4;
4575 vm_page_t pml4pg;
4576 pt_entry_t PG_V;
4577 bool allocated;
4578
4579 if (!pmap_is_la57(pmap))
4580 return (&pmap->pm_pmltop[pmap_pml4e_index(va)]);
4581
4582 PG_V = pmap_valid_bit(pmap);
4583 pml5index = pmap_pml5e_index(va);
4584 pml5 = &pmap->pm_pmltop[pml5index];
4585 if ((*pml5 & PG_V) == 0) {
4586 if (pmap_allocpte_nosleep(pmap, pmap_pml5e_pindex(va), lockp,
4587 va) == NULL)
4588 return (NULL);
4589 allocated = true;
4590 } else {
4591 allocated = false;
4592 }
4593 pml4 = (pml4_entry_t *)PHYS_TO_DMAP(*pml5 & PG_FRAME);
4594 pml4 = &pml4[pmap_pml4e_index(va)];
4595 if ((*pml4 & PG_V) == 0) {
4596 pml4pg = PHYS_TO_VM_PAGE(*pml5 & PG_FRAME);
4597 if (allocated && !addref)
4598 pml4pg->ref_count--;
4599 else if (!allocated && addref)
4600 pml4pg->ref_count++;
4601 }
4602 return (pml4);
4603 }
4604
4605 static pdp_entry_t *
pmap_allocpte_getpdp(pmap_t pmap,struct rwlock ** lockp,vm_offset_t va,bool addref)4606 pmap_allocpte_getpdp(pmap_t pmap, struct rwlock **lockp, vm_offset_t va,
4607 bool addref)
4608 {
4609 vm_page_t pdppg;
4610 pml4_entry_t *pml4;
4611 pdp_entry_t *pdp;
4612 pt_entry_t PG_V;
4613 bool allocated;
4614
4615 PG_V = pmap_valid_bit(pmap);
4616
4617 pml4 = pmap_allocpte_getpml4(pmap, lockp, va, false);
4618 if (pml4 == NULL)
4619 return (NULL);
4620
4621 if ((*pml4 & PG_V) == 0) {
4622 /* Have to allocate a new pdp, recurse */
4623 if (pmap_allocpte_nosleep(pmap, pmap_pml4e_pindex(va), lockp,
4624 va) == NULL) {
4625 if (pmap_is_la57(pmap))
4626 pmap_allocpte_free_unref(pmap, va,
4627 pmap_pml5e(pmap, va));
4628 return (NULL);
4629 }
4630 allocated = true;
4631 } else {
4632 allocated = false;
4633 }
4634 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
4635 pdp = &pdp[pmap_pdpe_index(va)];
4636 if ((*pdp & PG_V) == 0) {
4637 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
4638 if (allocated && !addref)
4639 pdppg->ref_count--;
4640 else if (!allocated && addref)
4641 pdppg->ref_count++;
4642 }
4643 return (pdp);
4644 }
4645
4646 /*
4647 * The ptepindexes, i.e. page indices, of the page table pages encountered
4648 * while translating virtual address va are defined as follows:
4649 * - for the page table page (last level),
4650 * ptepindex = pmap_pde_pindex(va) = va >> PDRSHIFT,
4651 * in other words, it is just the index of the PDE that maps the page
4652 * table page.
4653 * - for the page directory page,
4654 * ptepindex = NUPDE (number of userland PD entries) +
4655 * (pmap_pde_index(va) >> NPDEPGSHIFT)
4656 * i.e. index of PDPE is put after the last index of PDE,
4657 * - for the page directory pointer page,
4658 * ptepindex = NUPDE + NUPDPE + (pmap_pde_index(va) >> (NPDEPGSHIFT +
4659 * NPML4EPGSHIFT),
4660 * i.e. index of pml4e is put after the last index of PDPE,
4661 * - for the PML4 page (if LA57 mode is enabled),
4662 * ptepindex = NUPDE + NUPDPE + NUPML4E + (pmap_pde_index(va) >>
4663 * (NPDEPGSHIFT + NPML4EPGSHIFT + NPML5EPGSHIFT),
4664 * i.e. index of pml5e is put after the last index of PML4E.
4665 *
4666 * Define an order on the paging entries, where all entries of the
4667 * same height are put together, then heights are put from deepest to
4668 * root. Then ptexpindex is the sequential number of the
4669 * corresponding paging entry in this order.
4670 *
4671 * The values of NUPDE, NUPDPE, and NUPML4E are determined by the size of
4672 * LA57 paging structures even in LA48 paging mode. Moreover, the
4673 * ptepindexes are calculated as if the paging structures were 5-level
4674 * regardless of the actual mode of operation.
4675 *
4676 * The root page at PML4/PML5 does not participate in this indexing scheme,
4677 * since it is statically allocated by pmap_pinit() and not by pmap_allocpte().
4678 */
4679 static vm_page_t
pmap_allocpte_nosleep(pmap_t pmap,vm_pindex_t ptepindex,struct rwlock ** lockp,vm_offset_t va)4680 pmap_allocpte_nosleep(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp,
4681 vm_offset_t va)
4682 {
4683 vm_pindex_t pml5index, pml4index;
4684 pml5_entry_t *pml5, *pml5u;
4685 pml4_entry_t *pml4, *pml4u;
4686 pdp_entry_t *pdp;
4687 pd_entry_t *pd;
4688 vm_page_t m, pdpg;
4689 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
4690
4691 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4692
4693 PG_A = pmap_accessed_bit(pmap);
4694 PG_M = pmap_modified_bit(pmap);
4695 PG_V = pmap_valid_bit(pmap);
4696 PG_RW = pmap_rw_bit(pmap);
4697
4698 /*
4699 * Allocate a page table page.
4700 */
4701 m = pmap_alloc_pt_page(pmap, ptepindex,
4702 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
4703 if (m == NULL)
4704 return (NULL);
4705
4706 /*
4707 * Map the pagetable page into the process address space, if
4708 * it isn't already there.
4709 */
4710 if (ptepindex >= NUPDE + NUPDPE + NUPML4E) {
4711 MPASS(pmap_is_la57(pmap));
4712
4713 pml5index = pmap_pml5e_index(va);
4714 pml5 = &pmap->pm_pmltop[pml5index];
4715 KASSERT((*pml5 & PG_V) == 0,
4716 ("pmap %p va %#lx pml5 %#lx", pmap, va, *pml5));
4717 *pml5 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4718
4719 if (pmap->pm_pmltopu != NULL && pml5index < NUPML5E) {
4720 MPASS(pmap->pm_ucr3 != PMAP_NO_CR3);
4721 *pml5 |= pg_nx;
4722
4723 pml5u = &pmap->pm_pmltopu[pml5index];
4724 *pml5u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
4725 PG_A | PG_M;
4726 }
4727 } else if (ptepindex >= NUPDE + NUPDPE) {
4728 pml4index = pmap_pml4e_index(va);
4729 /* Wire up a new PDPE page */
4730 pml4 = pmap_allocpte_getpml4(pmap, lockp, va, true);
4731 if (pml4 == NULL) {
4732 pmap_free_pt_page(pmap, m, true);
4733 return (NULL);
4734 }
4735 KASSERT((*pml4 & PG_V) == 0,
4736 ("pmap %p va %#lx pml4 %#lx", pmap, va, *pml4));
4737 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4738
4739 if (!pmap_is_la57(pmap) && pmap->pm_pmltopu != NULL &&
4740 pml4index < NUPML4E) {
4741 MPASS(pmap->pm_ucr3 != PMAP_NO_CR3);
4742
4743 /*
4744 * PTI: Make all user-space mappings in the
4745 * kernel-mode page table no-execute so that
4746 * we detect any programming errors that leave
4747 * the kernel-mode page table active on return
4748 * to user space.
4749 */
4750 *pml4 |= pg_nx;
4751
4752 pml4u = &pmap->pm_pmltopu[pml4index];
4753 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
4754 PG_A | PG_M;
4755 }
4756 } else if (ptepindex >= NUPDE) {
4757 /* Wire up a new PDE page */
4758 pdp = pmap_allocpte_getpdp(pmap, lockp, va, true);
4759 if (pdp == NULL) {
4760 pmap_free_pt_page(pmap, m, true);
4761 return (NULL);
4762 }
4763 KASSERT((*pdp & PG_V) == 0,
4764 ("pmap %p va %#lx pdp %#lx", pmap, va, *pdp));
4765 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4766 } else {
4767 /* Wire up a new PTE page */
4768 pdp = pmap_allocpte_getpdp(pmap, lockp, va, false);
4769 if (pdp == NULL) {
4770 pmap_free_pt_page(pmap, m, true);
4771 return (NULL);
4772 }
4773 if ((*pdp & PG_V) == 0) {
4774 /* Have to allocate a new pd, recurse */
4775 if (pmap_allocpte_nosleep(pmap, pmap_pdpe_pindex(va),
4776 lockp, va) == NULL) {
4777 pmap_allocpte_free_unref(pmap, va,
4778 pmap_pml4e(pmap, va));
4779 pmap_free_pt_page(pmap, m, true);
4780 return (NULL);
4781 }
4782 } else {
4783 /* Add reference to the pd page */
4784 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
4785 pdpg->ref_count++;
4786 }
4787 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
4788
4789 /* Now we know where the page directory page is */
4790 pd = &pd[pmap_pde_index(va)];
4791 KASSERT((*pd & PG_V) == 0,
4792 ("pmap %p va %#lx pd %#lx", pmap, va, *pd));
4793 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
4794 }
4795
4796 return (m);
4797 }
4798
4799 /*
4800 * This routine is called if the desired page table page does not exist.
4801 *
4802 * If page table page allocation fails, this routine may sleep before
4803 * returning NULL. It sleeps only if a lock pointer was given. Sleep
4804 * occurs right before returning to the caller. This way, we never
4805 * drop pmap lock to sleep while a page table page has ref_count == 0,
4806 * which prevents the page from being freed under us.
4807 */
4808 static vm_page_t
pmap_allocpte_alloc(pmap_t pmap,vm_pindex_t ptepindex,struct rwlock ** lockp,vm_offset_t va)4809 pmap_allocpte_alloc(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp,
4810 vm_offset_t va)
4811 {
4812 vm_page_t m;
4813
4814 m = pmap_allocpte_nosleep(pmap, ptepindex, lockp, va);
4815 if (m == NULL && lockp != NULL) {
4816 RELEASE_PV_LIST_LOCK(lockp);
4817 PMAP_UNLOCK(pmap);
4818 PMAP_ASSERT_NOT_IN_DI();
4819 vm_wait(NULL);
4820 PMAP_LOCK(pmap);
4821 }
4822 return (m);
4823 }
4824
4825 static pd_entry_t *
pmap_alloc_pde(pmap_t pmap,vm_offset_t va,vm_page_t * pdpgp,struct rwlock ** lockp)4826 pmap_alloc_pde(pmap_t pmap, vm_offset_t va, vm_page_t *pdpgp,
4827 struct rwlock **lockp)
4828 {
4829 pdp_entry_t *pdpe, PG_V;
4830 pd_entry_t *pde;
4831 vm_page_t pdpg;
4832 vm_pindex_t pdpindex;
4833
4834 PG_V = pmap_valid_bit(pmap);
4835
4836 retry:
4837 pdpe = pmap_pdpe(pmap, va);
4838 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
4839 pde = pmap_pdpe_to_pde(pdpe, va);
4840 if (va < VM_MAXUSER_ADDRESS) {
4841 /* Add a reference to the pd page. */
4842 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
4843 pdpg->ref_count++;
4844 } else
4845 pdpg = NULL;
4846 } else if (va < VM_MAXUSER_ADDRESS) {
4847 /* Allocate a pd page. */
4848 pdpindex = pmap_pde_pindex(va) >> NPDPEPGSHIFT;
4849 pdpg = pmap_allocpte_alloc(pmap, NUPDE + pdpindex, lockp, va);
4850 if (pdpg == NULL) {
4851 if (lockp != NULL)
4852 goto retry;
4853 else
4854 return (NULL);
4855 }
4856 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
4857 pde = &pde[pmap_pde_index(va)];
4858 } else
4859 panic("pmap_alloc_pde: missing page table page for va %#lx",
4860 va);
4861 *pdpgp = pdpg;
4862 return (pde);
4863 }
4864
4865 static vm_page_t
pmap_allocpte(pmap_t pmap,vm_offset_t va,struct rwlock ** lockp)4866 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
4867 {
4868 vm_pindex_t ptepindex;
4869 pd_entry_t *pd, PG_V;
4870 vm_page_t m;
4871
4872 PG_V = pmap_valid_bit(pmap);
4873
4874 /*
4875 * Calculate pagetable page index
4876 */
4877 ptepindex = pmap_pde_pindex(va);
4878 retry:
4879 /*
4880 * Get the page directory entry
4881 */
4882 pd = pmap_pde(pmap, va);
4883
4884 /*
4885 * This supports switching from a 2MB page to a
4886 * normal 4K page.
4887 */
4888 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
4889 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
4890 /*
4891 * Invalidation of the 2MB page mapping may have caused
4892 * the deallocation of the underlying PD page.
4893 */
4894 pd = NULL;
4895 }
4896 }
4897
4898 /*
4899 * If the page table page is mapped, we just increment the
4900 * hold count, and activate it.
4901 */
4902 if (pd != NULL && (*pd & PG_V) != 0) {
4903 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
4904 m->ref_count++;
4905 } else {
4906 /*
4907 * Here if the pte page isn't mapped, or if it has been
4908 * deallocated.
4909 */
4910 m = pmap_allocpte_alloc(pmap, ptepindex, lockp, va);
4911 if (m == NULL && lockp != NULL)
4912 goto retry;
4913 }
4914 return (m);
4915 }
4916
4917 /***************************************************
4918 * Pmap allocation/deallocation routines.
4919 ***************************************************/
4920
4921 /*
4922 * Release any resources held by the given physical map.
4923 * Called when a pmap initialized by pmap_pinit is being released.
4924 * Should only be called if the map contains no valid mappings.
4925 */
4926 void
pmap_release(pmap_t pmap)4927 pmap_release(pmap_t pmap)
4928 {
4929 vm_page_t m;
4930 int i;
4931
4932 KASSERT(vm_radix_is_empty(&pmap->pm_root),
4933 ("pmap_release: pmap %p has reserved page table page(s)",
4934 pmap));
4935 KASSERT(CPU_EMPTY(&pmap->pm_active),
4936 ("releasing active pmap %p", pmap));
4937
4938 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pmltop));
4939
4940 if (pmap_is_la57(pmap)) {
4941 pmap->pm_pmltop[pmap_pml5e_index(UPT_MAX_ADDRESS)] = 0;
4942 pmap->pm_pmltop[PML5PML5I] = 0;
4943 } else {
4944 for (i = 0; i < NKPML4E; i++) /* KVA */
4945 pmap->pm_pmltop[KPML4BASE + i] = 0;
4946 #ifdef KASAN
4947 for (i = 0; i < NKASANPML4E; i++) /* KASAN shadow map */
4948 pmap->pm_pmltop[KASANPML4I + i] = 0;
4949 #endif
4950 #ifdef KMSAN
4951 for (i = 0; i < NKMSANSHADPML4E; i++) /* KMSAN shadow map */
4952 pmap->pm_pmltop[KMSANSHADPML4I + i] = 0;
4953 for (i = 0; i < NKMSANORIGPML4E; i++) /* KMSAN shadow map */
4954 pmap->pm_pmltop[KMSANORIGPML4I + i] = 0;
4955 #endif
4956 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
4957 pmap->pm_pmltop[DMPML4I + i] = 0;
4958 pmap->pm_pmltop[PML4PML4I] = 0; /* Recursive Mapping */
4959 for (i = 0; i < lm_ents; i++) /* Large Map */
4960 pmap->pm_pmltop[LMSPML4I + i] = 0;
4961 }
4962
4963 pmap_free_pt_page(NULL, m, true);
4964 pmap_pt_page_count_pinit(pmap, -1);
4965
4966 if (pmap->pm_pmltopu != NULL) {
4967 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->
4968 pm_pmltopu));
4969 pmap_free_pt_page(NULL, m, false);
4970 pmap_pt_page_count_pinit(pmap, -1);
4971 }
4972 if (pmap->pm_type == PT_X86 &&
4973 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0)
4974 rangeset_fini(&pmap->pm_pkru);
4975
4976 KASSERT(pmap->pm_stats.resident_count == 0,
4977 ("pmap_release: pmap %p resident count %ld != 0",
4978 pmap, pmap->pm_stats.resident_count));
4979 }
4980
4981 static int
kvm_size(SYSCTL_HANDLER_ARGS)4982 kvm_size(SYSCTL_HANDLER_ARGS)
4983 {
4984 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
4985
4986 return sysctl_handle_long(oidp, &ksize, 0, req);
4987 }
4988 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
4989 0, 0, kvm_size, "LU",
4990 "Size of KVM");
4991
4992 static int
kvm_free(SYSCTL_HANDLER_ARGS)4993 kvm_free(SYSCTL_HANDLER_ARGS)
4994 {
4995 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
4996
4997 return sysctl_handle_long(oidp, &kfree, 0, req);
4998 }
4999 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG | CTLFLAG_RD | CTLFLAG_MPSAFE,
5000 0, 0, kvm_free, "LU",
5001 "Amount of KVM free");
5002
5003 #ifdef KMSAN
5004 static void
pmap_kmsan_shadow_map_page_array(vm_paddr_t pdppa,vm_size_t size)5005 pmap_kmsan_shadow_map_page_array(vm_paddr_t pdppa, vm_size_t size)
5006 {
5007 pdp_entry_t *pdpe;
5008 pd_entry_t *pde;
5009 pt_entry_t *pte;
5010 vm_paddr_t dummypa, dummypd, dummypt;
5011 int i, npde, npdpg;
5012
5013 npdpg = howmany(size, NBPDP);
5014 npde = size / NBPDR;
5015
5016 dummypa = vm_phys_early_alloc(-1, PAGE_SIZE);
5017 pagezero((void *)PHYS_TO_DMAP(dummypa));
5018
5019 dummypt = vm_phys_early_alloc(-1, PAGE_SIZE);
5020 pagezero((void *)PHYS_TO_DMAP(dummypt));
5021 dummypd = vm_phys_early_alloc(-1, PAGE_SIZE * npdpg);
5022 for (i = 0; i < npdpg; i++)
5023 pagezero((void *)PHYS_TO_DMAP(dummypd + ptoa(i)));
5024
5025 pte = (pt_entry_t *)PHYS_TO_DMAP(dummypt);
5026 for (i = 0; i < NPTEPG; i++)
5027 pte[i] = (pt_entry_t)(dummypa | X86_PG_V | X86_PG_RW |
5028 X86_PG_A | X86_PG_M | pg_nx);
5029
5030 pde = (pd_entry_t *)PHYS_TO_DMAP(dummypd);
5031 for (i = 0; i < npde; i++)
5032 pde[i] = (pd_entry_t)(dummypt | X86_PG_V | X86_PG_RW | pg_nx);
5033
5034 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(pdppa);
5035 for (i = 0; i < npdpg; i++)
5036 pdpe[i] = (pdp_entry_t)(dummypd + ptoa(i) | X86_PG_V |
5037 X86_PG_RW | pg_nx);
5038 }
5039
5040 static void
pmap_kmsan_page_array_startup(vm_offset_t start,vm_offset_t end)5041 pmap_kmsan_page_array_startup(vm_offset_t start, vm_offset_t end)
5042 {
5043 vm_size_t size;
5044
5045 KASSERT(start % NBPDP == 0, ("unaligned page array start address"));
5046
5047 /*
5048 * The end of the page array's KVA region is 2MB aligned, see
5049 * kmem_init().
5050 */
5051 size = round_2mpage(end) - start;
5052 pmap_kmsan_shadow_map_page_array(KMSANSHADPDPphys, size);
5053 pmap_kmsan_shadow_map_page_array(KMSANORIGPDPphys, size);
5054 }
5055 #endif
5056
5057 /*
5058 * Allocate physical memory for the vm_page array and map it into KVA,
5059 * attempting to back the vm_pages with domain-local memory.
5060 */
5061 void
pmap_page_array_startup(long pages)5062 pmap_page_array_startup(long pages)
5063 {
5064 pdp_entry_t *pdpe;
5065 pd_entry_t *pde, newpdir;
5066 vm_offset_t va, start, end;
5067 vm_paddr_t pa;
5068 long pfn;
5069 int domain, i;
5070
5071 vm_page_array_size = pages;
5072
5073 start = VM_MIN_KERNEL_ADDRESS;
5074 end = start + pages * sizeof(struct vm_page);
5075 for (va = start; va < end; va += NBPDR) {
5076 pfn = first_page + (va - start) / sizeof(struct vm_page);
5077 domain = vm_phys_domain(ptoa(pfn));
5078 pdpe = pmap_pdpe(kernel_pmap, va);
5079 if ((*pdpe & X86_PG_V) == 0) {
5080 pa = vm_phys_early_alloc(domain, PAGE_SIZE);
5081 dump_add_page(pa);
5082 pagezero((void *)PHYS_TO_DMAP(pa));
5083 *pdpe = (pdp_entry_t)(pa | X86_PG_V | X86_PG_RW |
5084 X86_PG_A | X86_PG_M);
5085 }
5086 pde = pmap_pdpe_to_pde(pdpe, va);
5087 if ((*pde & X86_PG_V) != 0)
5088 panic("Unexpected pde");
5089 pa = vm_phys_early_alloc(domain, NBPDR);
5090 for (i = 0; i < NPDEPG; i++)
5091 dump_add_page(pa + i * PAGE_SIZE);
5092 newpdir = (pd_entry_t)(pa | X86_PG_V | X86_PG_RW | X86_PG_A |
5093 X86_PG_M | PG_PS | pg_g | pg_nx);
5094 pde_store(pde, newpdir);
5095 }
5096 vm_page_array = (vm_page_t)start;
5097
5098 #ifdef KMSAN
5099 pmap_kmsan_page_array_startup(start, end);
5100 #endif
5101 }
5102
5103 /*
5104 * grow the number of kernel page table entries, if needed
5105 */
5106 void
pmap_growkernel(vm_offset_t addr)5107 pmap_growkernel(vm_offset_t addr)
5108 {
5109 vm_paddr_t paddr;
5110 vm_page_t nkpg;
5111 pd_entry_t *pde, newpdir;
5112 pdp_entry_t *pdpe;
5113 vm_offset_t end;
5114
5115 TSENTER();
5116 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
5117
5118 /*
5119 * The kernel map covers two distinct regions of KVA: that used
5120 * for dynamic kernel memory allocations, and the uppermost 2GB
5121 * of the virtual address space. The latter is used to map the
5122 * kernel and loadable kernel modules. This scheme enables the
5123 * use of a special code generation model for kernel code which
5124 * takes advantage of compact addressing modes in machine code.
5125 *
5126 * Both regions grow upwards; to avoid wasting memory, the gap
5127 * in between is unmapped. If "addr" is above "KERNBASE", the
5128 * kernel's region is grown, otherwise the kmem region is grown.
5129 *
5130 * The correctness of this action is based on the following
5131 * argument: vm_map_insert() allocates contiguous ranges of the
5132 * kernel virtual address space. It calls this function if a range
5133 * ends after "kernel_vm_end". If the kernel is mapped between
5134 * "kernel_vm_end" and "addr", then the range cannot begin at
5135 * "kernel_vm_end". In fact, its beginning address cannot be less
5136 * than the kernel. Thus, there is no immediate need to allocate
5137 * any new kernel page table pages between "kernel_vm_end" and
5138 * "KERNBASE".
5139 */
5140 if (KERNBASE < addr) {
5141 end = KERNBASE + nkpt * NBPDR;
5142 if (end == 0) {
5143 TSEXIT();
5144 return;
5145 }
5146 } else {
5147 end = kernel_vm_end;
5148 }
5149
5150 addr = roundup2(addr, NBPDR);
5151 if (addr - 1 >= vm_map_max(kernel_map))
5152 addr = vm_map_max(kernel_map);
5153 if (addr <= end) {
5154 /*
5155 * The grown region is already mapped, so there is
5156 * nothing to do.
5157 */
5158 TSEXIT();
5159 return;
5160 }
5161
5162 kasan_shadow_map(end, addr - end);
5163 kmsan_shadow_map(end, addr - end);
5164 while (end < addr) {
5165 pdpe = pmap_pdpe(kernel_pmap, end);
5166 if ((*pdpe & X86_PG_V) == 0) {
5167 nkpg = pmap_alloc_pt_page(kernel_pmap,
5168 pmap_pdpe_pindex(end), VM_ALLOC_INTERRUPT |
5169 VM_ALLOC_NOFREE | VM_ALLOC_WIRED | VM_ALLOC_ZERO);
5170 if (nkpg == NULL)
5171 panic("pmap_growkernel: no memory to grow kernel");
5172 paddr = VM_PAGE_TO_PHYS(nkpg);
5173 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
5174 X86_PG_A | X86_PG_M);
5175 continue; /* try again */
5176 }
5177 pde = pmap_pdpe_to_pde(pdpe, end);
5178 if ((*pde & X86_PG_V) != 0) {
5179 end = (end + NBPDR) & ~PDRMASK;
5180 if (end - 1 >= vm_map_max(kernel_map)) {
5181 end = vm_map_max(kernel_map);
5182 break;
5183 }
5184 continue;
5185 }
5186
5187 nkpg = pmap_alloc_pt_page(kernel_pmap, pmap_pde_pindex(end),
5188 VM_ALLOC_INTERRUPT | VM_ALLOC_NOFREE | VM_ALLOC_WIRED |
5189 VM_ALLOC_ZERO);
5190 if (nkpg == NULL)
5191 panic("pmap_growkernel: no memory to grow kernel");
5192 paddr = VM_PAGE_TO_PHYS(nkpg);
5193 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
5194 pde_store(pde, newpdir);
5195
5196 end = (end + NBPDR) & ~PDRMASK;
5197 if (end - 1 >= vm_map_max(kernel_map)) {
5198 end = vm_map_max(kernel_map);
5199 break;
5200 }
5201 }
5202
5203 if (end <= KERNBASE)
5204 kernel_vm_end = end;
5205 else
5206 nkpt = howmany(end - KERNBASE, NBPDR);
5207 TSEXIT();
5208 }
5209
5210 /***************************************************
5211 * page management routines.
5212 ***************************************************/
5213
5214 static const uint64_t pc_freemask[_NPCM] = {
5215 [0 ... _NPCM - 2] = PC_FREEN,
5216 [_NPCM - 1] = PC_FREEL
5217 };
5218
5219 #ifdef PV_STATS
5220
5221 static COUNTER_U64_DEFINE_EARLY(pc_chunk_count);
5222 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD,
5223 &pc_chunk_count, "Current number of pv entry cnunks");
5224
5225 static COUNTER_U64_DEFINE_EARLY(pc_chunk_allocs);
5226 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD,
5227 &pc_chunk_allocs, "Total number of pv entry chunks allocated");
5228
5229 static COUNTER_U64_DEFINE_EARLY(pc_chunk_frees);
5230 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD,
5231 &pc_chunk_frees, "Total number of pv entry chunks freed");
5232
5233 static COUNTER_U64_DEFINE_EARLY(pc_chunk_tryfail);
5234 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD,
5235 &pc_chunk_tryfail,
5236 "Number of failed attempts to get a pv entry chunk page");
5237
5238 static COUNTER_U64_DEFINE_EARLY(pv_entry_frees);
5239 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD,
5240 &pv_entry_frees, "Total number of pv entries freed");
5241
5242 static COUNTER_U64_DEFINE_EARLY(pv_entry_allocs);
5243 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD,
5244 &pv_entry_allocs, "Total number of pv entries allocated");
5245
5246 static COUNTER_U64_DEFINE_EARLY(pv_entry_count);
5247 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD,
5248 &pv_entry_count, "Current number of pv entries");
5249
5250 static COUNTER_U64_DEFINE_EARLY(pv_entry_spare);
5251 SYSCTL_COUNTER_U64(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD,
5252 &pv_entry_spare, "Current number of spare pv entries");
5253 #endif
5254
5255 static void
reclaim_pv_chunk_leave_pmap(pmap_t pmap,pmap_t locked_pmap,bool start_di)5256 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
5257 {
5258
5259 if (pmap == NULL)
5260 return;
5261 pmap_invalidate_all(pmap);
5262 if (pmap != locked_pmap)
5263 PMAP_UNLOCK(pmap);
5264 if (start_di)
5265 pmap_delayed_invl_finish();
5266 }
5267
5268 /*
5269 * We are in a serious low memory condition. Resort to
5270 * drastic measures to free some pages so we can allocate
5271 * another pv entry chunk.
5272 *
5273 * Returns NULL if PV entries were reclaimed from the specified pmap.
5274 *
5275 * We do not, however, unmap 2mpages because subsequent accesses will
5276 * allocate per-page pv entries until repromotion occurs, thereby
5277 * exacerbating the shortage of free pv entries.
5278 */
5279 static vm_page_t
reclaim_pv_chunk_domain(pmap_t locked_pmap,struct rwlock ** lockp,int domain)5280 reclaim_pv_chunk_domain(pmap_t locked_pmap, struct rwlock **lockp, int domain)
5281 {
5282 struct pv_chunks_list *pvc;
5283 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
5284 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
5285 struct md_page *pvh;
5286 pd_entry_t *pde;
5287 pmap_t next_pmap, pmap;
5288 pt_entry_t *pte, tpte;
5289 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
5290 pv_entry_t pv;
5291 vm_offset_t va;
5292 vm_page_t m, m_pc;
5293 struct spglist free;
5294 uint64_t inuse;
5295 int bit, field, freed;
5296 bool start_di, restart;
5297
5298 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
5299 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
5300 pmap = NULL;
5301 m_pc = NULL;
5302 PG_G = PG_A = PG_M = PG_RW = 0;
5303 SLIST_INIT(&free);
5304 bzero(&pc_marker_b, sizeof(pc_marker_b));
5305 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
5306 pc_marker = (struct pv_chunk *)&pc_marker_b;
5307 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
5308
5309 /*
5310 * A delayed invalidation block should already be active if
5311 * pmap_advise() or pmap_remove() called this function by way
5312 * of pmap_demote_pde_locked().
5313 */
5314 start_di = pmap_not_in_di();
5315
5316 pvc = &pv_chunks[domain];
5317 mtx_lock(&pvc->pvc_lock);
5318 pvc->active_reclaims++;
5319 TAILQ_INSERT_HEAD(&pvc->pvc_list, pc_marker, pc_lru);
5320 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc_marker_end, pc_lru);
5321 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
5322 SLIST_EMPTY(&free)) {
5323 next_pmap = pc->pc_pmap;
5324 if (next_pmap == NULL) {
5325 /*
5326 * The next chunk is a marker. However, it is
5327 * not our marker, so active_reclaims must be
5328 * > 1. Consequently, the next_chunk code
5329 * will not rotate the pv_chunks list.
5330 */
5331 goto next_chunk;
5332 }
5333 mtx_unlock(&pvc->pvc_lock);
5334
5335 /*
5336 * A pv_chunk can only be removed from the pc_lru list
5337 * when both pc_chunks_mutex is owned and the
5338 * corresponding pmap is locked.
5339 */
5340 if (pmap != next_pmap) {
5341 restart = false;
5342 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
5343 start_di);
5344 pmap = next_pmap;
5345 /* Avoid deadlock and lock recursion. */
5346 if (pmap > locked_pmap) {
5347 RELEASE_PV_LIST_LOCK(lockp);
5348 PMAP_LOCK(pmap);
5349 if (start_di)
5350 pmap_delayed_invl_start();
5351 mtx_lock(&pvc->pvc_lock);
5352 restart = true;
5353 } else if (pmap != locked_pmap) {
5354 if (PMAP_TRYLOCK(pmap)) {
5355 if (start_di)
5356 pmap_delayed_invl_start();
5357 mtx_lock(&pvc->pvc_lock);
5358 restart = true;
5359 } else {
5360 pmap = NULL; /* pmap is not locked */
5361 mtx_lock(&pvc->pvc_lock);
5362 pc = TAILQ_NEXT(pc_marker, pc_lru);
5363 if (pc == NULL ||
5364 pc->pc_pmap != next_pmap)
5365 continue;
5366 goto next_chunk;
5367 }
5368 } else if (start_di)
5369 pmap_delayed_invl_start();
5370 PG_G = pmap_global_bit(pmap);
5371 PG_A = pmap_accessed_bit(pmap);
5372 PG_M = pmap_modified_bit(pmap);
5373 PG_RW = pmap_rw_bit(pmap);
5374 if (restart)
5375 continue;
5376 }
5377
5378 /*
5379 * Destroy every non-wired, 4 KB page mapping in the chunk.
5380 */
5381 freed = 0;
5382 for (field = 0; field < _NPCM; field++) {
5383 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
5384 inuse != 0; inuse &= ~(1UL << bit)) {
5385 bit = bsfq(inuse);
5386 pv = &pc->pc_pventry[field * 64 + bit];
5387 va = pv->pv_va;
5388 pde = pmap_pde(pmap, va);
5389 if ((*pde & PG_PS) != 0)
5390 continue;
5391 pte = pmap_pde_to_pte(pde, va);
5392 if ((*pte & PG_W) != 0)
5393 continue;
5394 tpte = pte_load_clear(pte);
5395 if ((tpte & PG_G) != 0)
5396 pmap_invalidate_page(pmap, va);
5397 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
5398 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5399 vm_page_dirty(m);
5400 if ((tpte & PG_A) != 0)
5401 vm_page_aflag_set(m, PGA_REFERENCED);
5402 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
5403 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
5404 m->md.pv_gen++;
5405 if (TAILQ_EMPTY(&m->md.pv_list) &&
5406 (m->flags & PG_FICTITIOUS) == 0) {
5407 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5408 if (TAILQ_EMPTY(&pvh->pv_list)) {
5409 vm_page_aflag_clear(m,
5410 PGA_WRITEABLE);
5411 }
5412 }
5413 pmap_delayed_invl_page(m);
5414 pc->pc_map[field] |= 1UL << bit;
5415 pmap_unuse_pt(pmap, va, *pde, &free);
5416 freed++;
5417 }
5418 }
5419 if (freed == 0) {
5420 mtx_lock(&pvc->pvc_lock);
5421 goto next_chunk;
5422 }
5423 /* Every freed mapping is for a 4 KB page. */
5424 pmap_resident_count_adj(pmap, -freed);
5425 PV_STAT(counter_u64_add(pv_entry_frees, freed));
5426 PV_STAT(counter_u64_add(pv_entry_spare, freed));
5427 PV_STAT(counter_u64_add(pv_entry_count, -freed));
5428 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5429 if (pc_is_free(pc)) {
5430 PV_STAT(counter_u64_add(pv_entry_spare, -_NPCPV));
5431 PV_STAT(counter_u64_add(pc_chunk_count, -1));
5432 PV_STAT(counter_u64_add(pc_chunk_frees, 1));
5433 /* Entire chunk is free; return it. */
5434 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
5435 dump_drop_page(m_pc->phys_addr);
5436 mtx_lock(&pvc->pvc_lock);
5437 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5438 break;
5439 }
5440 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5441 mtx_lock(&pvc->pvc_lock);
5442 /* One freed pv entry in locked_pmap is sufficient. */
5443 if (pmap == locked_pmap)
5444 break;
5445 next_chunk:
5446 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
5447 TAILQ_INSERT_AFTER(&pvc->pvc_list, pc, pc_marker, pc_lru);
5448 if (pvc->active_reclaims == 1 && pmap != NULL) {
5449 /*
5450 * Rotate the pv chunks list so that we do not
5451 * scan the same pv chunks that could not be
5452 * freed (because they contained a wired
5453 * and/or superpage mapping) on every
5454 * invocation of reclaim_pv_chunk().
5455 */
5456 while ((pc = TAILQ_FIRST(&pvc->pvc_list)) != pc_marker) {
5457 MPASS(pc->pc_pmap != NULL);
5458 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5459 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
5460 }
5461 }
5462 }
5463 TAILQ_REMOVE(&pvc->pvc_list, pc_marker, pc_lru);
5464 TAILQ_REMOVE(&pvc->pvc_list, pc_marker_end, pc_lru);
5465 pvc->active_reclaims--;
5466 mtx_unlock(&pvc->pvc_lock);
5467 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
5468 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
5469 m_pc = SLIST_FIRST(&free);
5470 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
5471 /* Recycle a freed page table page. */
5472 m_pc->ref_count = 1;
5473 }
5474 vm_page_free_pages_toq(&free, true);
5475 return (m_pc);
5476 }
5477
5478 static vm_page_t
reclaim_pv_chunk(pmap_t locked_pmap,struct rwlock ** lockp)5479 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
5480 {
5481 vm_page_t m;
5482 int i, domain;
5483
5484 domain = PCPU_GET(domain);
5485 for (i = 0; i < vm_ndomains; i++) {
5486 m = reclaim_pv_chunk_domain(locked_pmap, lockp, domain);
5487 if (m != NULL)
5488 break;
5489 domain = (domain + 1) % vm_ndomains;
5490 }
5491
5492 return (m);
5493 }
5494
5495 /*
5496 * free the pv_entry back to the free list
5497 */
5498 static void
free_pv_entry(pmap_t pmap,pv_entry_t pv)5499 free_pv_entry(pmap_t pmap, pv_entry_t pv)
5500 {
5501 struct pv_chunk *pc;
5502 int idx, field, bit;
5503
5504 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5505 PV_STAT(counter_u64_add(pv_entry_frees, 1));
5506 PV_STAT(counter_u64_add(pv_entry_spare, 1));
5507 PV_STAT(counter_u64_add(pv_entry_count, -1));
5508 pc = pv_to_chunk(pv);
5509 idx = pv - &pc->pc_pventry[0];
5510 field = idx / 64;
5511 bit = idx % 64;
5512 pc->pc_map[field] |= 1ul << bit;
5513 if (!pc_is_free(pc)) {
5514 /* 98% of the time, pc is already at the head of the list. */
5515 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
5516 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5517 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5518 }
5519 return;
5520 }
5521 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5522 free_pv_chunk(pc);
5523 }
5524
5525 static void
free_pv_chunk_dequeued(struct pv_chunk * pc)5526 free_pv_chunk_dequeued(struct pv_chunk *pc)
5527 {
5528 vm_page_t m;
5529
5530 PV_STAT(counter_u64_add(pv_entry_spare, -_NPCPV));
5531 PV_STAT(counter_u64_add(pc_chunk_count, -1));
5532 PV_STAT(counter_u64_add(pc_chunk_frees, 1));
5533 counter_u64_add(pv_page_count, -1);
5534 /* entire chunk is free, return it */
5535 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
5536 dump_drop_page(m->phys_addr);
5537 vm_page_unwire_noq(m);
5538 vm_page_free(m);
5539 }
5540
5541 static void
free_pv_chunk(struct pv_chunk * pc)5542 free_pv_chunk(struct pv_chunk *pc)
5543 {
5544 struct pv_chunks_list *pvc;
5545
5546 pvc = &pv_chunks[pc_to_domain(pc)];
5547 mtx_lock(&pvc->pvc_lock);
5548 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5549 mtx_unlock(&pvc->pvc_lock);
5550 free_pv_chunk_dequeued(pc);
5551 }
5552
5553 static void
free_pv_chunk_batch(struct pv_chunklist * batch)5554 free_pv_chunk_batch(struct pv_chunklist *batch)
5555 {
5556 struct pv_chunks_list *pvc;
5557 struct pv_chunk *pc, *npc;
5558 int i;
5559
5560 for (i = 0; i < vm_ndomains; i++) {
5561 if (TAILQ_EMPTY(&batch[i]))
5562 continue;
5563 pvc = &pv_chunks[i];
5564 mtx_lock(&pvc->pvc_lock);
5565 TAILQ_FOREACH(pc, &batch[i], pc_list) {
5566 TAILQ_REMOVE(&pvc->pvc_list, pc, pc_lru);
5567 }
5568 mtx_unlock(&pvc->pvc_lock);
5569 }
5570
5571 for (i = 0; i < vm_ndomains; i++) {
5572 TAILQ_FOREACH_SAFE(pc, &batch[i], pc_list, npc) {
5573 free_pv_chunk_dequeued(pc);
5574 }
5575 }
5576 }
5577
5578 /*
5579 * Returns a new PV entry, allocating a new PV chunk from the system when
5580 * needed. If this PV chunk allocation fails and a PV list lock pointer was
5581 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
5582 * returned.
5583 *
5584 * The given PV list lock may be released.
5585 */
5586 static pv_entry_t
get_pv_entry(pmap_t pmap,struct rwlock ** lockp)5587 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
5588 {
5589 struct pv_chunks_list *pvc;
5590 int bit, field;
5591 pv_entry_t pv;
5592 struct pv_chunk *pc;
5593 vm_page_t m;
5594
5595 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5596 PV_STAT(counter_u64_add(pv_entry_allocs, 1));
5597 retry:
5598 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
5599 if (pc != NULL) {
5600 for (field = 0; field < _NPCM; field++) {
5601 if (pc->pc_map[field]) {
5602 bit = bsfq(pc->pc_map[field]);
5603 break;
5604 }
5605 }
5606 if (field < _NPCM) {
5607 pv = &pc->pc_pventry[field * 64 + bit];
5608 pc->pc_map[field] &= ~(1ul << bit);
5609 /* If this was the last item, move it to tail */
5610 if (pc_is_full(pc)) {
5611 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5612 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
5613 pc_list);
5614 }
5615 PV_STAT(counter_u64_add(pv_entry_count, 1));
5616 PV_STAT(counter_u64_add(pv_entry_spare, -1));
5617 return (pv);
5618 }
5619 }
5620 /* No free items, allocate another chunk */
5621 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
5622 if (m == NULL) {
5623 if (lockp == NULL) {
5624 PV_STAT(counter_u64_add(pc_chunk_tryfail, 1));
5625 return (NULL);
5626 }
5627 m = reclaim_pv_chunk(pmap, lockp);
5628 if (m == NULL)
5629 goto retry;
5630 } else
5631 counter_u64_add(pv_page_count, 1);
5632 PV_STAT(counter_u64_add(pc_chunk_count, 1));
5633 PV_STAT(counter_u64_add(pc_chunk_allocs, 1));
5634 dump_add_page(m->phys_addr);
5635 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
5636 pc->pc_pmap = pmap;
5637 pc->pc_map[0] = PC_FREEN & ~1ul; /* preallocated bit 0 */
5638 pc->pc_map[1] = PC_FREEN;
5639 pc->pc_map[2] = PC_FREEL;
5640 pvc = &pv_chunks[vm_page_domain(m)];
5641 mtx_lock(&pvc->pvc_lock);
5642 TAILQ_INSERT_TAIL(&pvc->pvc_list, pc, pc_lru);
5643 mtx_unlock(&pvc->pvc_lock);
5644 pv = &pc->pc_pventry[0];
5645 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5646 PV_STAT(counter_u64_add(pv_entry_count, 1));
5647 PV_STAT(counter_u64_add(pv_entry_spare, _NPCPV - 1));
5648 return (pv);
5649 }
5650
5651 /*
5652 * Returns the number of one bits within the given PV chunk map.
5653 *
5654 * The erratas for Intel processors state that "POPCNT Instruction May
5655 * Take Longer to Execute Than Expected". It is believed that the
5656 * issue is the spurious dependency on the destination register.
5657 * Provide a hint to the register rename logic that the destination
5658 * value is overwritten, by clearing it, as suggested in the
5659 * optimization manual. It should be cheap for unaffected processors
5660 * as well.
5661 *
5662 * Reference numbers for erratas are
5663 * 4th Gen Core: HSD146
5664 * 5th Gen Core: BDM85
5665 * 6th Gen Core: SKL029
5666 */
5667 static int
popcnt_pc_map_pq(uint64_t * map)5668 popcnt_pc_map_pq(uint64_t *map)
5669 {
5670 u_long result, tmp;
5671
5672 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
5673 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
5674 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
5675 : "=&r" (result), "=&r" (tmp)
5676 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
5677 return (result);
5678 }
5679
5680 /*
5681 * Ensure that the number of spare PV entries in the specified pmap meets or
5682 * exceeds the given count, "needed".
5683 *
5684 * The given PV list lock may be released.
5685 */
5686 static void
reserve_pv_entries(pmap_t pmap,int needed,struct rwlock ** lockp)5687 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
5688 {
5689 struct pv_chunks_list *pvc;
5690 struct pch new_tail[PMAP_MEMDOM];
5691 struct pv_chunk *pc;
5692 vm_page_t m;
5693 int avail, free, i;
5694 bool reclaimed;
5695
5696 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5697 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
5698
5699 /*
5700 * Newly allocated PV chunks must be stored in a private list until
5701 * the required number of PV chunks have been allocated. Otherwise,
5702 * reclaim_pv_chunk() could recycle one of these chunks. In
5703 * contrast, these chunks must be added to the pmap upon allocation.
5704 */
5705 for (i = 0; i < PMAP_MEMDOM; i++)
5706 TAILQ_INIT(&new_tail[i]);
5707 retry:
5708 avail = 0;
5709 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
5710 #ifndef __POPCNT__
5711 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
5712 bit_count((bitstr_t *)pc->pc_map, 0,
5713 sizeof(pc->pc_map) * NBBY, &free);
5714 else
5715 #endif
5716 free = popcnt_pc_map_pq(pc->pc_map);
5717 if (free == 0)
5718 break;
5719 avail += free;
5720 if (avail >= needed)
5721 break;
5722 }
5723 for (reclaimed = false; avail < needed; avail += _NPCPV) {
5724 m = vm_page_alloc_noobj(VM_ALLOC_WIRED);
5725 if (m == NULL) {
5726 m = reclaim_pv_chunk(pmap, lockp);
5727 if (m == NULL)
5728 goto retry;
5729 reclaimed = true;
5730 } else
5731 counter_u64_add(pv_page_count, 1);
5732 PV_STAT(counter_u64_add(pc_chunk_count, 1));
5733 PV_STAT(counter_u64_add(pc_chunk_allocs, 1));
5734 dump_add_page(m->phys_addr);
5735 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
5736 pc->pc_pmap = pmap;
5737 pc->pc_map[0] = PC_FREEN;
5738 pc->pc_map[1] = PC_FREEN;
5739 pc->pc_map[2] = PC_FREEL;
5740 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
5741 TAILQ_INSERT_TAIL(&new_tail[vm_page_domain(m)], pc, pc_lru);
5742 PV_STAT(counter_u64_add(pv_entry_spare, _NPCPV));
5743
5744 /*
5745 * The reclaim might have freed a chunk from the current pmap.
5746 * If that chunk contained available entries, we need to
5747 * re-count the number of available entries.
5748 */
5749 if (reclaimed)
5750 goto retry;
5751 }
5752 for (i = 0; i < vm_ndomains; i++) {
5753 if (TAILQ_EMPTY(&new_tail[i]))
5754 continue;
5755 pvc = &pv_chunks[i];
5756 mtx_lock(&pvc->pvc_lock);
5757 TAILQ_CONCAT(&pvc->pvc_list, &new_tail[i], pc_lru);
5758 mtx_unlock(&pvc->pvc_lock);
5759 }
5760 }
5761
5762 /*
5763 * First find and then remove the pv entry for the specified pmap and virtual
5764 * address from the specified pv list. Returns the pv entry if found and NULL
5765 * otherwise. This operation can be performed on pv lists for either 4KB or
5766 * 2MB page mappings.
5767 */
5768 static __inline pv_entry_t
pmap_pvh_remove(struct md_page * pvh,pmap_t pmap,vm_offset_t va)5769 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
5770 {
5771 pv_entry_t pv;
5772
5773 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5774 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
5775 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
5776 pvh->pv_gen++;
5777 break;
5778 }
5779 }
5780 return (pv);
5781 }
5782
5783 /*
5784 * After demotion from a 2MB page mapping to 512 4KB page mappings,
5785 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
5786 * entries for each of the 4KB page mappings.
5787 */
5788 static void
pmap_pv_demote_pde(pmap_t pmap,vm_offset_t va,vm_paddr_t pa,struct rwlock ** lockp)5789 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
5790 struct rwlock **lockp)
5791 {
5792 struct md_page *pvh;
5793 struct pv_chunk *pc;
5794 pv_entry_t pv;
5795 vm_offset_t va_last;
5796 vm_page_t m;
5797 int bit, field;
5798
5799 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5800 KASSERT((pa & PDRMASK) == 0,
5801 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
5802 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5803
5804 /*
5805 * Transfer the 2mpage's pv entry for this mapping to the first
5806 * page's pv list. Once this transfer begins, the pv list lock
5807 * must not be released until the last pv entry is reinstantiated.
5808 */
5809 pvh = pa_to_pvh(pa);
5810 va = trunc_2mpage(va);
5811 pv = pmap_pvh_remove(pvh, pmap, va);
5812 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
5813 m = PHYS_TO_VM_PAGE(pa);
5814 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5815 m->md.pv_gen++;
5816 /* Instantiate the remaining NPTEPG - 1 pv entries. */
5817 PV_STAT(counter_u64_add(pv_entry_allocs, NPTEPG - 1));
5818 va_last = va + NBPDR - PAGE_SIZE;
5819 for (;;) {
5820 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
5821 KASSERT(!pc_is_full(pc), ("pmap_pv_demote_pde: missing spare"));
5822 for (field = 0; field < _NPCM; field++) {
5823 while (pc->pc_map[field]) {
5824 bit = bsfq(pc->pc_map[field]);
5825 pc->pc_map[field] &= ~(1ul << bit);
5826 pv = &pc->pc_pventry[field * 64 + bit];
5827 va += PAGE_SIZE;
5828 pv->pv_va = va;
5829 m++;
5830 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5831 ("pmap_pv_demote_pde: page %p is not managed", m));
5832 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5833 m->md.pv_gen++;
5834 if (va == va_last)
5835 goto out;
5836 }
5837 }
5838 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5839 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
5840 }
5841 out:
5842 if (pc_is_full(pc)) {
5843 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
5844 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
5845 }
5846 PV_STAT(counter_u64_add(pv_entry_count, NPTEPG - 1));
5847 PV_STAT(counter_u64_add(pv_entry_spare, -(NPTEPG - 1)));
5848 }
5849
5850 #if VM_NRESERVLEVEL > 0
5851 /*
5852 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
5853 * replace the many pv entries for the 4KB page mappings by a single pv entry
5854 * for the 2MB page mapping.
5855 */
5856 static void
pmap_pv_promote_pde(pmap_t pmap,vm_offset_t va,vm_paddr_t pa,struct rwlock ** lockp)5857 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
5858 struct rwlock **lockp)
5859 {
5860 struct md_page *pvh;
5861 pv_entry_t pv;
5862 vm_offset_t va_last;
5863 vm_page_t m;
5864
5865 KASSERT((pa & PDRMASK) == 0,
5866 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
5867 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5868
5869 /*
5870 * Transfer the first page's pv entry for this mapping to the 2mpage's
5871 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
5872 * a transfer avoids the possibility that get_pv_entry() calls
5873 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
5874 * mappings that is being promoted.
5875 */
5876 m = PHYS_TO_VM_PAGE(pa);
5877 va = trunc_2mpage(va);
5878 pv = pmap_pvh_remove(&m->md, pmap, va);
5879 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
5880 pvh = pa_to_pvh(pa);
5881 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5882 pvh->pv_gen++;
5883 /* Free the remaining NPTEPG - 1 pv entries. */
5884 va_last = va + NBPDR - PAGE_SIZE;
5885 do {
5886 m++;
5887 va += PAGE_SIZE;
5888 pmap_pvh_free(&m->md, pmap, va);
5889 } while (va < va_last);
5890 }
5891 #endif /* VM_NRESERVLEVEL > 0 */
5892
5893 /*
5894 * First find and then destroy the pv entry for the specified pmap and virtual
5895 * address. This operation can be performed on pv lists for either 4KB or 2MB
5896 * page mappings.
5897 */
5898 static void
pmap_pvh_free(struct md_page * pvh,pmap_t pmap,vm_offset_t va)5899 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
5900 {
5901 pv_entry_t pv;
5902
5903 pv = pmap_pvh_remove(pvh, pmap, va);
5904 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
5905 free_pv_entry(pmap, pv);
5906 }
5907
5908 /*
5909 * Conditionally create the PV entry for a 4KB page mapping if the required
5910 * memory can be allocated without resorting to reclamation.
5911 */
5912 static bool
pmap_try_insert_pv_entry(pmap_t pmap,vm_offset_t va,vm_page_t m,struct rwlock ** lockp)5913 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
5914 struct rwlock **lockp)
5915 {
5916 pv_entry_t pv;
5917
5918 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5919 /* Pass NULL instead of the lock pointer to disable reclamation. */
5920 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
5921 pv->pv_va = va;
5922 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
5923 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
5924 m->md.pv_gen++;
5925 return (true);
5926 } else
5927 return (false);
5928 }
5929
5930 /*
5931 * Create the PV entry for a 2MB page mapping. Always returns true unless the
5932 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
5933 * false if the PV entry cannot be allocated without resorting to reclamation.
5934 */
5935 static bool
pmap_pv_insert_pde(pmap_t pmap,vm_offset_t va,pd_entry_t pde,u_int flags,struct rwlock ** lockp)5936 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
5937 struct rwlock **lockp)
5938 {
5939 struct md_page *pvh;
5940 pv_entry_t pv;
5941 vm_paddr_t pa;
5942
5943 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5944 /* Pass NULL instead of the lock pointer to disable reclamation. */
5945 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
5946 NULL : lockp)) == NULL)
5947 return (false);
5948 pv->pv_va = va;
5949 pa = pde & PG_PS_FRAME;
5950 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
5951 pvh = pa_to_pvh(pa);
5952 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
5953 pvh->pv_gen++;
5954 return (true);
5955 }
5956
5957 /*
5958 * Fills a page table page with mappings to consecutive physical pages.
5959 */
5960 static void
pmap_fill_ptp(pt_entry_t * firstpte,pt_entry_t newpte)5961 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
5962 {
5963 pt_entry_t *pte;
5964
5965 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
5966 *pte = newpte;
5967 newpte += PAGE_SIZE;
5968 }
5969 }
5970
5971 /*
5972 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
5973 * mapping is invalidated.
5974 */
5975 static bool
pmap_demote_pde(pmap_t pmap,pd_entry_t * pde,vm_offset_t va)5976 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
5977 {
5978 struct rwlock *lock;
5979 bool rv;
5980
5981 lock = NULL;
5982 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
5983 if (lock != NULL)
5984 rw_wunlock(lock);
5985 return (rv);
5986 }
5987
5988 static void
pmap_demote_pde_check(pt_entry_t * firstpte __unused,pt_entry_t newpte __unused)5989 pmap_demote_pde_check(pt_entry_t *firstpte __unused, pt_entry_t newpte __unused)
5990 {
5991 #ifdef INVARIANTS
5992 #ifdef DIAGNOSTIC
5993 pt_entry_t *xpte, *ypte;
5994
5995 for (xpte = firstpte; xpte < firstpte + NPTEPG;
5996 xpte++, newpte += PAGE_SIZE) {
5997 if ((*xpte & PG_FRAME) != (newpte & PG_FRAME)) {
5998 printf("pmap_demote_pde: xpte %zd and newpte map "
5999 "different pages: found %#lx, expected %#lx\n",
6000 xpte - firstpte, *xpte, newpte);
6001 printf("page table dump\n");
6002 for (ypte = firstpte; ypte < firstpte + NPTEPG; ypte++)
6003 printf("%zd %#lx\n", ypte - firstpte, *ypte);
6004 panic("firstpte");
6005 }
6006 }
6007 #else
6008 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
6009 ("pmap_demote_pde: firstpte and newpte map different physical"
6010 " addresses"));
6011 #endif
6012 #endif
6013 }
6014
6015 static void
pmap_demote_pde_abort(pmap_t pmap,vm_offset_t va,pd_entry_t * pde,pd_entry_t oldpde,struct rwlock ** lockp)6016 pmap_demote_pde_abort(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
6017 pd_entry_t oldpde, struct rwlock **lockp)
6018 {
6019 struct spglist free;
6020 vm_offset_t sva;
6021
6022 SLIST_INIT(&free);
6023 sva = trunc_2mpage(va);
6024 pmap_remove_pde(pmap, pde, sva, &free, lockp);
6025 if ((oldpde & pmap_global_bit(pmap)) == 0)
6026 pmap_invalidate_pde_page(pmap, sva, oldpde);
6027 vm_page_free_pages_toq(&free, true);
6028 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx in pmap %p",
6029 va, pmap);
6030 }
6031
6032 static bool
pmap_demote_pde_locked(pmap_t pmap,pd_entry_t * pde,vm_offset_t va,struct rwlock ** lockp)6033 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
6034 struct rwlock **lockp)
6035 {
6036 pd_entry_t newpde, oldpde;
6037 pt_entry_t *firstpte, newpte;
6038 pt_entry_t PG_A, PG_G, PG_M, PG_PKU_MASK, PG_RW, PG_V;
6039 vm_paddr_t mptepa;
6040 vm_page_t mpte;
6041 int PG_PTE_CACHE;
6042 bool in_kernel;
6043
6044 PG_A = pmap_accessed_bit(pmap);
6045 PG_G = pmap_global_bit(pmap);
6046 PG_M = pmap_modified_bit(pmap);
6047 PG_RW = pmap_rw_bit(pmap);
6048 PG_V = pmap_valid_bit(pmap);
6049 PG_PTE_CACHE = pmap_cache_mask(pmap, false);
6050 PG_PKU_MASK = pmap_pku_mask_bit(pmap);
6051
6052 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6053 in_kernel = va >= VM_MAXUSER_ADDRESS;
6054 oldpde = *pde;
6055 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
6056 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
6057
6058 /*
6059 * Invalidate the 2MB page mapping and return "failure" if the
6060 * mapping was never accessed.
6061 */
6062 if ((oldpde & PG_A) == 0) {
6063 KASSERT((oldpde & PG_W) == 0,
6064 ("pmap_demote_pde: a wired mapping is missing PG_A"));
6065 pmap_demote_pde_abort(pmap, va, pde, oldpde, lockp);
6066 return (false);
6067 }
6068
6069 mpte = pmap_remove_pt_page(pmap, va);
6070 if (mpte == NULL) {
6071 KASSERT((oldpde & PG_W) == 0,
6072 ("pmap_demote_pde: page table page for a wired mapping"
6073 " is missing"));
6074
6075 /*
6076 * If the page table page is missing and the mapping
6077 * is for a kernel address, the mapping must belong to
6078 * the direct map. Page table pages are preallocated
6079 * for every other part of the kernel address space,
6080 * so the direct map region is the only part of the
6081 * kernel address space that must be handled here.
6082 */
6083 KASSERT(!in_kernel || (va >= DMAP_MIN_ADDRESS &&
6084 va < DMAP_MAX_ADDRESS),
6085 ("pmap_demote_pde: No saved mpte for va %#lx", va));
6086
6087 /*
6088 * If the 2MB page mapping belongs to the direct map
6089 * region of the kernel's address space, then the page
6090 * allocation request specifies the highest possible
6091 * priority (VM_ALLOC_INTERRUPT). Otherwise, the
6092 * priority is normal.
6093 */
6094 mpte = pmap_alloc_pt_page(pmap, pmap_pde_pindex(va),
6095 (in_kernel ? VM_ALLOC_INTERRUPT : 0) | VM_ALLOC_WIRED);
6096
6097 /*
6098 * If the allocation of the new page table page fails,
6099 * invalidate the 2MB page mapping and return "failure".
6100 */
6101 if (mpte == NULL) {
6102 pmap_demote_pde_abort(pmap, va, pde, oldpde, lockp);
6103 return (false);
6104 }
6105
6106 if (!in_kernel)
6107 mpte->ref_count = NPTEPG;
6108 }
6109 mptepa = VM_PAGE_TO_PHYS(mpte);
6110 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
6111 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
6112 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
6113 ("pmap_demote_pde: oldpde is missing PG_M"));
6114 newpte = oldpde & ~PG_PS;
6115 newpte = pmap_swap_pat(pmap, newpte);
6116
6117 /*
6118 * If the PTP is not leftover from an earlier promotion or it does not
6119 * have PG_A set in every PTE, then fill it. The new PTEs will all
6120 * have PG_A set.
6121 */
6122 if (!vm_page_all_valid(mpte))
6123 pmap_fill_ptp(firstpte, newpte);
6124
6125 pmap_demote_pde_check(firstpte, newpte);
6126
6127 /*
6128 * If the mapping has changed attributes, update the PTEs.
6129 */
6130 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
6131 pmap_fill_ptp(firstpte, newpte);
6132
6133 /*
6134 * The spare PV entries must be reserved prior to demoting the
6135 * mapping, that is, prior to changing the PDE. Otherwise, the state
6136 * of the PDE and the PV lists will be inconsistent, which can result
6137 * in reclaim_pv_chunk() attempting to remove a PV entry from the
6138 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
6139 * PV entry for the 2MB page mapping that is being demoted.
6140 */
6141 if ((oldpde & PG_MANAGED) != 0)
6142 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
6143
6144 /*
6145 * Demote the mapping. This pmap is locked. The old PDE has
6146 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
6147 * set. Thus, there is no danger of a race with another
6148 * processor changing the setting of PG_A and/or PG_M between
6149 * the read above and the store below.
6150 */
6151 if (workaround_erratum383)
6152 pmap_update_pde(pmap, va, pde, newpde);
6153 else
6154 pde_store(pde, newpde);
6155
6156 /*
6157 * Invalidate a stale recursive mapping of the page table page.
6158 */
6159 if (in_kernel)
6160 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
6161
6162 /*
6163 * Demote the PV entry.
6164 */
6165 if ((oldpde & PG_MANAGED) != 0)
6166 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
6167
6168 counter_u64_add(pmap_pde_demotions, 1);
6169 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx in pmap %p",
6170 va, pmap);
6171 return (true);
6172 }
6173
6174 /*
6175 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
6176 */
6177 static void
pmap_remove_kernel_pde(pmap_t pmap,pd_entry_t * pde,vm_offset_t va)6178 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
6179 {
6180 pd_entry_t newpde;
6181 vm_paddr_t mptepa;
6182 vm_page_t mpte;
6183
6184 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
6185 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6186 mpte = pmap_remove_pt_page(pmap, va);
6187 if (mpte == NULL)
6188 panic("pmap_remove_kernel_pde: Missing pt page.");
6189
6190 mptepa = VM_PAGE_TO_PHYS(mpte);
6191 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
6192
6193 /*
6194 * If this page table page was unmapped by a promotion, then it
6195 * contains valid mappings. Zero it to invalidate those mappings.
6196 */
6197 if (vm_page_any_valid(mpte))
6198 pagezero((void *)PHYS_TO_DMAP(mptepa));
6199
6200 /*
6201 * Demote the mapping.
6202 */
6203 if (workaround_erratum383)
6204 pmap_update_pde(pmap, va, pde, newpde);
6205 else
6206 pde_store(pde, newpde);
6207
6208 /*
6209 * Invalidate a stale recursive mapping of the page table page.
6210 */
6211 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
6212 }
6213
6214 /*
6215 * pmap_remove_pde: do the things to unmap a superpage in a process
6216 */
6217 static int
pmap_remove_pde(pmap_t pmap,pd_entry_t * pdq,vm_offset_t sva,struct spglist * free,struct rwlock ** lockp)6218 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
6219 struct spglist *free, struct rwlock **lockp)
6220 {
6221 struct md_page *pvh;
6222 pd_entry_t oldpde;
6223 vm_offset_t eva, va;
6224 vm_page_t m, mpte;
6225 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
6226
6227 PG_G = pmap_global_bit(pmap);
6228 PG_A = pmap_accessed_bit(pmap);
6229 PG_M = pmap_modified_bit(pmap);
6230 PG_RW = pmap_rw_bit(pmap);
6231
6232 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6233 KASSERT((sva & PDRMASK) == 0,
6234 ("pmap_remove_pde: sva is not 2mpage aligned"));
6235 oldpde = pte_load_clear(pdq);
6236 if (oldpde & PG_W)
6237 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
6238 if ((oldpde & PG_G) != 0)
6239 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
6240 pmap_resident_count_adj(pmap, -NBPDR / PAGE_SIZE);
6241 if (oldpde & PG_MANAGED) {
6242 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
6243 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
6244 pmap_pvh_free(pvh, pmap, sva);
6245 eva = sva + NBPDR;
6246 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
6247 va < eva; va += PAGE_SIZE, m++) {
6248 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
6249 vm_page_dirty(m);
6250 if (oldpde & PG_A)
6251 vm_page_aflag_set(m, PGA_REFERENCED);
6252 if (TAILQ_EMPTY(&m->md.pv_list) &&
6253 TAILQ_EMPTY(&pvh->pv_list))
6254 vm_page_aflag_clear(m, PGA_WRITEABLE);
6255 pmap_delayed_invl_page(m);
6256 }
6257 }
6258 if (pmap == kernel_pmap) {
6259 pmap_remove_kernel_pde(pmap, pdq, sva);
6260 } else {
6261 mpte = pmap_remove_pt_page(pmap, sva);
6262 if (mpte != NULL) {
6263 KASSERT(vm_page_any_valid(mpte),
6264 ("pmap_remove_pde: pte page not promoted"));
6265 pmap_pt_page_count_adj(pmap, -1);
6266 KASSERT(mpte->ref_count == NPTEPG,
6267 ("pmap_remove_pde: pte page ref count error"));
6268 mpte->ref_count = 0;
6269 pmap_add_delayed_free_list(mpte, free, false);
6270 }
6271 }
6272 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
6273 }
6274
6275 /*
6276 * pmap_remove_pte: do the things to unmap a page in a process
6277 */
6278 static int
pmap_remove_pte(pmap_t pmap,pt_entry_t * ptq,vm_offset_t va,pd_entry_t ptepde,struct spglist * free,struct rwlock ** lockp)6279 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
6280 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
6281 {
6282 struct md_page *pvh;
6283 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
6284 vm_page_t m;
6285
6286 PG_A = pmap_accessed_bit(pmap);
6287 PG_M = pmap_modified_bit(pmap);
6288 PG_RW = pmap_rw_bit(pmap);
6289
6290 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6291 oldpte = pte_load_clear(ptq);
6292 if (oldpte & PG_W)
6293 pmap->pm_stats.wired_count -= 1;
6294 pmap_resident_count_adj(pmap, -1);
6295 if (oldpte & PG_MANAGED) {
6296 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
6297 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6298 vm_page_dirty(m);
6299 if (oldpte & PG_A)
6300 vm_page_aflag_set(m, PGA_REFERENCED);
6301 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
6302 pmap_pvh_free(&m->md, pmap, va);
6303 if (TAILQ_EMPTY(&m->md.pv_list) &&
6304 (m->flags & PG_FICTITIOUS) == 0) {
6305 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6306 if (TAILQ_EMPTY(&pvh->pv_list))
6307 vm_page_aflag_clear(m, PGA_WRITEABLE);
6308 }
6309 pmap_delayed_invl_page(m);
6310 }
6311 return (pmap_unuse_pt(pmap, va, ptepde, free));
6312 }
6313
6314 /*
6315 * Remove a single page from a process address space
6316 */
6317 static void
pmap_remove_page(pmap_t pmap,vm_offset_t va,pd_entry_t * pde,struct spglist * free)6318 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
6319 struct spglist *free)
6320 {
6321 struct rwlock *lock;
6322 pt_entry_t *pte, PG_V;
6323
6324 PG_V = pmap_valid_bit(pmap);
6325 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6326 if ((*pde & PG_V) == 0)
6327 return;
6328 pte = pmap_pde_to_pte(pde, va);
6329 if ((*pte & PG_V) == 0)
6330 return;
6331 lock = NULL;
6332 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
6333 if (lock != NULL)
6334 rw_wunlock(lock);
6335 pmap_invalidate_page(pmap, va);
6336 }
6337
6338 /*
6339 * Removes the specified range of addresses from the page table page.
6340 */
6341 static bool
pmap_remove_ptes(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,pd_entry_t * pde,struct spglist * free,struct rwlock ** lockp)6342 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
6343 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
6344 {
6345 pt_entry_t PG_G, *pte;
6346 vm_offset_t va;
6347 bool anyvalid;
6348
6349 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6350 PG_G = pmap_global_bit(pmap);
6351 anyvalid = false;
6352 va = eva;
6353 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
6354 sva += PAGE_SIZE) {
6355 if (*pte == 0) {
6356 if (va != eva) {
6357 pmap_invalidate_range(pmap, va, sva);
6358 va = eva;
6359 }
6360 continue;
6361 }
6362 if ((*pte & PG_G) == 0)
6363 anyvalid = true;
6364 else if (va == eva)
6365 va = sva;
6366 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
6367 sva += PAGE_SIZE;
6368 break;
6369 }
6370 }
6371 if (va != eva)
6372 pmap_invalidate_range(pmap, va, sva);
6373 return (anyvalid);
6374 }
6375
6376 static void
pmap_remove1(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,bool map_delete)6377 pmap_remove1(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, bool map_delete)
6378 {
6379 struct rwlock *lock;
6380 vm_page_t mt;
6381 vm_offset_t va_next;
6382 pml5_entry_t *pml5e;
6383 pml4_entry_t *pml4e;
6384 pdp_entry_t *pdpe;
6385 pd_entry_t ptpaddr, *pde;
6386 pt_entry_t PG_G, PG_V;
6387 struct spglist free;
6388 int anyvalid;
6389
6390 PG_G = pmap_global_bit(pmap);
6391 PG_V = pmap_valid_bit(pmap);
6392
6393 /*
6394 * If there are no resident pages besides the top level page
6395 * table page(s), there is nothing to do. Kernel pmap always
6396 * accounts whole preloaded area as resident, which makes its
6397 * resident count > 2.
6398 * Perform an unsynchronized read. This is, however, safe.
6399 */
6400 if (pmap->pm_stats.resident_count <= 1 + (pmap->pm_pmltopu != NULL ?
6401 1 : 0))
6402 return;
6403
6404 anyvalid = 0;
6405 SLIST_INIT(&free);
6406
6407 pmap_delayed_invl_start();
6408 PMAP_LOCK(pmap);
6409 if (map_delete)
6410 pmap_pkru_on_remove(pmap, sva, eva);
6411
6412 /*
6413 * special handling of removing one page. a very
6414 * common operation and easy to short circuit some
6415 * code.
6416 */
6417 if (sva + PAGE_SIZE == eva) {
6418 pde = pmap_pde(pmap, sva);
6419 if (pde && (*pde & PG_PS) == 0) {
6420 pmap_remove_page(pmap, sva, pde, &free);
6421 goto out;
6422 }
6423 }
6424
6425 lock = NULL;
6426 for (; sva < eva; sva = va_next) {
6427 if (pmap->pm_stats.resident_count == 0)
6428 break;
6429
6430 if (pmap_is_la57(pmap)) {
6431 pml5e = pmap_pml5e(pmap, sva);
6432 if ((*pml5e & PG_V) == 0) {
6433 va_next = (sva + NBPML5) & ~PML5MASK;
6434 if (va_next < sva)
6435 va_next = eva;
6436 continue;
6437 }
6438 pml4e = pmap_pml5e_to_pml4e(pml5e, sva);
6439 } else {
6440 pml4e = pmap_pml4e(pmap, sva);
6441 }
6442 if ((*pml4e & PG_V) == 0) {
6443 va_next = (sva + NBPML4) & ~PML4MASK;
6444 if (va_next < sva)
6445 va_next = eva;
6446 continue;
6447 }
6448
6449 va_next = (sva + NBPDP) & ~PDPMASK;
6450 if (va_next < sva)
6451 va_next = eva;
6452 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6453 if ((*pdpe & PG_V) == 0)
6454 continue;
6455 if ((*pdpe & PG_PS) != 0) {
6456 KASSERT(va_next <= eva,
6457 ("partial update of non-transparent 1G mapping "
6458 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
6459 *pdpe, sva, eva, va_next));
6460 MPASS(pmap != kernel_pmap); /* XXXKIB */
6461 MPASS((*pdpe & (PG_MANAGED | PG_G)) == 0);
6462 anyvalid = 1;
6463 *pdpe = 0;
6464 pmap_resident_count_adj(pmap, -NBPDP / PAGE_SIZE);
6465 mt = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, sva) & PG_FRAME);
6466 pmap_unwire_ptp(pmap, sva, mt, &free);
6467 continue;
6468 }
6469
6470 /*
6471 * Calculate index for next page table.
6472 */
6473 va_next = (sva + NBPDR) & ~PDRMASK;
6474 if (va_next < sva)
6475 va_next = eva;
6476
6477 pde = pmap_pdpe_to_pde(pdpe, sva);
6478 ptpaddr = *pde;
6479
6480 /*
6481 * Weed out invalid mappings.
6482 */
6483 if (ptpaddr == 0)
6484 continue;
6485
6486 /*
6487 * Check for large page.
6488 */
6489 if ((ptpaddr & PG_PS) != 0) {
6490 /*
6491 * Are we removing the entire large page? If not,
6492 * demote the mapping and fall through.
6493 */
6494 if (sva + NBPDR == va_next && eva >= va_next) {
6495 /*
6496 * The TLB entry for a PG_G mapping is
6497 * invalidated by pmap_remove_pde().
6498 */
6499 if ((ptpaddr & PG_G) == 0)
6500 anyvalid = 1;
6501 pmap_remove_pde(pmap, pde, sva, &free, &lock);
6502 continue;
6503 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
6504 &lock)) {
6505 /* The large page mapping was destroyed. */
6506 continue;
6507 } else
6508 ptpaddr = *pde;
6509 }
6510
6511 /*
6512 * Limit our scan to either the end of the va represented
6513 * by the current page table page, or to the end of the
6514 * range being removed.
6515 */
6516 if (va_next > eva)
6517 va_next = eva;
6518
6519 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
6520 anyvalid = 1;
6521 }
6522 if (lock != NULL)
6523 rw_wunlock(lock);
6524 out:
6525 if (anyvalid)
6526 pmap_invalidate_all(pmap);
6527 PMAP_UNLOCK(pmap);
6528 pmap_delayed_invl_finish();
6529 vm_page_free_pages_toq(&free, true);
6530 }
6531
6532 /*
6533 * Remove the given range of addresses from the specified map.
6534 *
6535 * It is assumed that the start and end are properly
6536 * rounded to the page size.
6537 */
6538 void
pmap_remove(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)6539 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
6540 {
6541 pmap_remove1(pmap, sva, eva, false);
6542 }
6543
6544 /*
6545 * Remove the given range of addresses as part of a logical unmap
6546 * operation. This has the effect of calling pmap_remove(), but
6547 * also clears any metadata that should persist for the lifetime
6548 * of a logical mapping.
6549 */
6550 void
pmap_map_delete(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)6551 pmap_map_delete(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
6552 {
6553 pmap_remove1(pmap, sva, eva, true);
6554 }
6555
6556 /*
6557 * Routine: pmap_remove_all
6558 * Function:
6559 * Removes this physical page from
6560 * all physical maps in which it resides.
6561 * Reflects back modify bits to the pager.
6562 *
6563 * Notes:
6564 * Original versions of this routine were very
6565 * inefficient because they iteratively called
6566 * pmap_remove (slow...)
6567 */
6568
6569 void
pmap_remove_all(vm_page_t m)6570 pmap_remove_all(vm_page_t m)
6571 {
6572 struct md_page *pvh;
6573 pv_entry_t pv;
6574 pmap_t pmap;
6575 struct rwlock *lock;
6576 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
6577 pd_entry_t *pde;
6578 vm_offset_t va;
6579 struct spglist free;
6580 int pvh_gen, md_gen;
6581
6582 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6583 ("pmap_remove_all: page %p is not managed", m));
6584 SLIST_INIT(&free);
6585 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6586 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6587 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6588 rw_wlock(lock);
6589 retry:
6590 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
6591 pmap = PV_PMAP(pv);
6592 if (!PMAP_TRYLOCK(pmap)) {
6593 pvh_gen = pvh->pv_gen;
6594 rw_wunlock(lock);
6595 PMAP_LOCK(pmap);
6596 rw_wlock(lock);
6597 if (pvh_gen != pvh->pv_gen) {
6598 PMAP_UNLOCK(pmap);
6599 goto retry;
6600 }
6601 }
6602 va = pv->pv_va;
6603 pde = pmap_pde(pmap, va);
6604 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6605 PMAP_UNLOCK(pmap);
6606 }
6607 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
6608 pmap = PV_PMAP(pv);
6609 if (!PMAP_TRYLOCK(pmap)) {
6610 pvh_gen = pvh->pv_gen;
6611 md_gen = m->md.pv_gen;
6612 rw_wunlock(lock);
6613 PMAP_LOCK(pmap);
6614 rw_wlock(lock);
6615 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6616 PMAP_UNLOCK(pmap);
6617 goto retry;
6618 }
6619 }
6620 PG_A = pmap_accessed_bit(pmap);
6621 PG_M = pmap_modified_bit(pmap);
6622 PG_RW = pmap_rw_bit(pmap);
6623 pmap_resident_count_adj(pmap, -1);
6624 pde = pmap_pde(pmap, pv->pv_va);
6625 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
6626 " a 2mpage in page %p's pv list", m));
6627 pte = pmap_pde_to_pte(pde, pv->pv_va);
6628 tpte = pte_load_clear(pte);
6629 if (tpte & PG_W)
6630 pmap->pm_stats.wired_count--;
6631 if (tpte & PG_A)
6632 vm_page_aflag_set(m, PGA_REFERENCED);
6633
6634 /*
6635 * Update the vm_page_t clean and reference bits.
6636 */
6637 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6638 vm_page_dirty(m);
6639 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
6640 pmap_invalidate_page(pmap, pv->pv_va);
6641 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6642 m->md.pv_gen++;
6643 free_pv_entry(pmap, pv);
6644 PMAP_UNLOCK(pmap);
6645 }
6646 vm_page_aflag_clear(m, PGA_WRITEABLE);
6647 rw_wunlock(lock);
6648 pmap_delayed_invl_wait(m);
6649 vm_page_free_pages_toq(&free, true);
6650 }
6651
6652 /*
6653 * pmap_protect_pde: do the things to protect a 2mpage in a process
6654 */
6655 static bool
pmap_protect_pde(pmap_t pmap,pd_entry_t * pde,vm_offset_t sva,vm_prot_t prot)6656 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
6657 {
6658 pd_entry_t newpde, oldpde;
6659 vm_page_t m, mt;
6660 bool anychanged;
6661 pt_entry_t PG_G, PG_M, PG_RW;
6662
6663 PG_G = pmap_global_bit(pmap);
6664 PG_M = pmap_modified_bit(pmap);
6665 PG_RW = pmap_rw_bit(pmap);
6666
6667 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6668 KASSERT((sva & PDRMASK) == 0,
6669 ("pmap_protect_pde: sva is not 2mpage aligned"));
6670 anychanged = false;
6671 retry:
6672 oldpde = newpde = *pde;
6673 if ((prot & VM_PROT_WRITE) == 0) {
6674 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
6675 (PG_MANAGED | PG_M | PG_RW)) {
6676 m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
6677 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6678 vm_page_dirty(mt);
6679 }
6680 newpde &= ~(PG_RW | PG_M);
6681 }
6682 if ((prot & VM_PROT_EXECUTE) == 0)
6683 newpde |= pg_nx;
6684 if (newpde != oldpde) {
6685 /*
6686 * As an optimization to future operations on this PDE, clear
6687 * PG_PROMOTED. The impending invalidation will remove any
6688 * lingering 4KB page mappings from the TLB.
6689 */
6690 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
6691 goto retry;
6692 if ((oldpde & PG_G) != 0)
6693 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
6694 else
6695 anychanged = true;
6696 }
6697 return (anychanged);
6698 }
6699
6700 /*
6701 * Set the physical protection on the
6702 * specified range of this map as requested.
6703 */
6704 void
pmap_protect(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,vm_prot_t prot)6705 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
6706 {
6707 vm_page_t m;
6708 vm_offset_t va_next;
6709 pml4_entry_t *pml4e;
6710 pdp_entry_t *pdpe;
6711 pd_entry_t ptpaddr, *pde;
6712 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
6713 pt_entry_t obits, pbits;
6714 bool anychanged;
6715
6716 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
6717 if (prot == VM_PROT_NONE) {
6718 pmap_remove(pmap, sva, eva);
6719 return;
6720 }
6721
6722 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
6723 (VM_PROT_WRITE|VM_PROT_EXECUTE))
6724 return;
6725
6726 PG_G = pmap_global_bit(pmap);
6727 PG_M = pmap_modified_bit(pmap);
6728 PG_V = pmap_valid_bit(pmap);
6729 PG_RW = pmap_rw_bit(pmap);
6730 anychanged = false;
6731
6732 /*
6733 * Although this function delays and batches the invalidation
6734 * of stale TLB entries, it does not need to call
6735 * pmap_delayed_invl_start() and
6736 * pmap_delayed_invl_finish(), because it does not
6737 * ordinarily destroy mappings. Stale TLB entries from
6738 * protection-only changes need only be invalidated before the
6739 * pmap lock is released, because protection-only changes do
6740 * not destroy PV entries. Even operations that iterate over
6741 * a physical page's PV list of mappings, like
6742 * pmap_remove_write(), acquire the pmap lock for each
6743 * mapping. Consequently, for protection-only changes, the
6744 * pmap lock suffices to synchronize both page table and TLB
6745 * updates.
6746 *
6747 * This function only destroys a mapping if pmap_demote_pde()
6748 * fails. In that case, stale TLB entries are immediately
6749 * invalidated.
6750 */
6751
6752 PMAP_LOCK(pmap);
6753 for (; sva < eva; sva = va_next) {
6754 pml4e = pmap_pml4e(pmap, sva);
6755 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
6756 va_next = (sva + NBPML4) & ~PML4MASK;
6757 if (va_next < sva)
6758 va_next = eva;
6759 continue;
6760 }
6761
6762 va_next = (sva + NBPDP) & ~PDPMASK;
6763 if (va_next < sva)
6764 va_next = eva;
6765 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6766 if ((*pdpe & PG_V) == 0)
6767 continue;
6768 if ((*pdpe & PG_PS) != 0) {
6769 KASSERT(va_next <= eva,
6770 ("partial update of non-transparent 1G mapping "
6771 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
6772 *pdpe, sva, eva, va_next));
6773 retry_pdpe:
6774 obits = pbits = *pdpe;
6775 MPASS((pbits & (PG_MANAGED | PG_G)) == 0);
6776 MPASS(pmap != kernel_pmap); /* XXXKIB */
6777 if ((prot & VM_PROT_WRITE) == 0)
6778 pbits &= ~(PG_RW | PG_M);
6779 if ((prot & VM_PROT_EXECUTE) == 0)
6780 pbits |= pg_nx;
6781
6782 if (pbits != obits) {
6783 if (!atomic_cmpset_long(pdpe, obits, pbits))
6784 /* PG_PS cannot be cleared under us, */
6785 goto retry_pdpe;
6786 anychanged = true;
6787 }
6788 continue;
6789 }
6790
6791 va_next = (sva + NBPDR) & ~PDRMASK;
6792 if (va_next < sva)
6793 va_next = eva;
6794
6795 pde = pmap_pdpe_to_pde(pdpe, sva);
6796 ptpaddr = *pde;
6797
6798 /*
6799 * Weed out invalid mappings.
6800 */
6801 if (ptpaddr == 0)
6802 continue;
6803
6804 /*
6805 * Check for large page.
6806 */
6807 if ((ptpaddr & PG_PS) != 0) {
6808 /*
6809 * Are we protecting the entire large page?
6810 */
6811 if (sva + NBPDR == va_next && eva >= va_next) {
6812 /*
6813 * The TLB entry for a PG_G mapping is
6814 * invalidated by pmap_protect_pde().
6815 */
6816 if (pmap_protect_pde(pmap, pde, sva, prot))
6817 anychanged = true;
6818 continue;
6819 }
6820
6821 /*
6822 * Does the large page mapping need to change? If so,
6823 * demote it and fall through.
6824 */
6825 pbits = ptpaddr;
6826 if ((prot & VM_PROT_WRITE) == 0)
6827 pbits &= ~(PG_RW | PG_M);
6828 if ((prot & VM_PROT_EXECUTE) == 0)
6829 pbits |= pg_nx;
6830 if (ptpaddr == pbits || !pmap_demote_pde(pmap, pde,
6831 sva)) {
6832 /*
6833 * Either the large page mapping doesn't need
6834 * to change, or it was destroyed during
6835 * demotion.
6836 */
6837 continue;
6838 }
6839 }
6840
6841 if (va_next > eva)
6842 va_next = eva;
6843
6844 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6845 sva += PAGE_SIZE) {
6846 retry:
6847 obits = pbits = *pte;
6848 if ((pbits & PG_V) == 0)
6849 continue;
6850
6851 if ((prot & VM_PROT_WRITE) == 0) {
6852 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
6853 (PG_MANAGED | PG_M | PG_RW)) {
6854 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
6855 vm_page_dirty(m);
6856 }
6857 pbits &= ~(PG_RW | PG_M);
6858 }
6859 if ((prot & VM_PROT_EXECUTE) == 0)
6860 pbits |= pg_nx;
6861
6862 if (pbits != obits) {
6863 if (!atomic_cmpset_long(pte, obits, pbits))
6864 goto retry;
6865 if (obits & PG_G)
6866 pmap_invalidate_page(pmap, sva);
6867 else
6868 anychanged = true;
6869 }
6870 }
6871 }
6872 if (anychanged)
6873 pmap_invalidate_all(pmap);
6874 PMAP_UNLOCK(pmap);
6875 }
6876
6877 static bool
pmap_pde_ept_executable(pmap_t pmap,pd_entry_t pde)6878 pmap_pde_ept_executable(pmap_t pmap, pd_entry_t pde)
6879 {
6880
6881 if (pmap->pm_type != PT_EPT)
6882 return (false);
6883 return ((pde & EPT_PG_EXECUTE) != 0);
6884 }
6885
6886 #if VM_NRESERVLEVEL > 0
6887 /*
6888 * Tries to promote the 512, contiguous 4KB page mappings that are within a
6889 * single page table page (PTP) to a single 2MB page mapping. For promotion
6890 * to occur, two conditions must be met: (1) the 4KB page mappings must map
6891 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
6892 * identical characteristics.
6893 */
6894 static bool
pmap_promote_pde(pmap_t pmap,pd_entry_t * pde,vm_offset_t va,vm_page_t mpte,struct rwlock ** lockp)6895 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va, vm_page_t mpte,
6896 struct rwlock **lockp)
6897 {
6898 pd_entry_t newpde;
6899 pt_entry_t *firstpte, oldpte, pa, *pte;
6900 pt_entry_t allpte_PG_A, PG_A, PG_G, PG_M, PG_PKU_MASK, PG_RW, PG_V;
6901 int PG_PTE_CACHE;
6902
6903 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6904 if (!pmap_ps_enabled(pmap))
6905 return (false);
6906
6907 PG_A = pmap_accessed_bit(pmap);
6908 PG_G = pmap_global_bit(pmap);
6909 PG_M = pmap_modified_bit(pmap);
6910 PG_V = pmap_valid_bit(pmap);
6911 PG_RW = pmap_rw_bit(pmap);
6912 PG_PKU_MASK = pmap_pku_mask_bit(pmap);
6913 PG_PTE_CACHE = pmap_cache_mask(pmap, false);
6914
6915 /*
6916 * Examine the first PTE in the specified PTP. Abort if this PTE is
6917 * ineligible for promotion due to hardware errata, invalid, or does
6918 * not map the first 4KB physical page within a 2MB page.
6919 */
6920 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
6921 newpde = *firstpte;
6922 if (!pmap_allow_2m_x_page(pmap, pmap_pde_ept_executable(pmap, newpde)))
6923 return (false);
6924 if ((newpde & ((PG_FRAME & PDRMASK) | PG_V)) != PG_V) {
6925 counter_u64_add(pmap_pde_p_failures, 1);
6926 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6927 " in pmap %p", va, pmap);
6928 return (false);
6929 }
6930
6931 /*
6932 * Both here and in the below "for" loop, to allow for repromotion
6933 * after MADV_FREE, conditionally write protect a clean PTE before
6934 * possibly aborting the promotion due to other PTE attributes. Why?
6935 * Suppose that MADV_FREE is applied to a part of a superpage, the
6936 * address range [S, E). pmap_advise() will demote the superpage
6937 * mapping, destroy the 4KB page mapping at the end of [S, E), and
6938 * clear PG_M and PG_A in the PTEs for the rest of [S, E). Later,
6939 * imagine that the memory in [S, E) is recycled, but the last 4KB
6940 * page in [S, E) is not the last to be rewritten, or simply accessed.
6941 * In other words, there is still a 4KB page in [S, E), call it P,
6942 * that is writeable but PG_M and PG_A are clear in P's PTE. Unless
6943 * we write protect P before aborting the promotion, if and when P is
6944 * finally rewritten, there won't be a page fault to trigger
6945 * repromotion.
6946 */
6947 setpde:
6948 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
6949 /*
6950 * When PG_M is already clear, PG_RW can be cleared without
6951 * a TLB invalidation.
6952 */
6953 if (!atomic_fcmpset_long(firstpte, &newpde, newpde & ~PG_RW))
6954 goto setpde;
6955 newpde &= ~PG_RW;
6956 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
6957 " in pmap %p", va & ~PDRMASK, pmap);
6958 }
6959
6960 /*
6961 * Examine each of the other PTEs in the specified PTP. Abort if this
6962 * PTE maps an unexpected 4KB physical page or does not have identical
6963 * characteristics to the first PTE.
6964 */
6965 allpte_PG_A = newpde & PG_A;
6966 pa = (newpde & (PG_PS_FRAME | PG_V)) + NBPDR - PAGE_SIZE;
6967 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
6968 oldpte = *pte;
6969 if ((oldpte & (PG_FRAME | PG_V)) != pa) {
6970 counter_u64_add(pmap_pde_p_failures, 1);
6971 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6972 " in pmap %p", va, pmap);
6973 return (false);
6974 }
6975 setpte:
6976 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
6977 /*
6978 * When PG_M is already clear, PG_RW can be cleared
6979 * without a TLB invalidation.
6980 */
6981 if (!atomic_fcmpset_long(pte, &oldpte, oldpte & ~PG_RW))
6982 goto setpte;
6983 oldpte &= ~PG_RW;
6984 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
6985 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
6986 (va & ~PDRMASK), pmap);
6987 }
6988 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
6989 counter_u64_add(pmap_pde_p_failures, 1);
6990 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
6991 " in pmap %p", va, pmap);
6992 return (false);
6993 }
6994 allpte_PG_A &= oldpte;
6995 pa -= PAGE_SIZE;
6996 }
6997
6998 /*
6999 * Unless all PTEs have PG_A set, clear it from the superpage mapping,
7000 * so that promotions triggered by speculative mappings, such as
7001 * pmap_enter_quick(), don't automatically mark the underlying pages
7002 * as referenced.
7003 */
7004 newpde &= ~PG_A | allpte_PG_A;
7005
7006 /*
7007 * EPT PTEs with PG_M set and PG_A clear are not supported by early
7008 * MMUs supporting EPT.
7009 */
7010 KASSERT((newpde & PG_A) != 0 || safe_to_clear_referenced(pmap, newpde),
7011 ("unsupported EPT PTE"));
7012
7013 /*
7014 * Save the PTP in its current state until the PDE mapping the
7015 * superpage is demoted by pmap_demote_pde() or destroyed by
7016 * pmap_remove_pde(). If PG_A is not set in every PTE, then request
7017 * that the PTP be refilled on demotion.
7018 */
7019 if (mpte == NULL)
7020 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7021 KASSERT(mpte >= vm_page_array &&
7022 mpte < &vm_page_array[vm_page_array_size],
7023 ("pmap_promote_pde: page table page is out of range"));
7024 KASSERT(mpte->pindex == pmap_pde_pindex(va),
7025 ("pmap_promote_pde: page table page's pindex is wrong "
7026 "mpte %p pidx %#lx va %#lx va pde pidx %#lx",
7027 mpte, mpte->pindex, va, pmap_pde_pindex(va)));
7028 if (pmap_insert_pt_page(pmap, mpte, true, allpte_PG_A != 0)) {
7029 counter_u64_add(pmap_pde_p_failures, 1);
7030 CTR2(KTR_PMAP,
7031 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
7032 pmap);
7033 return (false);
7034 }
7035
7036 /*
7037 * Promote the pv entries.
7038 */
7039 if ((newpde & PG_MANAGED) != 0)
7040 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
7041
7042 /*
7043 * Propagate the PAT index to its proper position.
7044 */
7045 newpde = pmap_swap_pat(pmap, newpde);
7046
7047 /*
7048 * Map the superpage.
7049 */
7050 if (workaround_erratum383)
7051 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
7052 else
7053 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
7054
7055 counter_u64_add(pmap_pde_promotions, 1);
7056 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
7057 " in pmap %p", va, pmap);
7058 return (true);
7059 }
7060 #endif /* VM_NRESERVLEVEL > 0 */
7061
7062 static int
pmap_enter_largepage(pmap_t pmap,vm_offset_t va,pt_entry_t newpte,int flags,int psind)7063 pmap_enter_largepage(pmap_t pmap, vm_offset_t va, pt_entry_t newpte, int flags,
7064 int psind)
7065 {
7066 vm_page_t mp;
7067 pt_entry_t origpte, *pml4e, *pdpe, *pde, pten, PG_V;
7068
7069 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7070 KASSERT(psind > 0 && psind < MAXPAGESIZES && pagesizes[psind] != 0,
7071 ("psind %d unexpected", psind));
7072 KASSERT(((newpte & PG_FRAME) & (pagesizes[psind] - 1)) == 0,
7073 ("unaligned phys address %#lx newpte %#lx psind %d",
7074 newpte & PG_FRAME, newpte, psind));
7075 KASSERT((va & (pagesizes[psind] - 1)) == 0,
7076 ("unaligned va %#lx psind %d", va, psind));
7077 KASSERT(va < VM_MAXUSER_ADDRESS,
7078 ("kernel mode non-transparent superpage")); /* XXXKIB */
7079 KASSERT(va + pagesizes[psind] < VM_MAXUSER_ADDRESS,
7080 ("overflowing user map va %#lx psind %d", va, psind)); /* XXXKIB */
7081
7082 PG_V = pmap_valid_bit(pmap);
7083
7084 restart:
7085 pten = newpte;
7086 if (!pmap_pkru_same(pmap, va, va + pagesizes[psind], &pten))
7087 return (KERN_PROTECTION_FAILURE);
7088
7089 if (psind == 2) { /* 1G */
7090 pml4e = pmap_pml4e(pmap, va);
7091 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
7092 mp = pmap_allocpte_alloc(pmap, pmap_pml4e_pindex(va),
7093 NULL, va);
7094 if (mp == NULL)
7095 goto allocf;
7096 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
7097 pdpe = &pdpe[pmap_pdpe_index(va)];
7098 origpte = *pdpe;
7099 MPASS(origpte == 0);
7100 } else {
7101 pdpe = pmap_pml4e_to_pdpe(pml4e, va);
7102 KASSERT(pdpe != NULL, ("va %#lx lost pdpe", va));
7103 origpte = *pdpe;
7104 if ((origpte & PG_V) == 0) {
7105 mp = PHYS_TO_VM_PAGE(*pml4e & PG_FRAME);
7106 mp->ref_count++;
7107 }
7108 }
7109 *pdpe = pten;
7110 } else /* (psind == 1) */ { /* 2M */
7111 pde = pmap_pde(pmap, va);
7112 if (pde == NULL) {
7113 mp = pmap_allocpte_alloc(pmap, pmap_pdpe_pindex(va),
7114 NULL, va);
7115 if (mp == NULL)
7116 goto allocf;
7117 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mp));
7118 pde = &pde[pmap_pde_index(va)];
7119 origpte = *pde;
7120 MPASS(origpte == 0);
7121 } else {
7122 origpte = *pde;
7123 if ((origpte & PG_V) == 0) {
7124 pdpe = pmap_pdpe(pmap, va);
7125 MPASS(pdpe != NULL && (*pdpe & PG_V) != 0);
7126 mp = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
7127 mp->ref_count++;
7128 }
7129 }
7130 *pde = pten;
7131 }
7132 KASSERT((origpte & PG_V) == 0 || ((origpte & PG_PS) != 0 &&
7133 (origpte & PG_PS_FRAME) == (pten & PG_PS_FRAME)),
7134 ("va %#lx changing %s phys page origpte %#lx pten %#lx",
7135 va, psind == 2 ? "1G" : "2M", origpte, pten));
7136 if ((pten & PG_W) != 0 && (origpte & PG_W) == 0)
7137 pmap->pm_stats.wired_count += pagesizes[psind] / PAGE_SIZE;
7138 else if ((pten & PG_W) == 0 && (origpte & PG_W) != 0)
7139 pmap->pm_stats.wired_count -= pagesizes[psind] / PAGE_SIZE;
7140 if ((origpte & PG_V) == 0)
7141 pmap_resident_count_adj(pmap, pagesizes[psind] / PAGE_SIZE);
7142
7143 return (KERN_SUCCESS);
7144
7145 allocf:
7146 if ((flags & PMAP_ENTER_NOSLEEP) != 0)
7147 return (KERN_RESOURCE_SHORTAGE);
7148 PMAP_UNLOCK(pmap);
7149 vm_wait(NULL);
7150 PMAP_LOCK(pmap);
7151 goto restart;
7152 }
7153
7154 /*
7155 * Insert the given physical page (p) at
7156 * the specified virtual address (v) in the
7157 * target physical map with the protection requested.
7158 *
7159 * If specified, the page will be wired down, meaning
7160 * that the related pte can not be reclaimed.
7161 *
7162 * NB: This is the only routine which MAY NOT lazy-evaluate
7163 * or lose information. That is, this routine must actually
7164 * insert this page into the given map NOW.
7165 *
7166 * When destroying both a page table and PV entry, this function
7167 * performs the TLB invalidation before releasing the PV list
7168 * lock, so we do not need pmap_delayed_invl_page() calls here.
7169 */
7170 int
pmap_enter(pmap_t pmap,vm_offset_t va,vm_page_t m,vm_prot_t prot,u_int flags,int8_t psind)7171 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
7172 u_int flags, int8_t psind)
7173 {
7174 struct rwlock *lock;
7175 pd_entry_t *pde;
7176 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
7177 pt_entry_t newpte, origpte;
7178 pv_entry_t pv;
7179 vm_paddr_t opa, pa;
7180 vm_page_t mpte, om;
7181 int rv;
7182 bool nosleep;
7183
7184 PG_A = pmap_accessed_bit(pmap);
7185 PG_G = pmap_global_bit(pmap);
7186 PG_M = pmap_modified_bit(pmap);
7187 PG_V = pmap_valid_bit(pmap);
7188 PG_RW = pmap_rw_bit(pmap);
7189
7190 va = trunc_page(va);
7191 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
7192 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
7193 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
7194 va));
7195 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || !VA_IS_CLEANMAP(va),
7196 ("pmap_enter: managed mapping within the clean submap"));
7197 if ((m->oflags & VPO_UNMANAGED) == 0)
7198 VM_PAGE_OBJECT_BUSY_ASSERT(m);
7199 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
7200 ("pmap_enter: flags %u has reserved bits set", flags));
7201 pa = VM_PAGE_TO_PHYS(m);
7202 newpte = (pt_entry_t)(pa | PG_A | PG_V);
7203 if ((flags & VM_PROT_WRITE) != 0)
7204 newpte |= PG_M;
7205 if ((prot & VM_PROT_WRITE) != 0)
7206 newpte |= PG_RW;
7207 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
7208 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
7209 if ((prot & VM_PROT_EXECUTE) == 0)
7210 newpte |= pg_nx;
7211 if ((flags & PMAP_ENTER_WIRED) != 0)
7212 newpte |= PG_W;
7213 if (va < VM_MAXUSER_ADDRESS)
7214 newpte |= PG_U;
7215 if (pmap == kernel_pmap)
7216 newpte |= PG_G;
7217 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
7218
7219 /*
7220 * Set modified bit gratuitously for writeable mappings if
7221 * the page is unmanaged. We do not want to take a fault
7222 * to do the dirty bit accounting for these mappings.
7223 */
7224 if ((m->oflags & VPO_UNMANAGED) != 0) {
7225 if ((newpte & PG_RW) != 0)
7226 newpte |= PG_M;
7227 } else
7228 newpte |= PG_MANAGED;
7229
7230 lock = NULL;
7231 PMAP_LOCK(pmap);
7232 if ((flags & PMAP_ENTER_LARGEPAGE) != 0) {
7233 KASSERT((m->oflags & VPO_UNMANAGED) != 0,
7234 ("managed largepage va %#lx flags %#x", va, flags));
7235 rv = pmap_enter_largepage(pmap, va, newpte | PG_PS, flags,
7236 psind);
7237 goto out;
7238 }
7239 if (psind == 1) {
7240 /* Assert the required virtual and physical alignment. */
7241 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
7242 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
7243 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
7244 goto out;
7245 }
7246 mpte = NULL;
7247
7248 /*
7249 * In the case that a page table page is not
7250 * resident, we are creating it here.
7251 */
7252 retry:
7253 pde = pmap_pde(pmap, va);
7254 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
7255 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
7256 pte = pmap_pde_to_pte(pde, va);
7257 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
7258 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7259 mpte->ref_count++;
7260 }
7261 } else if (va < VM_MAXUSER_ADDRESS) {
7262 /*
7263 * Here if the pte page isn't mapped, or if it has been
7264 * deallocated.
7265 */
7266 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
7267 mpte = pmap_allocpte_alloc(pmap, pmap_pde_pindex(va),
7268 nosleep ? NULL : &lock, va);
7269 if (mpte == NULL && nosleep) {
7270 rv = KERN_RESOURCE_SHORTAGE;
7271 goto out;
7272 }
7273 goto retry;
7274 } else
7275 panic("pmap_enter: invalid page directory va=%#lx", va);
7276
7277 origpte = *pte;
7278 pv = NULL;
7279 if (va < VM_MAXUSER_ADDRESS && pmap->pm_type == PT_X86)
7280 newpte |= pmap_pkru_get(pmap, va);
7281
7282 /*
7283 * Is the specified virtual address already mapped?
7284 */
7285 if ((origpte & PG_V) != 0) {
7286 /*
7287 * Wiring change, just update stats. We don't worry about
7288 * wiring PT pages as they remain resident as long as there
7289 * are valid mappings in them. Hence, if a user page is wired,
7290 * the PT page will be also.
7291 */
7292 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
7293 pmap->pm_stats.wired_count++;
7294 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
7295 pmap->pm_stats.wired_count--;
7296
7297 /*
7298 * Remove the extra PT page reference.
7299 */
7300 if (mpte != NULL) {
7301 mpte->ref_count--;
7302 KASSERT(mpte->ref_count > 0,
7303 ("pmap_enter: missing reference to page table page,"
7304 " va: 0x%lx", va));
7305 }
7306
7307 /*
7308 * Has the physical page changed?
7309 */
7310 opa = origpte & PG_FRAME;
7311 if (opa == pa) {
7312 /*
7313 * No, might be a protection or wiring change.
7314 */
7315 if ((origpte & PG_MANAGED) != 0 &&
7316 (newpte & PG_RW) != 0)
7317 vm_page_aflag_set(m, PGA_WRITEABLE);
7318 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
7319 goto unchanged;
7320 goto validate;
7321 }
7322
7323 /*
7324 * The physical page has changed. Temporarily invalidate
7325 * the mapping. This ensures that all threads sharing the
7326 * pmap keep a consistent view of the mapping, which is
7327 * necessary for the correct handling of COW faults. It
7328 * also permits reuse of the old mapping's PV entry,
7329 * avoiding an allocation.
7330 *
7331 * For consistency, handle unmanaged mappings the same way.
7332 */
7333 origpte = pte_load_clear(pte);
7334 KASSERT((origpte & PG_FRAME) == opa,
7335 ("pmap_enter: unexpected pa update for %#lx", va));
7336 if ((origpte & PG_MANAGED) != 0) {
7337 om = PHYS_TO_VM_PAGE(opa);
7338
7339 /*
7340 * The pmap lock is sufficient to synchronize with
7341 * concurrent calls to pmap_page_test_mappings() and
7342 * pmap_ts_referenced().
7343 */
7344 if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7345 vm_page_dirty(om);
7346 if ((origpte & PG_A) != 0) {
7347 pmap_invalidate_page(pmap, va);
7348 vm_page_aflag_set(om, PGA_REFERENCED);
7349 }
7350 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
7351 pv = pmap_pvh_remove(&om->md, pmap, va);
7352 KASSERT(pv != NULL,
7353 ("pmap_enter: no PV entry for %#lx", va));
7354 if ((newpte & PG_MANAGED) == 0)
7355 free_pv_entry(pmap, pv);
7356 if ((om->a.flags & PGA_WRITEABLE) != 0 &&
7357 TAILQ_EMPTY(&om->md.pv_list) &&
7358 ((om->flags & PG_FICTITIOUS) != 0 ||
7359 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
7360 vm_page_aflag_clear(om, PGA_WRITEABLE);
7361 } else {
7362 /*
7363 * Since this mapping is unmanaged, assume that PG_A
7364 * is set.
7365 */
7366 pmap_invalidate_page(pmap, va);
7367 }
7368 origpte = 0;
7369 } else {
7370 /*
7371 * Increment the counters.
7372 */
7373 if ((newpte & PG_W) != 0)
7374 pmap->pm_stats.wired_count++;
7375 pmap_resident_count_adj(pmap, 1);
7376 }
7377
7378 /*
7379 * Enter on the PV list if part of our managed memory.
7380 */
7381 if ((newpte & PG_MANAGED) != 0) {
7382 if (pv == NULL) {
7383 pv = get_pv_entry(pmap, &lock);
7384 pv->pv_va = va;
7385 }
7386 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
7387 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
7388 m->md.pv_gen++;
7389 if ((newpte & PG_RW) != 0)
7390 vm_page_aflag_set(m, PGA_WRITEABLE);
7391 }
7392
7393 /*
7394 * Update the PTE.
7395 */
7396 if ((origpte & PG_V) != 0) {
7397 validate:
7398 origpte = pte_load_store(pte, newpte);
7399 KASSERT((origpte & PG_FRAME) == pa,
7400 ("pmap_enter: unexpected pa update for %#lx", va));
7401 if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
7402 (PG_M | PG_RW)) {
7403 if ((origpte & PG_MANAGED) != 0)
7404 vm_page_dirty(m);
7405
7406 /*
7407 * Although the PTE may still have PG_RW set, TLB
7408 * invalidation may nonetheless be required because
7409 * the PTE no longer has PG_M set.
7410 */
7411 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
7412 /*
7413 * This PTE change does not require TLB invalidation.
7414 */
7415 goto unchanged;
7416 }
7417 if ((origpte & PG_A) != 0)
7418 pmap_invalidate_page(pmap, va);
7419 } else
7420 pte_store(pte, newpte);
7421
7422 unchanged:
7423
7424 #if VM_NRESERVLEVEL > 0
7425 /*
7426 * If both the page table page and the reservation are fully
7427 * populated, then attempt promotion.
7428 */
7429 if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
7430 (m->flags & PG_FICTITIOUS) == 0 &&
7431 vm_reserv_level_iffullpop(m) == 0)
7432 (void)pmap_promote_pde(pmap, pde, va, mpte, &lock);
7433 #endif
7434
7435 rv = KERN_SUCCESS;
7436 out:
7437 if (lock != NULL)
7438 rw_wunlock(lock);
7439 PMAP_UNLOCK(pmap);
7440 return (rv);
7441 }
7442
7443 /*
7444 * Tries to create a read- and/or execute-only 2MB page mapping. Returns
7445 * KERN_SUCCESS if the mapping was created. Otherwise, returns an error
7446 * value. See pmap_enter_pde() for the possible error values when "no sleep",
7447 * "no replace", and "no reclaim" are specified.
7448 */
7449 static int
pmap_enter_2mpage(pmap_t pmap,vm_offset_t va,vm_page_t m,vm_prot_t prot,struct rwlock ** lockp)7450 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
7451 struct rwlock **lockp)
7452 {
7453 pd_entry_t newpde;
7454 pt_entry_t PG_V;
7455
7456 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7457 PG_V = pmap_valid_bit(pmap);
7458 newpde = VM_PAGE_TO_PHYS(m) |
7459 pmap_cache_bits(pmap, m->md.pat_mode, true) | PG_PS | PG_V;
7460 if ((m->oflags & VPO_UNMANAGED) == 0)
7461 newpde |= PG_MANAGED;
7462 if ((prot & VM_PROT_EXECUTE) == 0)
7463 newpde |= pg_nx;
7464 if (va < VM_MAXUSER_ADDRESS)
7465 newpde |= PG_U;
7466 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
7467 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp));
7468 }
7469
7470 /*
7471 * Returns true if every page table entry in the specified page table page is
7472 * zero.
7473 */
7474 static bool
pmap_every_pte_zero(vm_paddr_t pa)7475 pmap_every_pte_zero(vm_paddr_t pa)
7476 {
7477 pt_entry_t *pt_end, *pte;
7478
7479 KASSERT((pa & PAGE_MASK) == 0, ("pa is misaligned"));
7480 pte = (pt_entry_t *)PHYS_TO_DMAP(pa);
7481 for (pt_end = pte + NPTEPG; pte < pt_end; pte++) {
7482 if (*pte != 0)
7483 return (false);
7484 }
7485 return (true);
7486 }
7487
7488 /*
7489 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
7490 * the mapping was created, and one of KERN_FAILURE, KERN_NO_SPACE,
7491 * KERN_PROTECTION_FAILURE, or KERN_RESOURCE_SHORTAGE otherwise. Returns
7492 * KERN_FAILURE if either (1) PMAP_ENTER_NOREPLACE was specified and a 4KB
7493 * page mapping already exists within the 2MB virtual address range starting
7494 * at the specified virtual address or (2) the requested 2MB page mapping is
7495 * not supported due to hardware errata. Returns KERN_NO_SPACE if
7496 * PMAP_ENTER_NOREPLACE was specified and a 2MB page mapping already exists at
7497 * the specified virtual address. Returns KERN_PROTECTION_FAILURE if the PKRU
7498 * settings are not the same across the 2MB virtual address range starting at
7499 * the specified virtual address. Returns KERN_RESOURCE_SHORTAGE if either
7500 * (1) PMAP_ENTER_NOSLEEP was specified and a page table page allocation
7501 * failed or (2) PMAP_ENTER_NORECLAIM was specified and a PV entry allocation
7502 * failed.
7503 *
7504 * The parameter "m" is only used when creating a managed, writeable mapping.
7505 */
7506 static int
pmap_enter_pde(pmap_t pmap,vm_offset_t va,pd_entry_t newpde,u_int flags,vm_page_t m,struct rwlock ** lockp)7507 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
7508 vm_page_t m, struct rwlock **lockp)
7509 {
7510 struct spglist free;
7511 pd_entry_t oldpde, *pde;
7512 pt_entry_t PG_G, PG_RW, PG_V;
7513 vm_page_t mt, pdpg;
7514 vm_page_t uwptpg;
7515
7516 PG_G = pmap_global_bit(pmap);
7517 PG_RW = pmap_rw_bit(pmap);
7518 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
7519 ("pmap_enter_pde: newpde is missing PG_M"));
7520 PG_V = pmap_valid_bit(pmap);
7521 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7522
7523 if (!pmap_allow_2m_x_page(pmap, pmap_pde_ept_executable(pmap,
7524 newpde))) {
7525 CTR2(KTR_PMAP, "pmap_enter_pde: 2m x blocked for va %#lx"
7526 " in pmap %p", va, pmap);
7527 return (KERN_FAILURE);
7528 }
7529 if ((pde = pmap_alloc_pde(pmap, va, &pdpg, (flags &
7530 PMAP_ENTER_NOSLEEP) != 0 ? NULL : lockp)) == NULL) {
7531 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
7532 " in pmap %p", va, pmap);
7533 return (KERN_RESOURCE_SHORTAGE);
7534 }
7535
7536 /*
7537 * If pkru is not same for the whole pde range, return failure
7538 * and let vm_fault() cope. Check after pde allocation, since
7539 * it could sleep.
7540 */
7541 if (!pmap_pkru_same(pmap, va, va + NBPDR, &newpde)) {
7542 pmap_abort_ptp(pmap, va, pdpg);
7543 return (KERN_PROTECTION_FAILURE);
7544 }
7545
7546 /*
7547 * If there are existing mappings, either abort or remove them.
7548 */
7549 oldpde = *pde;
7550 if ((oldpde & PG_V) != 0) {
7551 KASSERT(pdpg == NULL || pdpg->ref_count > 1,
7552 ("pmap_enter_pde: pdpg's reference count is too low"));
7553 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
7554 if ((oldpde & PG_PS) != 0) {
7555 if (pdpg != NULL)
7556 pdpg->ref_count--;
7557 CTR2(KTR_PMAP,
7558 "pmap_enter_pde: no space for va %#lx"
7559 " in pmap %p", va, pmap);
7560 return (KERN_NO_SPACE);
7561 } else if (va < VM_MAXUSER_ADDRESS ||
7562 !pmap_every_pte_zero(oldpde & PG_FRAME)) {
7563 if (pdpg != NULL)
7564 pdpg->ref_count--;
7565 CTR2(KTR_PMAP,
7566 "pmap_enter_pde: failure for va %#lx"
7567 " in pmap %p", va, pmap);
7568 return (KERN_FAILURE);
7569 }
7570 }
7571 /* Break the existing mapping(s). */
7572 SLIST_INIT(&free);
7573 if ((oldpde & PG_PS) != 0) {
7574 /*
7575 * The reference to the PD page that was acquired by
7576 * pmap_alloc_pde() ensures that it won't be freed.
7577 * However, if the PDE resulted from a promotion, then
7578 * a reserved PT page could be freed.
7579 */
7580 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
7581 if ((oldpde & PG_G) == 0)
7582 pmap_invalidate_pde_page(pmap, va, oldpde);
7583 } else {
7584 pmap_delayed_invl_start();
7585 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
7586 lockp))
7587 pmap_invalidate_all(pmap);
7588 pmap_delayed_invl_finish();
7589 }
7590 if (va < VM_MAXUSER_ADDRESS) {
7591 vm_page_free_pages_toq(&free, true);
7592 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
7593 pde));
7594 } else {
7595 KASSERT(SLIST_EMPTY(&free),
7596 ("pmap_enter_pde: freed kernel page table page"));
7597
7598 /*
7599 * Both pmap_remove_pde() and pmap_remove_ptes() will
7600 * leave the kernel page table page zero filled.
7601 */
7602 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7603 if (pmap_insert_pt_page(pmap, mt, false, false))
7604 panic("pmap_enter_pde: trie insert failed");
7605 }
7606 }
7607
7608 /*
7609 * Allocate leaf ptpage for wired userspace pages.
7610 */
7611 uwptpg = NULL;
7612 if ((newpde & PG_W) != 0 && pmap != kernel_pmap) {
7613 uwptpg = pmap_alloc_pt_page(pmap, pmap_pde_pindex(va),
7614 VM_ALLOC_WIRED);
7615 if (uwptpg == NULL) {
7616 pmap_abort_ptp(pmap, va, pdpg);
7617 return (KERN_RESOURCE_SHORTAGE);
7618 }
7619 if (pmap_insert_pt_page(pmap, uwptpg, true, false)) {
7620 pmap_free_pt_page(pmap, uwptpg, false);
7621 pmap_abort_ptp(pmap, va, pdpg);
7622 return (KERN_RESOURCE_SHORTAGE);
7623 }
7624
7625 uwptpg->ref_count = NPTEPG;
7626 }
7627 if ((newpde & PG_MANAGED) != 0) {
7628 /*
7629 * Abort this mapping if its PV entry could not be created.
7630 */
7631 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
7632 if (pdpg != NULL)
7633 pmap_abort_ptp(pmap, va, pdpg);
7634 if (uwptpg != NULL) {
7635 mt = pmap_remove_pt_page(pmap, va);
7636 KASSERT(mt == uwptpg,
7637 ("removed pt page %p, expected %p", mt,
7638 uwptpg));
7639 uwptpg->ref_count = 1;
7640 pmap_free_pt_page(pmap, uwptpg, false);
7641 }
7642 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
7643 " in pmap %p", va, pmap);
7644 return (KERN_RESOURCE_SHORTAGE);
7645 }
7646 if ((newpde & PG_RW) != 0) {
7647 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
7648 vm_page_aflag_set(mt, PGA_WRITEABLE);
7649 }
7650 }
7651
7652 /*
7653 * Increment counters.
7654 */
7655 if ((newpde & PG_W) != 0)
7656 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
7657 pmap_resident_count_adj(pmap, NBPDR / PAGE_SIZE);
7658
7659 /*
7660 * Map the superpage. (This is not a promoted mapping; there will not
7661 * be any lingering 4KB page mappings in the TLB.)
7662 */
7663 pde_store(pde, newpde);
7664
7665 counter_u64_add(pmap_pde_mappings, 1);
7666 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx in pmap %p",
7667 va, pmap);
7668 return (KERN_SUCCESS);
7669 }
7670
7671 /*
7672 * Maps a sequence of resident pages belonging to the same object.
7673 * The sequence begins with the given page m_start. This page is
7674 * mapped at the given virtual address start. Each subsequent page is
7675 * mapped at a virtual address that is offset from start by the same
7676 * amount as the page is offset from m_start within the object. The
7677 * last page in the sequence is the page with the largest offset from
7678 * m_start that can be mapped at a virtual address less than the given
7679 * virtual address end. Not every virtual page between start and end
7680 * is mapped; only those for which a resident page exists with the
7681 * corresponding offset from m_start are mapped.
7682 */
7683 void
pmap_enter_object(pmap_t pmap,vm_offset_t start,vm_offset_t end,vm_page_t m_start,vm_prot_t prot)7684 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
7685 vm_page_t m_start, vm_prot_t prot)
7686 {
7687 struct rwlock *lock;
7688 vm_offset_t va;
7689 vm_page_t m, mpte;
7690 vm_pindex_t diff, psize;
7691 int rv;
7692
7693 VM_OBJECT_ASSERT_LOCKED(m_start->object);
7694
7695 psize = atop(end - start);
7696 mpte = NULL;
7697 m = m_start;
7698 lock = NULL;
7699 PMAP_LOCK(pmap);
7700 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
7701 va = start + ptoa(diff);
7702 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
7703 m->psind == 1 && pmap_ps_enabled(pmap) &&
7704 ((rv = pmap_enter_2mpage(pmap, va, m, prot, &lock)) ==
7705 KERN_SUCCESS || rv == KERN_NO_SPACE))
7706 m = &m[NBPDR / PAGE_SIZE - 1];
7707 else
7708 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
7709 mpte, &lock);
7710 m = TAILQ_NEXT(m, listq);
7711 }
7712 if (lock != NULL)
7713 rw_wunlock(lock);
7714 PMAP_UNLOCK(pmap);
7715 }
7716
7717 /*
7718 * this code makes some *MAJOR* assumptions:
7719 * 1. Current pmap & pmap exists.
7720 * 2. Not wired.
7721 * 3. Read access.
7722 * 4. No page table pages.
7723 * but is *MUCH* faster than pmap_enter...
7724 */
7725
7726 void
pmap_enter_quick(pmap_t pmap,vm_offset_t va,vm_page_t m,vm_prot_t prot)7727 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
7728 {
7729 struct rwlock *lock;
7730
7731 lock = NULL;
7732 PMAP_LOCK(pmap);
7733 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
7734 if (lock != NULL)
7735 rw_wunlock(lock);
7736 PMAP_UNLOCK(pmap);
7737 }
7738
7739 static vm_page_t
pmap_enter_quick_locked(pmap_t pmap,vm_offset_t va,vm_page_t m,vm_prot_t prot,vm_page_t mpte,struct rwlock ** lockp)7740 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
7741 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
7742 {
7743 pd_entry_t *pde;
7744 pt_entry_t newpte, *pte, PG_V;
7745
7746 KASSERT(!VA_IS_CLEANMAP(va) ||
7747 (m->oflags & VPO_UNMANAGED) != 0,
7748 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
7749 PG_V = pmap_valid_bit(pmap);
7750 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7751 pde = NULL;
7752
7753 /*
7754 * In the case that a page table page is not
7755 * resident, we are creating it here.
7756 */
7757 if (va < VM_MAXUSER_ADDRESS) {
7758 pdp_entry_t *pdpe;
7759 vm_pindex_t ptepindex;
7760
7761 /*
7762 * Calculate pagetable page index
7763 */
7764 ptepindex = pmap_pde_pindex(va);
7765 if (mpte && (mpte->pindex == ptepindex)) {
7766 mpte->ref_count++;
7767 } else {
7768 /*
7769 * If the page table page is mapped, we just increment
7770 * the hold count, and activate it. Otherwise, we
7771 * attempt to allocate a page table page, passing NULL
7772 * instead of the PV list lock pointer because we don't
7773 * intend to sleep. If this attempt fails, we don't
7774 * retry. Instead, we give up.
7775 */
7776 pdpe = pmap_pdpe(pmap, va);
7777 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
7778 if ((*pdpe & PG_PS) != 0)
7779 return (NULL);
7780 pde = pmap_pdpe_to_pde(pdpe, va);
7781 if ((*pde & PG_V) != 0) {
7782 if ((*pde & PG_PS) != 0)
7783 return (NULL);
7784 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7785 mpte->ref_count++;
7786 } else {
7787 mpte = pmap_allocpte_alloc(pmap,
7788 ptepindex, NULL, va);
7789 if (mpte == NULL)
7790 return (NULL);
7791 }
7792 } else {
7793 mpte = pmap_allocpte_alloc(pmap, ptepindex,
7794 NULL, va);
7795 if (mpte == NULL)
7796 return (NULL);
7797 }
7798 }
7799 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
7800 pte = &pte[pmap_pte_index(va)];
7801 } else {
7802 mpte = NULL;
7803 pte = vtopte(va);
7804 }
7805 if (*pte) {
7806 if (mpte != NULL)
7807 mpte->ref_count--;
7808 return (NULL);
7809 }
7810
7811 /*
7812 * Enter on the PV list if part of our managed memory.
7813 */
7814 if ((m->oflags & VPO_UNMANAGED) == 0 &&
7815 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
7816 if (mpte != NULL)
7817 pmap_abort_ptp(pmap, va, mpte);
7818 return (NULL);
7819 }
7820
7821 /*
7822 * Increment counters
7823 */
7824 pmap_resident_count_adj(pmap, 1);
7825
7826 newpte = VM_PAGE_TO_PHYS(m) | PG_V |
7827 pmap_cache_bits(pmap, m->md.pat_mode, false);
7828 if ((m->oflags & VPO_UNMANAGED) == 0)
7829 newpte |= PG_MANAGED;
7830 if ((prot & VM_PROT_EXECUTE) == 0)
7831 newpte |= pg_nx;
7832 if (va < VM_MAXUSER_ADDRESS)
7833 newpte |= PG_U | pmap_pkru_get(pmap, va);
7834 pte_store(pte, newpte);
7835
7836 #if VM_NRESERVLEVEL > 0
7837 /*
7838 * If both the PTP and the reservation are fully populated, then
7839 * attempt promotion.
7840 */
7841 if ((prot & VM_PROT_NO_PROMOTE) == 0 &&
7842 (mpte == NULL || mpte->ref_count == NPTEPG) &&
7843 (m->flags & PG_FICTITIOUS) == 0 &&
7844 vm_reserv_level_iffullpop(m) == 0) {
7845 if (pde == NULL)
7846 pde = pmap_pde(pmap, va);
7847
7848 /*
7849 * If promotion succeeds, then the next call to this function
7850 * should not be given the unmapped PTP as a hint.
7851 */
7852 if (pmap_promote_pde(pmap, pde, va, mpte, lockp))
7853 mpte = NULL;
7854 }
7855 #endif
7856
7857 return (mpte);
7858 }
7859
7860 /*
7861 * Make a temporary mapping for a physical address. This is only intended
7862 * to be used for panic dumps.
7863 */
7864 void *
pmap_kenter_temporary(vm_paddr_t pa,int i)7865 pmap_kenter_temporary(vm_paddr_t pa, int i)
7866 {
7867 vm_offset_t va;
7868
7869 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
7870 pmap_kenter(va, pa);
7871 pmap_invlpg(kernel_pmap, va);
7872 return ((void *)crashdumpmap);
7873 }
7874
7875 /*
7876 * This code maps large physical mmap regions into the
7877 * processor address space. Note that some shortcuts
7878 * are taken, but the code works.
7879 */
7880 void
pmap_object_init_pt(pmap_t pmap,vm_offset_t addr,vm_object_t object,vm_pindex_t pindex,vm_size_t size)7881 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
7882 vm_pindex_t pindex, vm_size_t size)
7883 {
7884 pd_entry_t *pde;
7885 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
7886 vm_paddr_t pa, ptepa;
7887 vm_page_t p, pdpg;
7888 int pat_mode;
7889
7890 PG_A = pmap_accessed_bit(pmap);
7891 PG_M = pmap_modified_bit(pmap);
7892 PG_V = pmap_valid_bit(pmap);
7893 PG_RW = pmap_rw_bit(pmap);
7894
7895 VM_OBJECT_ASSERT_WLOCKED(object);
7896 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
7897 ("pmap_object_init_pt: non-device object"));
7898 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
7899 if (!pmap_ps_enabled(pmap))
7900 return;
7901 if (!vm_object_populate(object, pindex, pindex + atop(size)))
7902 return;
7903 p = vm_page_lookup(object, pindex);
7904 KASSERT(vm_page_all_valid(p),
7905 ("pmap_object_init_pt: invalid page %p", p));
7906 pat_mode = p->md.pat_mode;
7907
7908 /*
7909 * Abort the mapping if the first page is not physically
7910 * aligned to a 2MB page boundary.
7911 */
7912 ptepa = VM_PAGE_TO_PHYS(p);
7913 if (ptepa & (NBPDR - 1))
7914 return;
7915
7916 /*
7917 * Skip the first page. Abort the mapping if the rest of
7918 * the pages are not physically contiguous or have differing
7919 * memory attributes.
7920 */
7921 p = TAILQ_NEXT(p, listq);
7922 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
7923 pa += PAGE_SIZE) {
7924 KASSERT(vm_page_all_valid(p),
7925 ("pmap_object_init_pt: invalid page %p", p));
7926 if (pa != VM_PAGE_TO_PHYS(p) ||
7927 pat_mode != p->md.pat_mode)
7928 return;
7929 p = TAILQ_NEXT(p, listq);
7930 }
7931
7932 /*
7933 * Map using 2MB pages. Since "ptepa" is 2M aligned and
7934 * "size" is a multiple of 2M, adding the PAT setting to "pa"
7935 * will not affect the termination of this loop.
7936 */
7937 PMAP_LOCK(pmap);
7938 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, true);
7939 pa < ptepa + size; pa += NBPDR) {
7940 pde = pmap_alloc_pde(pmap, addr, &pdpg, NULL);
7941 if (pde == NULL) {
7942 /*
7943 * The creation of mappings below is only an
7944 * optimization. If a page directory page
7945 * cannot be allocated without blocking,
7946 * continue on to the next mapping rather than
7947 * blocking.
7948 */
7949 addr += NBPDR;
7950 continue;
7951 }
7952 if ((*pde & PG_V) == 0) {
7953 pde_store(pde, pa | PG_PS | PG_M | PG_A |
7954 PG_U | PG_RW | PG_V);
7955 pmap_resident_count_adj(pmap, NBPDR / PAGE_SIZE);
7956 counter_u64_add(pmap_pde_mappings, 1);
7957 } else {
7958 /* Continue on if the PDE is already valid. */
7959 pdpg->ref_count--;
7960 KASSERT(pdpg->ref_count > 0,
7961 ("pmap_object_init_pt: missing reference "
7962 "to page directory page, va: 0x%lx", addr));
7963 }
7964 addr += NBPDR;
7965 }
7966 PMAP_UNLOCK(pmap);
7967 }
7968 }
7969
7970 /*
7971 * Clear the wired attribute from the mappings for the specified range of
7972 * addresses in the given pmap. Every valid mapping within that range
7973 * must have the wired attribute set. In contrast, invalid mappings
7974 * cannot have the wired attribute set, so they are ignored.
7975 *
7976 * The wired attribute of the page table entry is not a hardware
7977 * feature, so there is no need to invalidate any TLB entries.
7978 * Since pmap_demote_pde() for the wired entry must never fail,
7979 * pmap_delayed_invl_start()/finish() calls around the
7980 * function are not needed.
7981 */
7982 void
pmap_unwire(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)7983 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
7984 {
7985 vm_offset_t va_next;
7986 pml4_entry_t *pml4e;
7987 pdp_entry_t *pdpe;
7988 pd_entry_t *pde;
7989 pt_entry_t *pte, PG_V, PG_G __diagused;
7990
7991 PG_V = pmap_valid_bit(pmap);
7992 PG_G = pmap_global_bit(pmap);
7993 PMAP_LOCK(pmap);
7994 for (; sva < eva; sva = va_next) {
7995 pml4e = pmap_pml4e(pmap, sva);
7996 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
7997 va_next = (sva + NBPML4) & ~PML4MASK;
7998 if (va_next < sva)
7999 va_next = eva;
8000 continue;
8001 }
8002
8003 va_next = (sva + NBPDP) & ~PDPMASK;
8004 if (va_next < sva)
8005 va_next = eva;
8006 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
8007 if ((*pdpe & PG_V) == 0)
8008 continue;
8009 if ((*pdpe & PG_PS) != 0) {
8010 KASSERT(va_next <= eva,
8011 ("partial update of non-transparent 1G mapping "
8012 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
8013 *pdpe, sva, eva, va_next));
8014 MPASS(pmap != kernel_pmap); /* XXXKIB */
8015 MPASS((*pdpe & (PG_MANAGED | PG_G)) == 0);
8016 atomic_clear_long(pdpe, PG_W);
8017 pmap->pm_stats.wired_count -= NBPDP / PAGE_SIZE;
8018 continue;
8019 }
8020
8021 va_next = (sva + NBPDR) & ~PDRMASK;
8022 if (va_next < sva)
8023 va_next = eva;
8024 pde = pmap_pdpe_to_pde(pdpe, sva);
8025 if ((*pde & PG_V) == 0)
8026 continue;
8027 if ((*pde & PG_PS) != 0) {
8028 if ((*pde & PG_W) == 0)
8029 panic("pmap_unwire: pde %#jx is missing PG_W",
8030 (uintmax_t)*pde);
8031
8032 /*
8033 * Are we unwiring the entire large page? If not,
8034 * demote the mapping and fall through.
8035 */
8036 if (sva + NBPDR == va_next && eva >= va_next) {
8037 atomic_clear_long(pde, PG_W);
8038 pmap->pm_stats.wired_count -= NBPDR /
8039 PAGE_SIZE;
8040 continue;
8041 } else if (!pmap_demote_pde(pmap, pde, sva))
8042 panic("pmap_unwire: demotion failed");
8043 }
8044 if (va_next > eva)
8045 va_next = eva;
8046 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
8047 sva += PAGE_SIZE) {
8048 if ((*pte & PG_V) == 0)
8049 continue;
8050 if ((*pte & PG_W) == 0)
8051 panic("pmap_unwire: pte %#jx is missing PG_W",
8052 (uintmax_t)*pte);
8053
8054 /*
8055 * PG_W must be cleared atomically. Although the pmap
8056 * lock synchronizes access to PG_W, another processor
8057 * could be setting PG_M and/or PG_A concurrently.
8058 */
8059 atomic_clear_long(pte, PG_W);
8060 pmap->pm_stats.wired_count--;
8061 }
8062 }
8063 PMAP_UNLOCK(pmap);
8064 }
8065
8066 /*
8067 * Copy the range specified by src_addr/len
8068 * from the source map to the range dst_addr/len
8069 * in the destination map.
8070 *
8071 * This routine is only advisory and need not do anything.
8072 */
8073 void
pmap_copy(pmap_t dst_pmap,pmap_t src_pmap,vm_offset_t dst_addr,vm_size_t len,vm_offset_t src_addr)8074 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
8075 vm_offset_t src_addr)
8076 {
8077 struct rwlock *lock;
8078 pml4_entry_t *pml4e;
8079 pdp_entry_t *pdpe;
8080 pd_entry_t *pde, srcptepaddr;
8081 pt_entry_t *dst_pte, PG_A, PG_M, PG_V, ptetemp, *src_pte;
8082 vm_offset_t addr, end_addr, va_next;
8083 vm_page_t dst_pdpg, dstmpte, srcmpte;
8084
8085 if (dst_addr != src_addr)
8086 return;
8087
8088 if (dst_pmap->pm_type != src_pmap->pm_type)
8089 return;
8090
8091 /*
8092 * EPT page table entries that require emulation of A/D bits are
8093 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
8094 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
8095 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
8096 * implementations flag an EPT misconfiguration for exec-only
8097 * mappings we skip this function entirely for emulated pmaps.
8098 */
8099 if (pmap_emulate_ad_bits(dst_pmap))
8100 return;
8101
8102 end_addr = src_addr + len;
8103 lock = NULL;
8104 if (dst_pmap < src_pmap) {
8105 PMAP_LOCK(dst_pmap);
8106 PMAP_LOCK(src_pmap);
8107 } else {
8108 PMAP_LOCK(src_pmap);
8109 PMAP_LOCK(dst_pmap);
8110 }
8111
8112 PG_A = pmap_accessed_bit(dst_pmap);
8113 PG_M = pmap_modified_bit(dst_pmap);
8114 PG_V = pmap_valid_bit(dst_pmap);
8115
8116 for (addr = src_addr; addr < end_addr; addr = va_next) {
8117 KASSERT(addr < UPT_MIN_ADDRESS,
8118 ("pmap_copy: invalid to pmap_copy page tables"));
8119
8120 pml4e = pmap_pml4e(src_pmap, addr);
8121 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
8122 va_next = (addr + NBPML4) & ~PML4MASK;
8123 if (va_next < addr)
8124 va_next = end_addr;
8125 continue;
8126 }
8127
8128 va_next = (addr + NBPDP) & ~PDPMASK;
8129 if (va_next < addr)
8130 va_next = end_addr;
8131 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
8132 if ((*pdpe & PG_V) == 0)
8133 continue;
8134 if ((*pdpe & PG_PS) != 0) {
8135 KASSERT(va_next <= end_addr,
8136 ("partial update of non-transparent 1G mapping "
8137 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
8138 *pdpe, addr, end_addr, va_next));
8139 MPASS((addr & PDPMASK) == 0);
8140 MPASS((*pdpe & PG_MANAGED) == 0);
8141 srcptepaddr = *pdpe;
8142 pdpe = pmap_pdpe(dst_pmap, addr);
8143 if (pdpe == NULL) {
8144 if (pmap_allocpte_alloc(dst_pmap,
8145 pmap_pml4e_pindex(addr), NULL, addr) ==
8146 NULL)
8147 break;
8148 pdpe = pmap_pdpe(dst_pmap, addr);
8149 } else {
8150 pml4e = pmap_pml4e(dst_pmap, addr);
8151 dst_pdpg = PHYS_TO_VM_PAGE(*pml4e & PG_FRAME);
8152 dst_pdpg->ref_count++;
8153 }
8154 KASSERT(*pdpe == 0,
8155 ("1G mapping present in dst pmap "
8156 "pdpe %#lx sva %#lx eva %#lx va_next %#lx",
8157 *pdpe, addr, end_addr, va_next));
8158 *pdpe = srcptepaddr & ~PG_W;
8159 pmap_resident_count_adj(dst_pmap, NBPDP / PAGE_SIZE);
8160 continue;
8161 }
8162
8163 va_next = (addr + NBPDR) & ~PDRMASK;
8164 if (va_next < addr)
8165 va_next = end_addr;
8166
8167 pde = pmap_pdpe_to_pde(pdpe, addr);
8168 srcptepaddr = *pde;
8169 if (srcptepaddr == 0)
8170 continue;
8171
8172 if (srcptepaddr & PG_PS) {
8173 /*
8174 * We can only virtual copy whole superpages.
8175 */
8176 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
8177 continue;
8178 pde = pmap_alloc_pde(dst_pmap, addr, &dst_pdpg, NULL);
8179 if (pde == NULL)
8180 break;
8181 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
8182 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
8183 PMAP_ENTER_NORECLAIM, &lock))) {
8184 /*
8185 * We leave the dirty bit unchanged because
8186 * managed read/write superpage mappings are
8187 * required to be dirty. However, managed
8188 * superpage mappings are not required to
8189 * have their accessed bit set, so we clear
8190 * it because we don't know if this mapping
8191 * will be used.
8192 */
8193 srcptepaddr &= ~PG_W;
8194 if ((srcptepaddr & PG_MANAGED) != 0)
8195 srcptepaddr &= ~PG_A;
8196 *pde = srcptepaddr;
8197 pmap_resident_count_adj(dst_pmap, NBPDR /
8198 PAGE_SIZE);
8199 counter_u64_add(pmap_pde_mappings, 1);
8200 } else
8201 pmap_abort_ptp(dst_pmap, addr, dst_pdpg);
8202 continue;
8203 }
8204
8205 srcptepaddr &= PG_FRAME;
8206 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
8207 KASSERT(srcmpte->ref_count > 0,
8208 ("pmap_copy: source page table page is unused"));
8209
8210 if (va_next > end_addr)
8211 va_next = end_addr;
8212
8213 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
8214 src_pte = &src_pte[pmap_pte_index(addr)];
8215 dstmpte = NULL;
8216 for (; addr < va_next; addr += PAGE_SIZE, src_pte++) {
8217 ptetemp = *src_pte;
8218
8219 /*
8220 * We only virtual copy managed pages.
8221 */
8222 if ((ptetemp & PG_MANAGED) == 0)
8223 continue;
8224
8225 if (dstmpte != NULL) {
8226 KASSERT(dstmpte->pindex ==
8227 pmap_pde_pindex(addr),
8228 ("dstmpte pindex/addr mismatch"));
8229 dstmpte->ref_count++;
8230 } else if ((dstmpte = pmap_allocpte(dst_pmap, addr,
8231 NULL)) == NULL)
8232 goto out;
8233 dst_pte = (pt_entry_t *)
8234 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
8235 dst_pte = &dst_pte[pmap_pte_index(addr)];
8236 if (*dst_pte == 0 &&
8237 pmap_try_insert_pv_entry(dst_pmap, addr,
8238 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME), &lock)) {
8239 /*
8240 * Clear the wired, modified, and accessed
8241 * (referenced) bits during the copy.
8242 */
8243 *dst_pte = ptetemp & ~(PG_W | PG_M | PG_A);
8244 pmap_resident_count_adj(dst_pmap, 1);
8245 } else {
8246 pmap_abort_ptp(dst_pmap, addr, dstmpte);
8247 goto out;
8248 }
8249 /* Have we copied all of the valid mappings? */
8250 if (dstmpte->ref_count >= srcmpte->ref_count)
8251 break;
8252 }
8253 }
8254 out:
8255 if (lock != NULL)
8256 rw_wunlock(lock);
8257 PMAP_UNLOCK(src_pmap);
8258 PMAP_UNLOCK(dst_pmap);
8259 }
8260
8261 int
pmap_vmspace_copy(pmap_t dst_pmap,pmap_t src_pmap)8262 pmap_vmspace_copy(pmap_t dst_pmap, pmap_t src_pmap)
8263 {
8264 int error;
8265
8266 if (dst_pmap->pm_type != src_pmap->pm_type ||
8267 dst_pmap->pm_type != PT_X86 ||
8268 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0)
8269 return (0);
8270 for (;;) {
8271 if (dst_pmap < src_pmap) {
8272 PMAP_LOCK(dst_pmap);
8273 PMAP_LOCK(src_pmap);
8274 } else {
8275 PMAP_LOCK(src_pmap);
8276 PMAP_LOCK(dst_pmap);
8277 }
8278 error = pmap_pkru_copy(dst_pmap, src_pmap);
8279 /* Clean up partial copy on failure due to no memory. */
8280 if (error == ENOMEM)
8281 pmap_pkru_deassign_all(dst_pmap);
8282 PMAP_UNLOCK(src_pmap);
8283 PMAP_UNLOCK(dst_pmap);
8284 if (error != ENOMEM)
8285 break;
8286 vm_wait(NULL);
8287 }
8288 return (error);
8289 }
8290
8291 /*
8292 * Zero the specified hardware page.
8293 */
8294 void
pmap_zero_page(vm_page_t m)8295 pmap_zero_page(vm_page_t m)
8296 {
8297 vm_offset_t va;
8298
8299 #ifdef TSLOG_PAGEZERO
8300 TSENTER();
8301 #endif
8302 va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
8303 pagezero((void *)va);
8304 #ifdef TSLOG_PAGEZERO
8305 TSEXIT();
8306 #endif
8307 }
8308
8309 /*
8310 * Zero an area within a single hardware page. off and size must not
8311 * cover an area beyond a single hardware page.
8312 */
8313 void
pmap_zero_page_area(vm_page_t m,int off,int size)8314 pmap_zero_page_area(vm_page_t m, int off, int size)
8315 {
8316 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
8317
8318 if (off == 0 && size == PAGE_SIZE)
8319 pagezero((void *)va);
8320 else
8321 bzero((char *)va + off, size);
8322 }
8323
8324 /*
8325 * Copy 1 specified hardware page to another.
8326 */
8327 void
pmap_copy_page(vm_page_t msrc,vm_page_t mdst)8328 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
8329 {
8330 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
8331 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
8332
8333 pagecopy((void *)src, (void *)dst);
8334 }
8335
8336 int unmapped_buf_allowed = 1;
8337
8338 void
pmap_copy_pages(vm_page_t ma[],vm_offset_t a_offset,vm_page_t mb[],vm_offset_t b_offset,int xfersize)8339 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
8340 vm_offset_t b_offset, int xfersize)
8341 {
8342 void *a_cp, *b_cp;
8343 vm_page_t pages[2];
8344 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
8345 int cnt;
8346 bool mapped;
8347
8348 while (xfersize > 0) {
8349 a_pg_offset = a_offset & PAGE_MASK;
8350 pages[0] = ma[a_offset >> PAGE_SHIFT];
8351 b_pg_offset = b_offset & PAGE_MASK;
8352 pages[1] = mb[b_offset >> PAGE_SHIFT];
8353 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
8354 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
8355 mapped = pmap_map_io_transient(pages, vaddr, 2, false);
8356 a_cp = (char *)vaddr[0] + a_pg_offset;
8357 b_cp = (char *)vaddr[1] + b_pg_offset;
8358 bcopy(a_cp, b_cp, cnt);
8359 if (__predict_false(mapped))
8360 pmap_unmap_io_transient(pages, vaddr, 2, false);
8361 a_offset += cnt;
8362 b_offset += cnt;
8363 xfersize -= cnt;
8364 }
8365 }
8366
8367 /*
8368 * Returns true if the pmap's pv is one of the first
8369 * 16 pvs linked to from this page. This count may
8370 * be changed upwards or downwards in the future; it
8371 * is only necessary that true be returned for a small
8372 * subset of pmaps for proper page aging.
8373 */
8374 bool
pmap_page_exists_quick(pmap_t pmap,vm_page_t m)8375 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
8376 {
8377 struct md_page *pvh;
8378 struct rwlock *lock;
8379 pv_entry_t pv;
8380 int loops = 0;
8381 bool rv;
8382
8383 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8384 ("pmap_page_exists_quick: page %p is not managed", m));
8385 rv = false;
8386 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8387 rw_rlock(lock);
8388 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8389 if (PV_PMAP(pv) == pmap) {
8390 rv = true;
8391 break;
8392 }
8393 loops++;
8394 if (loops >= 16)
8395 break;
8396 }
8397 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
8398 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8399 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8400 if (PV_PMAP(pv) == pmap) {
8401 rv = true;
8402 break;
8403 }
8404 loops++;
8405 if (loops >= 16)
8406 break;
8407 }
8408 }
8409 rw_runlock(lock);
8410 return (rv);
8411 }
8412
8413 /*
8414 * pmap_page_wired_mappings:
8415 *
8416 * Return the number of managed mappings to the given physical page
8417 * that are wired.
8418 */
8419 int
pmap_page_wired_mappings(vm_page_t m)8420 pmap_page_wired_mappings(vm_page_t m)
8421 {
8422 struct rwlock *lock;
8423 struct md_page *pvh;
8424 pmap_t pmap;
8425 pt_entry_t *pte;
8426 pv_entry_t pv;
8427 int count, md_gen, pvh_gen;
8428
8429 if ((m->oflags & VPO_UNMANAGED) != 0)
8430 return (0);
8431 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8432 rw_rlock(lock);
8433 restart:
8434 count = 0;
8435 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8436 pmap = PV_PMAP(pv);
8437 if (!PMAP_TRYLOCK(pmap)) {
8438 md_gen = m->md.pv_gen;
8439 rw_runlock(lock);
8440 PMAP_LOCK(pmap);
8441 rw_rlock(lock);
8442 if (md_gen != m->md.pv_gen) {
8443 PMAP_UNLOCK(pmap);
8444 goto restart;
8445 }
8446 }
8447 pte = pmap_pte(pmap, pv->pv_va);
8448 if ((*pte & PG_W) != 0)
8449 count++;
8450 PMAP_UNLOCK(pmap);
8451 }
8452 if ((m->flags & PG_FICTITIOUS) == 0) {
8453 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8454 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8455 pmap = PV_PMAP(pv);
8456 if (!PMAP_TRYLOCK(pmap)) {
8457 md_gen = m->md.pv_gen;
8458 pvh_gen = pvh->pv_gen;
8459 rw_runlock(lock);
8460 PMAP_LOCK(pmap);
8461 rw_rlock(lock);
8462 if (md_gen != m->md.pv_gen ||
8463 pvh_gen != pvh->pv_gen) {
8464 PMAP_UNLOCK(pmap);
8465 goto restart;
8466 }
8467 }
8468 pte = pmap_pde(pmap, pv->pv_va);
8469 if ((*pte & PG_W) != 0)
8470 count++;
8471 PMAP_UNLOCK(pmap);
8472 }
8473 }
8474 rw_runlock(lock);
8475 return (count);
8476 }
8477
8478 /*
8479 * Returns true if the given page is mapped individually or as part of
8480 * a 2mpage. Otherwise, returns false.
8481 */
8482 bool
pmap_page_is_mapped(vm_page_t m)8483 pmap_page_is_mapped(vm_page_t m)
8484 {
8485 struct rwlock *lock;
8486 bool rv;
8487
8488 if ((m->oflags & VPO_UNMANAGED) != 0)
8489 return (false);
8490 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8491 rw_rlock(lock);
8492 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
8493 ((m->flags & PG_FICTITIOUS) == 0 &&
8494 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
8495 rw_runlock(lock);
8496 return (rv);
8497 }
8498
8499 /*
8500 * Destroy all managed, non-wired mappings in the given user-space
8501 * pmap. This pmap cannot be active on any processor besides the
8502 * caller.
8503 *
8504 * This function cannot be applied to the kernel pmap. Moreover, it
8505 * is not intended for general use. It is only to be used during
8506 * process termination. Consequently, it can be implemented in ways
8507 * that make it faster than pmap_remove(). First, it can more quickly
8508 * destroy mappings by iterating over the pmap's collection of PV
8509 * entries, rather than searching the page table. Second, it doesn't
8510 * have to test and clear the page table entries atomically, because
8511 * no processor is currently accessing the user address space. In
8512 * particular, a page table entry's dirty bit won't change state once
8513 * this function starts.
8514 *
8515 * Although this function destroys all of the pmap's managed,
8516 * non-wired mappings, it can delay and batch the invalidation of TLB
8517 * entries without calling pmap_delayed_invl_start() and
8518 * pmap_delayed_invl_finish(). Because the pmap is not active on
8519 * any other processor, none of these TLB entries will ever be used
8520 * before their eventual invalidation. Consequently, there is no need
8521 * for either pmap_remove_all() or pmap_remove_write() to wait for
8522 * that eventual TLB invalidation.
8523 */
8524 void
pmap_remove_pages(pmap_t pmap)8525 pmap_remove_pages(pmap_t pmap)
8526 {
8527 pd_entry_t ptepde;
8528 pt_entry_t *pte, tpte;
8529 pt_entry_t PG_M, PG_RW, PG_V;
8530 struct spglist free;
8531 struct pv_chunklist free_chunks[PMAP_MEMDOM];
8532 vm_page_t m, mpte, mt;
8533 pv_entry_t pv;
8534 struct md_page *pvh;
8535 struct pv_chunk *pc, *npc;
8536 struct rwlock *lock;
8537 int64_t bit;
8538 uint64_t inuse, bitmask;
8539 int allfree, field, i, idx;
8540 #ifdef PV_STATS
8541 int freed;
8542 #endif
8543 bool superpage;
8544 vm_paddr_t pa;
8545
8546 /*
8547 * Assert that the given pmap is only active on the current
8548 * CPU. Unfortunately, we cannot block another CPU from
8549 * activating the pmap while this function is executing.
8550 */
8551 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
8552 #ifdef INVARIANTS
8553 {
8554 cpuset_t other_cpus;
8555
8556 other_cpus = all_cpus;
8557 critical_enter();
8558 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
8559 CPU_AND(&other_cpus, &other_cpus, &pmap->pm_active);
8560 critical_exit();
8561 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
8562 }
8563 #endif
8564
8565 lock = NULL;
8566 PG_M = pmap_modified_bit(pmap);
8567 PG_V = pmap_valid_bit(pmap);
8568 PG_RW = pmap_rw_bit(pmap);
8569
8570 for (i = 0; i < PMAP_MEMDOM; i++)
8571 TAILQ_INIT(&free_chunks[i]);
8572 SLIST_INIT(&free);
8573 PMAP_LOCK(pmap);
8574 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
8575 allfree = 1;
8576 #ifdef PV_STATS
8577 freed = 0;
8578 #endif
8579 for (field = 0; field < _NPCM; field++) {
8580 inuse = ~pc->pc_map[field] & pc_freemask[field];
8581 while (inuse != 0) {
8582 bit = bsfq(inuse);
8583 bitmask = 1UL << bit;
8584 idx = field * 64 + bit;
8585 pv = &pc->pc_pventry[idx];
8586 inuse &= ~bitmask;
8587
8588 pte = pmap_pdpe(pmap, pv->pv_va);
8589 ptepde = *pte;
8590 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
8591 tpte = *pte;
8592 if ((tpte & (PG_PS | PG_V)) == PG_V) {
8593 superpage = false;
8594 ptepde = tpte;
8595 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
8596 PG_FRAME);
8597 pte = &pte[pmap_pte_index(pv->pv_va)];
8598 tpte = *pte;
8599 } else {
8600 /*
8601 * Keep track whether 'tpte' is a
8602 * superpage explicitly instead of
8603 * relying on PG_PS being set.
8604 *
8605 * This is because PG_PS is numerically
8606 * identical to PG_PTE_PAT and thus a
8607 * regular page could be mistaken for
8608 * a superpage.
8609 */
8610 superpage = true;
8611 }
8612
8613 if ((tpte & PG_V) == 0) {
8614 panic("bad pte va %lx pte %lx",
8615 pv->pv_va, tpte);
8616 }
8617
8618 /*
8619 * We cannot remove wired pages from a process' mapping at this time
8620 */
8621 if (tpte & PG_W) {
8622 allfree = 0;
8623 continue;
8624 }
8625
8626 /* Mark free */
8627 pc->pc_map[field] |= bitmask;
8628
8629 /*
8630 * Because this pmap is not active on other
8631 * processors, the dirty bit cannot have
8632 * changed state since we last loaded pte.
8633 */
8634 pte_clear(pte);
8635
8636 if (superpage)
8637 pa = tpte & PG_PS_FRAME;
8638 else
8639 pa = tpte & PG_FRAME;
8640
8641 m = PHYS_TO_VM_PAGE(pa);
8642 KASSERT(m->phys_addr == pa,
8643 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
8644 m, (uintmax_t)m->phys_addr,
8645 (uintmax_t)tpte));
8646
8647 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
8648 m < &vm_page_array[vm_page_array_size],
8649 ("pmap_remove_pages: bad tpte %#jx",
8650 (uintmax_t)tpte));
8651
8652 /*
8653 * Update the vm_page_t clean/reference bits.
8654 */
8655 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
8656 if (superpage) {
8657 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
8658 vm_page_dirty(mt);
8659 } else
8660 vm_page_dirty(m);
8661 }
8662
8663 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
8664
8665 if (superpage) {
8666 pmap_resident_count_adj(pmap, -NBPDR / PAGE_SIZE);
8667 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
8668 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
8669 pvh->pv_gen++;
8670 if (TAILQ_EMPTY(&pvh->pv_list)) {
8671 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
8672 if ((mt->a.flags & PGA_WRITEABLE) != 0 &&
8673 TAILQ_EMPTY(&mt->md.pv_list))
8674 vm_page_aflag_clear(mt, PGA_WRITEABLE);
8675 }
8676 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
8677 if (mpte != NULL) {
8678 KASSERT(vm_page_any_valid(mpte),
8679 ("pmap_remove_pages: pte page not promoted"));
8680 pmap_pt_page_count_adj(pmap, -1);
8681 KASSERT(mpte->ref_count == NPTEPG,
8682 ("pmap_remove_pages: pte page reference count error"));
8683 mpte->ref_count = 0;
8684 pmap_add_delayed_free_list(mpte, &free, false);
8685 }
8686 } else {
8687 pmap_resident_count_adj(pmap, -1);
8688 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
8689 m->md.pv_gen++;
8690 if ((m->a.flags & PGA_WRITEABLE) != 0 &&
8691 TAILQ_EMPTY(&m->md.pv_list) &&
8692 (m->flags & PG_FICTITIOUS) == 0) {
8693 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8694 if (TAILQ_EMPTY(&pvh->pv_list))
8695 vm_page_aflag_clear(m, PGA_WRITEABLE);
8696 }
8697 }
8698 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
8699 #ifdef PV_STATS
8700 freed++;
8701 #endif
8702 }
8703 }
8704 PV_STAT(counter_u64_add(pv_entry_frees, freed));
8705 PV_STAT(counter_u64_add(pv_entry_spare, freed));
8706 PV_STAT(counter_u64_add(pv_entry_count, -freed));
8707 if (allfree) {
8708 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
8709 TAILQ_INSERT_TAIL(&free_chunks[pc_to_domain(pc)], pc, pc_list);
8710 }
8711 }
8712 if (lock != NULL)
8713 rw_wunlock(lock);
8714 pmap_invalidate_all(pmap);
8715 pmap_pkru_deassign_all(pmap);
8716 free_pv_chunk_batch((struct pv_chunklist *)&free_chunks);
8717 PMAP_UNLOCK(pmap);
8718 vm_page_free_pages_toq(&free, true);
8719 }
8720
8721 static bool
pmap_page_test_mappings(vm_page_t m,bool accessed,bool modified)8722 pmap_page_test_mappings(vm_page_t m, bool accessed, bool modified)
8723 {
8724 struct rwlock *lock;
8725 pv_entry_t pv;
8726 struct md_page *pvh;
8727 pt_entry_t *pte, mask;
8728 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
8729 pmap_t pmap;
8730 int md_gen, pvh_gen;
8731 bool rv;
8732
8733 rv = false;
8734 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8735 rw_rlock(lock);
8736 restart:
8737 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8738 pmap = PV_PMAP(pv);
8739 if (!PMAP_TRYLOCK(pmap)) {
8740 md_gen = m->md.pv_gen;
8741 rw_runlock(lock);
8742 PMAP_LOCK(pmap);
8743 rw_rlock(lock);
8744 if (md_gen != m->md.pv_gen) {
8745 PMAP_UNLOCK(pmap);
8746 goto restart;
8747 }
8748 }
8749 pte = pmap_pte(pmap, pv->pv_va);
8750 mask = 0;
8751 if (modified) {
8752 PG_M = pmap_modified_bit(pmap);
8753 PG_RW = pmap_rw_bit(pmap);
8754 mask |= PG_RW | PG_M;
8755 }
8756 if (accessed) {
8757 PG_A = pmap_accessed_bit(pmap);
8758 PG_V = pmap_valid_bit(pmap);
8759 mask |= PG_V | PG_A;
8760 }
8761 rv = (*pte & mask) == mask;
8762 PMAP_UNLOCK(pmap);
8763 if (rv)
8764 goto out;
8765 }
8766 if ((m->flags & PG_FICTITIOUS) == 0) {
8767 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
8768 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
8769 pmap = PV_PMAP(pv);
8770 if (!PMAP_TRYLOCK(pmap)) {
8771 md_gen = m->md.pv_gen;
8772 pvh_gen = pvh->pv_gen;
8773 rw_runlock(lock);
8774 PMAP_LOCK(pmap);
8775 rw_rlock(lock);
8776 if (md_gen != m->md.pv_gen ||
8777 pvh_gen != pvh->pv_gen) {
8778 PMAP_UNLOCK(pmap);
8779 goto restart;
8780 }
8781 }
8782 pte = pmap_pde(pmap, pv->pv_va);
8783 mask = 0;
8784 if (modified) {
8785 PG_M = pmap_modified_bit(pmap);
8786 PG_RW = pmap_rw_bit(pmap);
8787 mask |= PG_RW | PG_M;
8788 }
8789 if (accessed) {
8790 PG_A = pmap_accessed_bit(pmap);
8791 PG_V = pmap_valid_bit(pmap);
8792 mask |= PG_V | PG_A;
8793 }
8794 rv = (*pte & mask) == mask;
8795 PMAP_UNLOCK(pmap);
8796 if (rv)
8797 goto out;
8798 }
8799 }
8800 out:
8801 rw_runlock(lock);
8802 return (rv);
8803 }
8804
8805 /*
8806 * pmap_is_modified:
8807 *
8808 * Return whether or not the specified physical page was modified
8809 * in any physical maps.
8810 */
8811 bool
pmap_is_modified(vm_page_t m)8812 pmap_is_modified(vm_page_t m)
8813 {
8814
8815 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8816 ("pmap_is_modified: page %p is not managed", m));
8817
8818 /*
8819 * If the page is not busied then this check is racy.
8820 */
8821 if (!pmap_page_is_write_mapped(m))
8822 return (false);
8823 return (pmap_page_test_mappings(m, false, true));
8824 }
8825
8826 /*
8827 * pmap_is_prefaultable:
8828 *
8829 * Return whether or not the specified virtual address is eligible
8830 * for prefault.
8831 */
8832 bool
pmap_is_prefaultable(pmap_t pmap,vm_offset_t addr)8833 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
8834 {
8835 pd_entry_t *pde;
8836 pt_entry_t *pte, PG_V;
8837 bool rv;
8838
8839 PG_V = pmap_valid_bit(pmap);
8840
8841 /*
8842 * Return true if and only if the PTE for the specified virtual
8843 * address is allocated but invalid.
8844 */
8845 rv = false;
8846 PMAP_LOCK(pmap);
8847 pde = pmap_pde(pmap, addr);
8848 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
8849 pte = pmap_pde_to_pte(pde, addr);
8850 rv = (*pte & PG_V) == 0;
8851 }
8852 PMAP_UNLOCK(pmap);
8853 return (rv);
8854 }
8855
8856 /*
8857 * pmap_is_referenced:
8858 *
8859 * Return whether or not the specified physical page was referenced
8860 * in any physical maps.
8861 */
8862 bool
pmap_is_referenced(vm_page_t m)8863 pmap_is_referenced(vm_page_t m)
8864 {
8865
8866 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8867 ("pmap_is_referenced: page %p is not managed", m));
8868 return (pmap_page_test_mappings(m, true, false));
8869 }
8870
8871 /*
8872 * Clear the write and modified bits in each of the given page's mappings.
8873 */
8874 void
pmap_remove_write(vm_page_t m)8875 pmap_remove_write(vm_page_t m)
8876 {
8877 struct md_page *pvh;
8878 pmap_t pmap;
8879 struct rwlock *lock;
8880 pv_entry_t next_pv, pv;
8881 pd_entry_t *pde;
8882 pt_entry_t oldpte, *pte, PG_M, PG_RW;
8883 vm_offset_t va;
8884 int pvh_gen, md_gen;
8885
8886 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8887 ("pmap_remove_write: page %p is not managed", m));
8888
8889 vm_page_assert_busied(m);
8890 if (!pmap_page_is_write_mapped(m))
8891 return;
8892
8893 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
8894 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
8895 pa_to_pvh(VM_PAGE_TO_PHYS(m));
8896 rw_wlock(lock);
8897 retry:
8898 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
8899 pmap = PV_PMAP(pv);
8900 if (!PMAP_TRYLOCK(pmap)) {
8901 pvh_gen = pvh->pv_gen;
8902 rw_wunlock(lock);
8903 PMAP_LOCK(pmap);
8904 rw_wlock(lock);
8905 if (pvh_gen != pvh->pv_gen) {
8906 PMAP_UNLOCK(pmap);
8907 goto retry;
8908 }
8909 }
8910 PG_RW = pmap_rw_bit(pmap);
8911 va = pv->pv_va;
8912 pde = pmap_pde(pmap, va);
8913 if ((*pde & PG_RW) != 0)
8914 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
8915 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
8916 ("inconsistent pv lock %p %p for page %p",
8917 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
8918 PMAP_UNLOCK(pmap);
8919 }
8920 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
8921 pmap = PV_PMAP(pv);
8922 if (!PMAP_TRYLOCK(pmap)) {
8923 pvh_gen = pvh->pv_gen;
8924 md_gen = m->md.pv_gen;
8925 rw_wunlock(lock);
8926 PMAP_LOCK(pmap);
8927 rw_wlock(lock);
8928 if (pvh_gen != pvh->pv_gen ||
8929 md_gen != m->md.pv_gen) {
8930 PMAP_UNLOCK(pmap);
8931 goto retry;
8932 }
8933 }
8934 PG_M = pmap_modified_bit(pmap);
8935 PG_RW = pmap_rw_bit(pmap);
8936 pde = pmap_pde(pmap, pv->pv_va);
8937 KASSERT((*pde & PG_PS) == 0,
8938 ("pmap_remove_write: found a 2mpage in page %p's pv list",
8939 m));
8940 pte = pmap_pde_to_pte(pde, pv->pv_va);
8941 oldpte = *pte;
8942 if (oldpte & PG_RW) {
8943 while (!atomic_fcmpset_long(pte, &oldpte, oldpte &
8944 ~(PG_RW | PG_M)))
8945 cpu_spinwait();
8946 if ((oldpte & PG_M) != 0)
8947 vm_page_dirty(m);
8948 pmap_invalidate_page(pmap, pv->pv_va);
8949 }
8950 PMAP_UNLOCK(pmap);
8951 }
8952 rw_wunlock(lock);
8953 vm_page_aflag_clear(m, PGA_WRITEABLE);
8954 pmap_delayed_invl_wait(m);
8955 }
8956
8957 /*
8958 * pmap_ts_referenced:
8959 *
8960 * Return a count of reference bits for a page, clearing those bits.
8961 * It is not necessary for every reference bit to be cleared, but it
8962 * is necessary that 0 only be returned when there are truly no
8963 * reference bits set.
8964 *
8965 * As an optimization, update the page's dirty field if a modified bit is
8966 * found while counting reference bits. This opportunistic update can be
8967 * performed at low cost and can eliminate the need for some future calls
8968 * to pmap_is_modified(). However, since this function stops after
8969 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
8970 * dirty pages. Those dirty pages will only be detected by a future call
8971 * to pmap_is_modified().
8972 *
8973 * A DI block is not needed within this function, because
8974 * invalidations are performed before the PV list lock is
8975 * released.
8976 */
8977 int
pmap_ts_referenced(vm_page_t m)8978 pmap_ts_referenced(vm_page_t m)
8979 {
8980 struct md_page *pvh;
8981 pv_entry_t pv, pvf;
8982 pmap_t pmap;
8983 struct rwlock *lock;
8984 pd_entry_t oldpde, *pde;
8985 pt_entry_t *pte, PG_A, PG_M, PG_RW;
8986 vm_offset_t va;
8987 vm_paddr_t pa;
8988 int cleared, md_gen, not_cleared, pvh_gen;
8989 struct spglist free;
8990 bool demoted;
8991
8992 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
8993 ("pmap_ts_referenced: page %p is not managed", m));
8994 SLIST_INIT(&free);
8995 cleared = 0;
8996 pa = VM_PAGE_TO_PHYS(m);
8997 lock = PHYS_TO_PV_LIST_LOCK(pa);
8998 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
8999 rw_wlock(lock);
9000 retry:
9001 not_cleared = 0;
9002 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
9003 goto small_mappings;
9004 pv = pvf;
9005 do {
9006 if (pvf == NULL)
9007 pvf = pv;
9008 pmap = PV_PMAP(pv);
9009 if (!PMAP_TRYLOCK(pmap)) {
9010 pvh_gen = pvh->pv_gen;
9011 rw_wunlock(lock);
9012 PMAP_LOCK(pmap);
9013 rw_wlock(lock);
9014 if (pvh_gen != pvh->pv_gen) {
9015 PMAP_UNLOCK(pmap);
9016 goto retry;
9017 }
9018 }
9019 PG_A = pmap_accessed_bit(pmap);
9020 PG_M = pmap_modified_bit(pmap);
9021 PG_RW = pmap_rw_bit(pmap);
9022 va = pv->pv_va;
9023 pde = pmap_pde(pmap, pv->pv_va);
9024 oldpde = *pde;
9025 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
9026 /*
9027 * Although "oldpde" is mapping a 2MB page, because
9028 * this function is called at a 4KB page granularity,
9029 * we only update the 4KB page under test.
9030 */
9031 vm_page_dirty(m);
9032 }
9033 if ((oldpde & PG_A) != 0) {
9034 /*
9035 * Since this reference bit is shared by 512 4KB
9036 * pages, it should not be cleared every time it is
9037 * tested. Apply a simple "hash" function on the
9038 * physical page number, the virtual superpage number,
9039 * and the pmap address to select one 4KB page out of
9040 * the 512 on which testing the reference bit will
9041 * result in clearing that reference bit. This
9042 * function is designed to avoid the selection of the
9043 * same 4KB page for every 2MB page mapping.
9044 *
9045 * On demotion, a mapping that hasn't been referenced
9046 * is simply destroyed. To avoid the possibility of a
9047 * subsequent page fault on a demoted wired mapping,
9048 * always leave its reference bit set. Moreover,
9049 * since the superpage is wired, the current state of
9050 * its reference bit won't affect page replacement.
9051 */
9052 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
9053 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
9054 (oldpde & PG_W) == 0) {
9055 if (safe_to_clear_referenced(pmap, oldpde)) {
9056 atomic_clear_long(pde, PG_A);
9057 pmap_invalidate_page(pmap, pv->pv_va);
9058 demoted = false;
9059 } else if (pmap_demote_pde_locked(pmap, pde,
9060 pv->pv_va, &lock)) {
9061 /*
9062 * Remove the mapping to a single page
9063 * so that a subsequent access may
9064 * repromote. Since the underlying
9065 * page table page is fully populated,
9066 * this removal never frees a page
9067 * table page.
9068 */
9069 demoted = true;
9070 va += VM_PAGE_TO_PHYS(m) - (oldpde &
9071 PG_PS_FRAME);
9072 pte = pmap_pde_to_pte(pde, va);
9073 pmap_remove_pte(pmap, pte, va, *pde,
9074 NULL, &lock);
9075 pmap_invalidate_page(pmap, va);
9076 } else
9077 demoted = true;
9078
9079 if (demoted) {
9080 /*
9081 * The superpage mapping was removed
9082 * entirely and therefore 'pv' is no
9083 * longer valid.
9084 */
9085 if (pvf == pv)
9086 pvf = NULL;
9087 pv = NULL;
9088 }
9089 cleared++;
9090 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
9091 ("inconsistent pv lock %p %p for page %p",
9092 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
9093 } else
9094 not_cleared++;
9095 }
9096 PMAP_UNLOCK(pmap);
9097 /* Rotate the PV list if it has more than one entry. */
9098 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
9099 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
9100 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
9101 pvh->pv_gen++;
9102 }
9103 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
9104 goto out;
9105 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
9106 small_mappings:
9107 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
9108 goto out;
9109 pv = pvf;
9110 do {
9111 if (pvf == NULL)
9112 pvf = pv;
9113 pmap = PV_PMAP(pv);
9114 if (!PMAP_TRYLOCK(pmap)) {
9115 pvh_gen = pvh->pv_gen;
9116 md_gen = m->md.pv_gen;
9117 rw_wunlock(lock);
9118 PMAP_LOCK(pmap);
9119 rw_wlock(lock);
9120 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
9121 PMAP_UNLOCK(pmap);
9122 goto retry;
9123 }
9124 }
9125 PG_A = pmap_accessed_bit(pmap);
9126 PG_M = pmap_modified_bit(pmap);
9127 PG_RW = pmap_rw_bit(pmap);
9128 pde = pmap_pde(pmap, pv->pv_va);
9129 KASSERT((*pde & PG_PS) == 0,
9130 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
9131 m));
9132 pte = pmap_pde_to_pte(pde, pv->pv_va);
9133 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
9134 vm_page_dirty(m);
9135 if ((*pte & PG_A) != 0) {
9136 if (safe_to_clear_referenced(pmap, *pte)) {
9137 atomic_clear_long(pte, PG_A);
9138 pmap_invalidate_page(pmap, pv->pv_va);
9139 cleared++;
9140 } else if ((*pte & PG_W) == 0) {
9141 /*
9142 * Wired pages cannot be paged out so
9143 * doing accessed bit emulation for
9144 * them is wasted effort. We do the
9145 * hard work for unwired pages only.
9146 */
9147 pmap_remove_pte(pmap, pte, pv->pv_va,
9148 *pde, &free, &lock);
9149 pmap_invalidate_page(pmap, pv->pv_va);
9150 cleared++;
9151 if (pvf == pv)
9152 pvf = NULL;
9153 pv = NULL;
9154 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
9155 ("inconsistent pv lock %p %p for page %p",
9156 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
9157 } else
9158 not_cleared++;
9159 }
9160 PMAP_UNLOCK(pmap);
9161 /* Rotate the PV list if it has more than one entry. */
9162 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
9163 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
9164 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
9165 m->md.pv_gen++;
9166 }
9167 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
9168 not_cleared < PMAP_TS_REFERENCED_MAX);
9169 out:
9170 rw_wunlock(lock);
9171 vm_page_free_pages_toq(&free, true);
9172 return (cleared + not_cleared);
9173 }
9174
9175 /*
9176 * Apply the given advice to the specified range of addresses within the
9177 * given pmap. Depending on the advice, clear the referenced and/or
9178 * modified flags in each mapping and set the mapped page's dirty field.
9179 */
9180 void
pmap_advise(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,int advice)9181 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
9182 {
9183 struct rwlock *lock;
9184 pml4_entry_t *pml4e;
9185 pdp_entry_t *pdpe;
9186 pd_entry_t oldpde, *pde;
9187 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
9188 vm_offset_t va, va_next;
9189 vm_page_t m;
9190 bool anychanged;
9191
9192 if (advice != MADV_DONTNEED && advice != MADV_FREE)
9193 return;
9194
9195 /*
9196 * A/D bit emulation requires an alternate code path when clearing
9197 * the modified and accessed bits below. Since this function is
9198 * advisory in nature we skip it entirely for pmaps that require
9199 * A/D bit emulation.
9200 */
9201 if (pmap_emulate_ad_bits(pmap))
9202 return;
9203
9204 PG_A = pmap_accessed_bit(pmap);
9205 PG_G = pmap_global_bit(pmap);
9206 PG_M = pmap_modified_bit(pmap);
9207 PG_V = pmap_valid_bit(pmap);
9208 PG_RW = pmap_rw_bit(pmap);
9209 anychanged = false;
9210 pmap_delayed_invl_start();
9211 PMAP_LOCK(pmap);
9212 for (; sva < eva; sva = va_next) {
9213 pml4e = pmap_pml4e(pmap, sva);
9214 if (pml4e == NULL || (*pml4e & PG_V) == 0) {
9215 va_next = (sva + NBPML4) & ~PML4MASK;
9216 if (va_next < sva)
9217 va_next = eva;
9218 continue;
9219 }
9220
9221 va_next = (sva + NBPDP) & ~PDPMASK;
9222 if (va_next < sva)
9223 va_next = eva;
9224 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
9225 if ((*pdpe & PG_V) == 0)
9226 continue;
9227 if ((*pdpe & PG_PS) != 0)
9228 continue;
9229
9230 va_next = (sva + NBPDR) & ~PDRMASK;
9231 if (va_next < sva)
9232 va_next = eva;
9233 pde = pmap_pdpe_to_pde(pdpe, sva);
9234 oldpde = *pde;
9235 if ((oldpde & PG_V) == 0)
9236 continue;
9237 else if ((oldpde & PG_PS) != 0) {
9238 if ((oldpde & PG_MANAGED) == 0)
9239 continue;
9240 lock = NULL;
9241 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
9242 if (lock != NULL)
9243 rw_wunlock(lock);
9244
9245 /*
9246 * The large page mapping was destroyed.
9247 */
9248 continue;
9249 }
9250
9251 /*
9252 * Unless the page mappings are wired, remove the
9253 * mapping to a single page so that a subsequent
9254 * access may repromote. Choosing the last page
9255 * within the address range [sva, min(va_next, eva))
9256 * generally results in more repromotions. Since the
9257 * underlying page table page is fully populated, this
9258 * removal never frees a page table page.
9259 */
9260 if ((oldpde & PG_W) == 0) {
9261 va = eva;
9262 if (va > va_next)
9263 va = va_next;
9264 va -= PAGE_SIZE;
9265 KASSERT(va >= sva,
9266 ("pmap_advise: no address gap"));
9267 pte = pmap_pde_to_pte(pde, va);
9268 KASSERT((*pte & PG_V) != 0,
9269 ("pmap_advise: invalid PTE"));
9270 pmap_remove_pte(pmap, pte, va, *pde, NULL,
9271 &lock);
9272 anychanged = true;
9273 }
9274 if (lock != NULL)
9275 rw_wunlock(lock);
9276 }
9277 if (va_next > eva)
9278 va_next = eva;
9279 va = va_next;
9280 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
9281 sva += PAGE_SIZE) {
9282 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
9283 goto maybe_invlrng;
9284 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
9285 if (advice == MADV_DONTNEED) {
9286 /*
9287 * Future calls to pmap_is_modified()
9288 * can be avoided by making the page
9289 * dirty now.
9290 */
9291 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
9292 vm_page_dirty(m);
9293 }
9294 atomic_clear_long(pte, PG_M | PG_A);
9295 } else if ((*pte & PG_A) != 0)
9296 atomic_clear_long(pte, PG_A);
9297 else
9298 goto maybe_invlrng;
9299
9300 if ((*pte & PG_G) != 0) {
9301 if (va == va_next)
9302 va = sva;
9303 } else
9304 anychanged = true;
9305 continue;
9306 maybe_invlrng:
9307 if (va != va_next) {
9308 pmap_invalidate_range(pmap, va, sva);
9309 va = va_next;
9310 }
9311 }
9312 if (va != va_next)
9313 pmap_invalidate_range(pmap, va, sva);
9314 }
9315 if (anychanged)
9316 pmap_invalidate_all(pmap);
9317 PMAP_UNLOCK(pmap);
9318 pmap_delayed_invl_finish();
9319 }
9320
9321 /*
9322 * Clear the modify bits on the specified physical page.
9323 */
9324 void
pmap_clear_modify(vm_page_t m)9325 pmap_clear_modify(vm_page_t m)
9326 {
9327 struct md_page *pvh;
9328 pmap_t pmap;
9329 pv_entry_t next_pv, pv;
9330 pd_entry_t oldpde, *pde;
9331 pt_entry_t *pte, PG_M, PG_RW;
9332 struct rwlock *lock;
9333 vm_offset_t va;
9334 int md_gen, pvh_gen;
9335
9336 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
9337 ("pmap_clear_modify: page %p is not managed", m));
9338 vm_page_assert_busied(m);
9339
9340 if (!pmap_page_is_write_mapped(m))
9341 return;
9342 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
9343 pa_to_pvh(VM_PAGE_TO_PHYS(m));
9344 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
9345 rw_wlock(lock);
9346 restart:
9347 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
9348 pmap = PV_PMAP(pv);
9349 if (!PMAP_TRYLOCK(pmap)) {
9350 pvh_gen = pvh->pv_gen;
9351 rw_wunlock(lock);
9352 PMAP_LOCK(pmap);
9353 rw_wlock(lock);
9354 if (pvh_gen != pvh->pv_gen) {
9355 PMAP_UNLOCK(pmap);
9356 goto restart;
9357 }
9358 }
9359 PG_M = pmap_modified_bit(pmap);
9360 PG_RW = pmap_rw_bit(pmap);
9361 va = pv->pv_va;
9362 pde = pmap_pde(pmap, va);
9363 oldpde = *pde;
9364 /* If oldpde has PG_RW set, then it also has PG_M set. */
9365 if ((oldpde & PG_RW) != 0 &&
9366 pmap_demote_pde_locked(pmap, pde, va, &lock) &&
9367 (oldpde & PG_W) == 0) {
9368 /*
9369 * Write protect the mapping to a single page so that
9370 * a subsequent write access may repromote.
9371 */
9372 va += VM_PAGE_TO_PHYS(m) - (oldpde & PG_PS_FRAME);
9373 pte = pmap_pde_to_pte(pde, va);
9374 atomic_clear_long(pte, PG_M | PG_RW);
9375 vm_page_dirty(m);
9376 pmap_invalidate_page(pmap, va);
9377 }
9378 PMAP_UNLOCK(pmap);
9379 }
9380 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
9381 pmap = PV_PMAP(pv);
9382 if (!PMAP_TRYLOCK(pmap)) {
9383 md_gen = m->md.pv_gen;
9384 pvh_gen = pvh->pv_gen;
9385 rw_wunlock(lock);
9386 PMAP_LOCK(pmap);
9387 rw_wlock(lock);
9388 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
9389 PMAP_UNLOCK(pmap);
9390 goto restart;
9391 }
9392 }
9393 PG_M = pmap_modified_bit(pmap);
9394 PG_RW = pmap_rw_bit(pmap);
9395 pde = pmap_pde(pmap, pv->pv_va);
9396 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
9397 " a 2mpage in page %p's pv list", m));
9398 pte = pmap_pde_to_pte(pde, pv->pv_va);
9399 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
9400 atomic_clear_long(pte, PG_M);
9401 pmap_invalidate_page(pmap, pv->pv_va);
9402 }
9403 PMAP_UNLOCK(pmap);
9404 }
9405 rw_wunlock(lock);
9406 }
9407
9408 /*
9409 * Miscellaneous support routines follow
9410 */
9411
9412 /* Adjust the properties for a leaf page table entry. */
9413 static __inline void
pmap_pte_props(pt_entry_t * pte,u_long bits,u_long mask)9414 pmap_pte_props(pt_entry_t *pte, u_long bits, u_long mask)
9415 {
9416 u_long opte, npte;
9417
9418 opte = *(u_long *)pte;
9419 do {
9420 npte = opte & ~mask;
9421 npte |= bits;
9422 } while (npte != opte && !atomic_fcmpset_long((u_long *)pte, &opte,
9423 npte));
9424 }
9425
9426 /*
9427 * Map a set of physical memory pages into the kernel virtual
9428 * address space. Return a pointer to where it is mapped. This
9429 * routine is intended to be used for mapping device memory,
9430 * NOT real memory.
9431 */
9432 static void *
pmap_mapdev_internal(vm_paddr_t pa,vm_size_t size,int mode,int flags)9433 pmap_mapdev_internal(vm_paddr_t pa, vm_size_t size, int mode, int flags)
9434 {
9435 struct pmap_preinit_mapping *ppim;
9436 vm_offset_t va, offset;
9437 vm_size_t tmpsize;
9438 int i;
9439
9440 offset = pa & PAGE_MASK;
9441 size = round_page(offset + size);
9442 pa = trunc_page(pa);
9443
9444 if (!pmap_initialized) {
9445 va = 0;
9446 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9447 ppim = pmap_preinit_mapping + i;
9448 if (ppim->va == 0) {
9449 ppim->pa = pa;
9450 ppim->sz = size;
9451 ppim->mode = mode;
9452 ppim->va = virtual_avail;
9453 virtual_avail += size;
9454 va = ppim->va;
9455 break;
9456 }
9457 }
9458 if (va == 0)
9459 panic("%s: too many preinit mappings", __func__);
9460 } else {
9461 /*
9462 * If we have a preinit mapping, reuse it.
9463 */
9464 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9465 ppim = pmap_preinit_mapping + i;
9466 if (ppim->pa == pa && ppim->sz == size &&
9467 (ppim->mode == mode ||
9468 (flags & MAPDEV_SETATTR) == 0))
9469 return ((void *)(ppim->va + offset));
9470 }
9471 /*
9472 * If the specified range of physical addresses fits within
9473 * the direct map window, use the direct map.
9474 */
9475 if (pa < dmaplimit && pa + size <= dmaplimit) {
9476 va = PHYS_TO_DMAP(pa);
9477 if ((flags & MAPDEV_SETATTR) != 0) {
9478 PMAP_LOCK(kernel_pmap);
9479 i = pmap_change_props_locked(va, size,
9480 PROT_NONE, mode, flags);
9481 PMAP_UNLOCK(kernel_pmap);
9482 } else
9483 i = 0;
9484 if (!i)
9485 return ((void *)(va + offset));
9486 }
9487 va = kva_alloc(size);
9488 if (va == 0)
9489 panic("%s: Couldn't allocate KVA", __func__);
9490 }
9491 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
9492 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
9493 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
9494 if ((flags & MAPDEV_FLUSHCACHE) != 0)
9495 pmap_invalidate_cache_range(va, va + tmpsize);
9496 return ((void *)(va + offset));
9497 }
9498
9499 void *
pmap_mapdev_attr(vm_paddr_t pa,vm_size_t size,int mode)9500 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
9501 {
9502
9503 return (pmap_mapdev_internal(pa, size, mode, MAPDEV_FLUSHCACHE |
9504 MAPDEV_SETATTR));
9505 }
9506
9507 void *
pmap_mapdev(vm_paddr_t pa,vm_size_t size)9508 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
9509 {
9510
9511 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
9512 }
9513
9514 void *
pmap_mapdev_pciecfg(vm_paddr_t pa,vm_size_t size)9515 pmap_mapdev_pciecfg(vm_paddr_t pa, vm_size_t size)
9516 {
9517
9518 return (pmap_mapdev_internal(pa, size, PAT_UNCACHEABLE,
9519 MAPDEV_SETATTR));
9520 }
9521
9522 void *
pmap_mapbios(vm_paddr_t pa,vm_size_t size)9523 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
9524 {
9525
9526 return (pmap_mapdev_internal(pa, size, PAT_WRITE_BACK,
9527 MAPDEV_FLUSHCACHE));
9528 }
9529
9530 void
pmap_unmapdev(void * p,vm_size_t size)9531 pmap_unmapdev(void *p, vm_size_t size)
9532 {
9533 struct pmap_preinit_mapping *ppim;
9534 vm_offset_t offset, va;
9535 int i;
9536
9537 va = (vm_offset_t)p;
9538
9539 /* If we gave a direct map region in pmap_mapdev, do nothing */
9540 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
9541 return;
9542 offset = va & PAGE_MASK;
9543 size = round_page(offset + size);
9544 va = trunc_page(va);
9545 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
9546 ppim = pmap_preinit_mapping + i;
9547 if (ppim->va == va && ppim->sz == size) {
9548 if (pmap_initialized)
9549 return;
9550 ppim->pa = 0;
9551 ppim->va = 0;
9552 ppim->sz = 0;
9553 ppim->mode = 0;
9554 if (va + size == virtual_avail)
9555 virtual_avail = va;
9556 return;
9557 }
9558 }
9559 if (pmap_initialized) {
9560 pmap_qremove(va, atop(size));
9561 kva_free(va, size);
9562 }
9563 }
9564
9565 /*
9566 * Tries to demote a 1GB page mapping.
9567 */
9568 static bool
pmap_demote_pdpe(pmap_t pmap,pdp_entry_t * pdpe,vm_offset_t va)9569 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
9570 {
9571 pdp_entry_t newpdpe, oldpdpe;
9572 pd_entry_t *firstpde, newpde, *pde;
9573 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
9574 vm_paddr_t pdpgpa;
9575 vm_page_t pdpg;
9576
9577 PG_A = pmap_accessed_bit(pmap);
9578 PG_M = pmap_modified_bit(pmap);
9579 PG_V = pmap_valid_bit(pmap);
9580 PG_RW = pmap_rw_bit(pmap);
9581
9582 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
9583 oldpdpe = *pdpe;
9584 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
9585 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
9586 pdpg = pmap_alloc_pt_page(pmap, va >> PDPSHIFT,
9587 VM_ALLOC_WIRED | VM_ALLOC_INTERRUPT);
9588 if (pdpg == NULL) {
9589 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
9590 " in pmap %p", va, pmap);
9591 return (false);
9592 }
9593 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
9594 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
9595 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
9596 KASSERT((oldpdpe & PG_A) != 0,
9597 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
9598 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
9599 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
9600 newpde = oldpdpe;
9601
9602 /*
9603 * Initialize the page directory page.
9604 */
9605 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
9606 *pde = newpde;
9607 newpde += NBPDR;
9608 }
9609
9610 /*
9611 * Demote the mapping.
9612 */
9613 *pdpe = newpdpe;
9614
9615 /*
9616 * Invalidate a stale recursive mapping of the page directory page.
9617 */
9618 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
9619
9620 counter_u64_add(pmap_pdpe_demotions, 1);
9621 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
9622 " in pmap %p", va, pmap);
9623 return (true);
9624 }
9625
9626 /*
9627 * Sets the memory attribute for the specified page.
9628 */
9629 void
pmap_page_set_memattr(vm_page_t m,vm_memattr_t ma)9630 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
9631 {
9632
9633 m->md.pat_mode = ma;
9634
9635 /*
9636 * If "m" is a normal page, update its direct mapping. This update
9637 * can be relied upon to perform any cache operations that are
9638 * required for data coherence.
9639 */
9640 if ((m->flags & PG_FICTITIOUS) == 0 &&
9641 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
9642 m->md.pat_mode))
9643 panic("memory attribute change on the direct map failed");
9644 }
9645
9646 void
pmap_page_set_memattr_noflush(vm_page_t m,vm_memattr_t ma)9647 pmap_page_set_memattr_noflush(vm_page_t m, vm_memattr_t ma)
9648 {
9649 int error;
9650
9651 m->md.pat_mode = ma;
9652
9653 if ((m->flags & PG_FICTITIOUS) != 0)
9654 return;
9655 PMAP_LOCK(kernel_pmap);
9656 error = pmap_change_props_locked(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)),
9657 PAGE_SIZE, PROT_NONE, m->md.pat_mode, 0);
9658 PMAP_UNLOCK(kernel_pmap);
9659 if (error != 0)
9660 panic("memory attribute change on the direct map failed");
9661 }
9662
9663 /*
9664 * Changes the specified virtual address range's memory type to that given by
9665 * the parameter "mode". The specified virtual address range must be
9666 * completely contained within either the direct map or the kernel map. If
9667 * the virtual address range is contained within the kernel map, then the
9668 * memory type for each of the corresponding ranges of the direct map is also
9669 * changed. (The corresponding ranges of the direct map are those ranges that
9670 * map the same physical pages as the specified virtual address range.) These
9671 * changes to the direct map are necessary because Intel describes the
9672 * behavior of their processors as "undefined" if two or more mappings to the
9673 * same physical page have different memory types.
9674 *
9675 * Returns zero if the change completed successfully, and either EINVAL or
9676 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
9677 * of the virtual address range was not mapped, and ENOMEM is returned if
9678 * there was insufficient memory available to complete the change. In the
9679 * latter case, the memory type may have been changed on some part of the
9680 * virtual address range or the direct map.
9681 */
9682 int
pmap_change_attr(vm_offset_t va,vm_size_t size,int mode)9683 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
9684 {
9685 int error;
9686
9687 PMAP_LOCK(kernel_pmap);
9688 error = pmap_change_props_locked(va, size, PROT_NONE, mode,
9689 MAPDEV_FLUSHCACHE);
9690 PMAP_UNLOCK(kernel_pmap);
9691 return (error);
9692 }
9693
9694 /*
9695 * Changes the specified virtual address range's protections to those
9696 * specified by "prot". Like pmap_change_attr(), protections for aliases
9697 * in the direct map are updated as well. Protections on aliasing mappings may
9698 * be a subset of the requested protections; for example, mappings in the direct
9699 * map are never executable.
9700 */
9701 int
pmap_change_prot(vm_offset_t va,vm_size_t size,vm_prot_t prot)9702 pmap_change_prot(vm_offset_t va, vm_size_t size, vm_prot_t prot)
9703 {
9704 int error;
9705
9706 /* Only supported within the kernel map. */
9707 if (va < VM_MIN_KERNEL_ADDRESS)
9708 return (EINVAL);
9709
9710 PMAP_LOCK(kernel_pmap);
9711 error = pmap_change_props_locked(va, size, prot, -1,
9712 MAPDEV_ASSERTVALID);
9713 PMAP_UNLOCK(kernel_pmap);
9714 return (error);
9715 }
9716
9717 static int
pmap_change_props_locked(vm_offset_t va,vm_size_t size,vm_prot_t prot,int mode,int flags)9718 pmap_change_props_locked(vm_offset_t va, vm_size_t size, vm_prot_t prot,
9719 int mode, int flags)
9720 {
9721 vm_offset_t base, offset, tmpva;
9722 vm_paddr_t pa_start, pa_end, pa_end1;
9723 pdp_entry_t *pdpe;
9724 pd_entry_t *pde, pde_bits, pde_mask;
9725 pt_entry_t *pte, pte_bits, pte_mask;
9726 int error;
9727 bool changed;
9728
9729 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
9730 base = trunc_page(va);
9731 offset = va & PAGE_MASK;
9732 size = round_page(offset + size);
9733
9734 /*
9735 * Only supported on kernel virtual addresses, including the direct
9736 * map but excluding the recursive map.
9737 */
9738 if (base < DMAP_MIN_ADDRESS)
9739 return (EINVAL);
9740
9741 /*
9742 * Construct our flag sets and masks. "bits" is the subset of
9743 * "mask" that will be set in each modified PTE.
9744 *
9745 * Mappings in the direct map are never allowed to be executable.
9746 */
9747 pde_bits = pte_bits = 0;
9748 pde_mask = pte_mask = 0;
9749 if (mode != -1) {
9750 pde_bits |= pmap_cache_bits(kernel_pmap, mode, true);
9751 pde_mask |= X86_PG_PDE_CACHE;
9752 pte_bits |= pmap_cache_bits(kernel_pmap, mode, false);
9753 pte_mask |= X86_PG_PTE_CACHE;
9754 }
9755 if (prot != VM_PROT_NONE) {
9756 if ((prot & VM_PROT_WRITE) != 0) {
9757 pde_bits |= X86_PG_RW;
9758 pte_bits |= X86_PG_RW;
9759 }
9760 if ((prot & VM_PROT_EXECUTE) == 0 ||
9761 va < VM_MIN_KERNEL_ADDRESS) {
9762 pde_bits |= pg_nx;
9763 pte_bits |= pg_nx;
9764 }
9765 pde_mask |= X86_PG_RW | pg_nx;
9766 pte_mask |= X86_PG_RW | pg_nx;
9767 }
9768
9769 /*
9770 * Pages that aren't mapped aren't supported. Also break down 2MB pages
9771 * into 4KB pages if required.
9772 */
9773 for (tmpva = base; tmpva < base + size; ) {
9774 pdpe = pmap_pdpe(kernel_pmap, tmpva);
9775 if (pdpe == NULL || *pdpe == 0) {
9776 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9777 ("%s: addr %#lx is not mapped", __func__, tmpva));
9778 return (EINVAL);
9779 }
9780 if (*pdpe & PG_PS) {
9781 /*
9782 * If the current 1GB page already has the required
9783 * properties, then we need not demote this page. Just
9784 * increment tmpva to the next 1GB page frame.
9785 */
9786 if ((*pdpe & pde_mask) == pde_bits) {
9787 tmpva = trunc_1gpage(tmpva) + NBPDP;
9788 continue;
9789 }
9790
9791 /*
9792 * If the current offset aligns with a 1GB page frame
9793 * and there is at least 1GB left within the range, then
9794 * we need not break down this page into 2MB pages.
9795 */
9796 if ((tmpva & PDPMASK) == 0 &&
9797 tmpva + PDPMASK < base + size) {
9798 tmpva += NBPDP;
9799 continue;
9800 }
9801 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
9802 return (ENOMEM);
9803 }
9804 pde = pmap_pdpe_to_pde(pdpe, tmpva);
9805 if (*pde == 0) {
9806 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9807 ("%s: addr %#lx is not mapped", __func__, tmpva));
9808 return (EINVAL);
9809 }
9810 if (*pde & PG_PS) {
9811 /*
9812 * If the current 2MB page already has the required
9813 * properties, then we need not demote this page. Just
9814 * increment tmpva to the next 2MB page frame.
9815 */
9816 if ((*pde & pde_mask) == pde_bits) {
9817 tmpva = trunc_2mpage(tmpva) + NBPDR;
9818 continue;
9819 }
9820
9821 /*
9822 * If the current offset aligns with a 2MB page frame
9823 * and there is at least 2MB left within the range, then
9824 * we need not break down this page into 4KB pages.
9825 */
9826 if ((tmpva & PDRMASK) == 0 &&
9827 tmpva + PDRMASK < base + size) {
9828 tmpva += NBPDR;
9829 continue;
9830 }
9831 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
9832 return (ENOMEM);
9833 }
9834 pte = pmap_pde_to_pte(pde, tmpva);
9835 if (*pte == 0) {
9836 KASSERT((flags & MAPDEV_ASSERTVALID) == 0,
9837 ("%s: addr %#lx is not mapped", __func__, tmpva));
9838 return (EINVAL);
9839 }
9840 tmpva += PAGE_SIZE;
9841 }
9842 error = 0;
9843
9844 /*
9845 * Ok, all the pages exist, so run through them updating their
9846 * properties if required.
9847 */
9848 changed = false;
9849 pa_start = pa_end = 0;
9850 for (tmpva = base; tmpva < base + size; ) {
9851 pdpe = pmap_pdpe(kernel_pmap, tmpva);
9852 if (*pdpe & PG_PS) {
9853 if ((*pdpe & pde_mask) != pde_bits) {
9854 pmap_pte_props(pdpe, pde_bits, pde_mask);
9855 changed = true;
9856 }
9857 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9858 (*pdpe & PG_PS_FRAME) < dmaplimit) {
9859 if (pa_start == pa_end) {
9860 /* Start physical address run. */
9861 pa_start = *pdpe & PG_PS_FRAME;
9862 pa_end = pa_start + NBPDP;
9863 } else if (pa_end == (*pdpe & PG_PS_FRAME))
9864 pa_end += NBPDP;
9865 else {
9866 /* Run ended, update direct map. */
9867 error = pmap_change_props_locked(
9868 PHYS_TO_DMAP(pa_start),
9869 pa_end - pa_start, prot, mode,
9870 flags);
9871 if (error != 0)
9872 break;
9873 /* Start physical address run. */
9874 pa_start = *pdpe & PG_PS_FRAME;
9875 pa_end = pa_start + NBPDP;
9876 }
9877 }
9878 tmpva = trunc_1gpage(tmpva) + NBPDP;
9879 continue;
9880 }
9881 pde = pmap_pdpe_to_pde(pdpe, tmpva);
9882 if (*pde & PG_PS) {
9883 if ((*pde & pde_mask) != pde_bits) {
9884 pmap_pte_props(pde, pde_bits, pde_mask);
9885 changed = true;
9886 }
9887 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9888 (*pde & PG_PS_FRAME) < dmaplimit) {
9889 if (pa_start == pa_end) {
9890 /* Start physical address run. */
9891 pa_start = *pde & PG_PS_FRAME;
9892 pa_end = pa_start + NBPDR;
9893 } else if (pa_end == (*pde & PG_PS_FRAME))
9894 pa_end += NBPDR;
9895 else {
9896 /* Run ended, update direct map. */
9897 error = pmap_change_props_locked(
9898 PHYS_TO_DMAP(pa_start),
9899 pa_end - pa_start, prot, mode,
9900 flags);
9901 if (error != 0)
9902 break;
9903 /* Start physical address run. */
9904 pa_start = *pde & PG_PS_FRAME;
9905 pa_end = pa_start + NBPDR;
9906 }
9907 }
9908 tmpva = trunc_2mpage(tmpva) + NBPDR;
9909 } else {
9910 pte = pmap_pde_to_pte(pde, tmpva);
9911 if ((*pte & pte_mask) != pte_bits) {
9912 pmap_pte_props(pte, pte_bits, pte_mask);
9913 changed = true;
9914 }
9915 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
9916 (*pte & PG_FRAME) < dmaplimit) {
9917 if (pa_start == pa_end) {
9918 /* Start physical address run. */
9919 pa_start = *pte & PG_FRAME;
9920 pa_end = pa_start + PAGE_SIZE;
9921 } else if (pa_end == (*pte & PG_FRAME))
9922 pa_end += PAGE_SIZE;
9923 else {
9924 /* Run ended, update direct map. */
9925 error = pmap_change_props_locked(
9926 PHYS_TO_DMAP(pa_start),
9927 pa_end - pa_start, prot, mode,
9928 flags);
9929 if (error != 0)
9930 break;
9931 /* Start physical address run. */
9932 pa_start = *pte & PG_FRAME;
9933 pa_end = pa_start + PAGE_SIZE;
9934 }
9935 }
9936 tmpva += PAGE_SIZE;
9937 }
9938 }
9939 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
9940 pa_end1 = MIN(pa_end, dmaplimit);
9941 if (pa_start != pa_end1)
9942 error = pmap_change_props_locked(PHYS_TO_DMAP(pa_start),
9943 pa_end1 - pa_start, prot, mode, flags);
9944 }
9945
9946 /*
9947 * Flush CPU caches if required to make sure any data isn't cached that
9948 * shouldn't be, etc.
9949 */
9950 if (changed) {
9951 pmap_invalidate_range(kernel_pmap, base, tmpva);
9952 if ((flags & MAPDEV_FLUSHCACHE) != 0)
9953 pmap_invalidate_cache_range(base, tmpva);
9954 }
9955 return (error);
9956 }
9957
9958 /*
9959 * Demotes any mapping within the direct map region that covers more than the
9960 * specified range of physical addresses. This range's size must be a power
9961 * of two and its starting address must be a multiple of its size. Since the
9962 * demotion does not change any attributes of the mapping, a TLB invalidation
9963 * is not mandatory. The caller may, however, request a TLB invalidation.
9964 */
9965 void
pmap_demote_DMAP(vm_paddr_t base,vm_size_t len,bool invalidate)9966 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, bool invalidate)
9967 {
9968 pdp_entry_t *pdpe;
9969 pd_entry_t *pde;
9970 vm_offset_t va;
9971 bool changed;
9972
9973 if (len == 0)
9974 return;
9975 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
9976 KASSERT((base & (len - 1)) == 0,
9977 ("pmap_demote_DMAP: base is not a multiple of len"));
9978 if (len < NBPDP && base < dmaplimit) {
9979 va = PHYS_TO_DMAP(base);
9980 changed = false;
9981 PMAP_LOCK(kernel_pmap);
9982 pdpe = pmap_pdpe(kernel_pmap, va);
9983 if ((*pdpe & X86_PG_V) == 0)
9984 panic("pmap_demote_DMAP: invalid PDPE");
9985 if ((*pdpe & PG_PS) != 0) {
9986 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
9987 panic("pmap_demote_DMAP: PDPE failed");
9988 changed = true;
9989 }
9990 if (len < NBPDR) {
9991 pde = pmap_pdpe_to_pde(pdpe, va);
9992 if ((*pde & X86_PG_V) == 0)
9993 panic("pmap_demote_DMAP: invalid PDE");
9994 if ((*pde & PG_PS) != 0) {
9995 if (!pmap_demote_pde(kernel_pmap, pde, va))
9996 panic("pmap_demote_DMAP: PDE failed");
9997 changed = true;
9998 }
9999 }
10000 if (changed && invalidate)
10001 pmap_invalidate_page(kernel_pmap, va);
10002 PMAP_UNLOCK(kernel_pmap);
10003 }
10004 }
10005
10006 /*
10007 * Perform the pmap work for mincore(2). If the page is not both referenced and
10008 * modified by this pmap, returns its physical address so that the caller can
10009 * find other mappings.
10010 */
10011 int
pmap_mincore(pmap_t pmap,vm_offset_t addr,vm_paddr_t * pap)10012 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *pap)
10013 {
10014 pdp_entry_t *pdpe;
10015 pd_entry_t *pdep;
10016 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
10017 vm_paddr_t pa;
10018 int val;
10019
10020 PG_A = pmap_accessed_bit(pmap);
10021 PG_M = pmap_modified_bit(pmap);
10022 PG_V = pmap_valid_bit(pmap);
10023 PG_RW = pmap_rw_bit(pmap);
10024
10025 PMAP_LOCK(pmap);
10026 pte = 0;
10027 pa = 0;
10028 val = 0;
10029 pdpe = pmap_pdpe(pmap, addr);
10030 if (pdpe == NULL)
10031 goto out;
10032 if ((*pdpe & PG_V) != 0) {
10033 if ((*pdpe & PG_PS) != 0) {
10034 pte = *pdpe;
10035 pa = ((pte & PG_PS_PDP_FRAME) | (addr & PDPMASK)) &
10036 PG_FRAME;
10037 val = MINCORE_PSIND(2);
10038 } else {
10039 pdep = pmap_pde(pmap, addr);
10040 if (pdep != NULL && (*pdep & PG_V) != 0) {
10041 if ((*pdep & PG_PS) != 0) {
10042 pte = *pdep;
10043 /* Compute the physical address of the 4KB page. */
10044 pa = ((pte & PG_PS_FRAME) | (addr &
10045 PDRMASK)) & PG_FRAME;
10046 val = MINCORE_PSIND(1);
10047 } else {
10048 pte = *pmap_pde_to_pte(pdep, addr);
10049 pa = pte & PG_FRAME;
10050 val = 0;
10051 }
10052 }
10053 }
10054 }
10055 if ((pte & PG_V) != 0) {
10056 val |= MINCORE_INCORE;
10057 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
10058 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
10059 if ((pte & PG_A) != 0)
10060 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
10061 }
10062 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
10063 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
10064 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
10065 *pap = pa;
10066 }
10067 out:
10068 PMAP_UNLOCK(pmap);
10069 return (val);
10070 }
10071
10072 static uint64_t
pmap_pcid_alloc(pmap_t pmap,struct pmap_pcid * pcidp)10073 pmap_pcid_alloc(pmap_t pmap, struct pmap_pcid *pcidp)
10074 {
10075 uint32_t gen, new_gen, pcid_next;
10076
10077 CRITICAL_ASSERT(curthread);
10078 gen = PCPU_GET(pcid_gen);
10079 if (pcidp->pm_pcid == PMAP_PCID_KERN)
10080 return (pti ? 0 : CR3_PCID_SAVE);
10081 if (pcidp->pm_gen == gen)
10082 return (CR3_PCID_SAVE);
10083 pcid_next = PCPU_GET(pcid_next);
10084 KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
10085 (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
10086 ("cpu %d pcid_next %#x", PCPU_GET(cpuid), pcid_next));
10087 if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
10088 (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
10089 new_gen = gen + 1;
10090 if (new_gen == 0)
10091 new_gen = 1;
10092 PCPU_SET(pcid_gen, new_gen);
10093 pcid_next = PMAP_PCID_KERN + 1;
10094 } else {
10095 new_gen = gen;
10096 }
10097 pcidp->pm_pcid = pcid_next;
10098 pcidp->pm_gen = new_gen;
10099 PCPU_SET(pcid_next, pcid_next + 1);
10100 return (0);
10101 }
10102
10103 static uint64_t
pmap_pcid_alloc_checked(pmap_t pmap,struct pmap_pcid * pcidp)10104 pmap_pcid_alloc_checked(pmap_t pmap, struct pmap_pcid *pcidp)
10105 {
10106 uint64_t cached;
10107
10108 cached = pmap_pcid_alloc(pmap, pcidp);
10109 KASSERT(pcidp->pm_pcid < PMAP_PCID_OVERMAX,
10110 ("pmap %p cpu %d pcid %#x", pmap, PCPU_GET(cpuid), pcidp->pm_pcid));
10111 KASSERT(pcidp->pm_pcid != PMAP_PCID_KERN || pmap == kernel_pmap,
10112 ("non-kernel pmap pmap %p cpu %d pcid %#x",
10113 pmap, PCPU_GET(cpuid), pcidp->pm_pcid));
10114 return (cached);
10115 }
10116
10117 static void
pmap_activate_sw_pti_post(struct thread * td,pmap_t pmap)10118 pmap_activate_sw_pti_post(struct thread *td, pmap_t pmap)
10119 {
10120
10121 PCPU_GET(tssp)->tss_rsp0 = pmap->pm_ucr3 != PMAP_NO_CR3 ?
10122 PCPU_GET(pti_rsp0) : (uintptr_t)td->td_md.md_stack_base;
10123 }
10124
10125 static void
pmap_activate_sw_pcid_pti(struct thread * td,pmap_t pmap,u_int cpuid)10126 pmap_activate_sw_pcid_pti(struct thread *td, pmap_t pmap, u_int cpuid)
10127 {
10128 pmap_t old_pmap;
10129 struct pmap_pcid *pcidp, *old_pcidp;
10130 uint64_t cached, cr3, kcr3, ucr3;
10131
10132 KASSERT((read_rflags() & PSL_I) == 0,
10133 ("PCID needs interrupts disabled in pmap_activate_sw()"));
10134
10135 /* See the comment in pmap_invalidate_page_pcid(). */
10136 if (PCPU_GET(ucr3_load_mask) != PMAP_UCR3_NOMASK) {
10137 PCPU_SET(ucr3_load_mask, PMAP_UCR3_NOMASK);
10138 old_pmap = PCPU_GET(curpmap);
10139 MPASS(old_pmap->pm_ucr3 != PMAP_NO_CR3);
10140 old_pcidp = zpcpu_get_cpu(old_pmap->pm_pcidp, cpuid);
10141 old_pcidp->pm_gen = 0;
10142 }
10143
10144 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, cpuid);
10145 cached = pmap_pcid_alloc_checked(pmap, pcidp);
10146 cr3 = rcr3();
10147 if ((cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3)
10148 load_cr3(pmap->pm_cr3 | pcidp->pm_pcid);
10149 PCPU_SET(curpmap, pmap);
10150 kcr3 = pmap->pm_cr3 | pcidp->pm_pcid;
10151 ucr3 = pmap->pm_ucr3 | pcidp->pm_pcid | PMAP_PCID_USER_PT;
10152
10153 if (!cached && pmap->pm_ucr3 != PMAP_NO_CR3)
10154 PCPU_SET(ucr3_load_mask, ~CR3_PCID_SAVE);
10155
10156 PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
10157 PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
10158 if (cached)
10159 counter_u64_add(pcid_save_cnt, 1);
10160
10161 pmap_activate_sw_pti_post(td, pmap);
10162 }
10163
10164 static void
pmap_activate_sw_pcid_nopti(struct thread * td __unused,pmap_t pmap,u_int cpuid)10165 pmap_activate_sw_pcid_nopti(struct thread *td __unused, pmap_t pmap,
10166 u_int cpuid)
10167 {
10168 struct pmap_pcid *pcidp;
10169 uint64_t cached, cr3;
10170
10171 KASSERT((read_rflags() & PSL_I) == 0,
10172 ("PCID needs interrupts disabled in pmap_activate_sw()"));
10173
10174 pcidp = zpcpu_get_cpu(pmap->pm_pcidp, cpuid);
10175 cached = pmap_pcid_alloc_checked(pmap, pcidp);
10176 cr3 = rcr3();
10177 if (!cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3)
10178 load_cr3(pmap->pm_cr3 | pcidp->pm_pcid | cached);
10179 PCPU_SET(curpmap, pmap);
10180 if (cached)
10181 counter_u64_add(pcid_save_cnt, 1);
10182 }
10183
10184 static void
pmap_activate_sw_nopcid_nopti(struct thread * td __unused,pmap_t pmap,u_int cpuid __unused)10185 pmap_activate_sw_nopcid_nopti(struct thread *td __unused, pmap_t pmap,
10186 u_int cpuid __unused)
10187 {
10188
10189 load_cr3(pmap->pm_cr3);
10190 PCPU_SET(curpmap, pmap);
10191 }
10192
10193 static void
pmap_activate_sw_nopcid_pti(struct thread * td,pmap_t pmap,u_int cpuid __unused)10194 pmap_activate_sw_nopcid_pti(struct thread *td, pmap_t pmap,
10195 u_int cpuid __unused)
10196 {
10197
10198 pmap_activate_sw_nopcid_nopti(td, pmap, cpuid);
10199 PCPU_SET(kcr3, pmap->pm_cr3);
10200 PCPU_SET(ucr3, pmap->pm_ucr3);
10201 pmap_activate_sw_pti_post(td, pmap);
10202 }
10203
10204 DEFINE_IFUNC(static, void, pmap_activate_sw_mode, (struct thread *, pmap_t,
10205 u_int))
10206 {
10207
10208 if (pmap_pcid_enabled && pti)
10209 return (pmap_activate_sw_pcid_pti);
10210 else if (pmap_pcid_enabled && !pti)
10211 return (pmap_activate_sw_pcid_nopti);
10212 else if (!pmap_pcid_enabled && pti)
10213 return (pmap_activate_sw_nopcid_pti);
10214 else /* if (!pmap_pcid_enabled && !pti) */
10215 return (pmap_activate_sw_nopcid_nopti);
10216 }
10217
10218 void
pmap_activate_sw(struct thread * td)10219 pmap_activate_sw(struct thread *td)
10220 {
10221 pmap_t oldpmap, pmap;
10222 u_int cpuid;
10223
10224 oldpmap = PCPU_GET(curpmap);
10225 pmap = vmspace_pmap(td->td_proc->p_vmspace);
10226 if (oldpmap == pmap) {
10227 if (cpu_vendor_id != CPU_VENDOR_INTEL)
10228 mfence();
10229 return;
10230 }
10231 cpuid = PCPU_GET(cpuid);
10232 #ifdef SMP
10233 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
10234 #else
10235 CPU_SET(cpuid, &pmap->pm_active);
10236 #endif
10237 pmap_activate_sw_mode(td, pmap, cpuid);
10238 #ifdef SMP
10239 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
10240 #else
10241 CPU_CLR(cpuid, &oldpmap->pm_active);
10242 #endif
10243 }
10244
10245 void
pmap_activate(struct thread * td)10246 pmap_activate(struct thread *td)
10247 {
10248 /*
10249 * invltlb_{invpcid,}_pcid_handler() is used to handle an
10250 * invalidate_all IPI, which checks for curpmap ==
10251 * smp_tlb_pmap. The below sequence of operations has a
10252 * window where %CR3 is loaded with the new pmap's PML4
10253 * address, but the curpmap value has not yet been updated.
10254 * This causes the invltlb IPI handler, which is called
10255 * between the updates, to execute as a NOP, which leaves
10256 * stale TLB entries.
10257 *
10258 * Note that the most common use of pmap_activate_sw(), from
10259 * a context switch, is immune to this race, because
10260 * interrupts are disabled (while the thread lock is owned),
10261 * so the IPI is delayed until after curpmap is updated. Protect
10262 * other callers in a similar way, by disabling interrupts
10263 * around the %cr3 register reload and curpmap assignment.
10264 */
10265 spinlock_enter();
10266 pmap_activate_sw(td);
10267 spinlock_exit();
10268 }
10269
10270 void
pmap_activate_boot(pmap_t pmap)10271 pmap_activate_boot(pmap_t pmap)
10272 {
10273 uint64_t kcr3;
10274 u_int cpuid;
10275
10276 /*
10277 * kernel_pmap must be never deactivated, and we ensure that
10278 * by never activating it at all.
10279 */
10280 MPASS(pmap != kernel_pmap);
10281
10282 cpuid = PCPU_GET(cpuid);
10283 #ifdef SMP
10284 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
10285 #else
10286 CPU_SET(cpuid, &pmap->pm_active);
10287 #endif
10288 PCPU_SET(curpmap, pmap);
10289 if (pti) {
10290 kcr3 = pmap->pm_cr3;
10291 if (pmap_pcid_enabled)
10292 kcr3 |= pmap_get_pcid(pmap) | CR3_PCID_SAVE;
10293 } else {
10294 kcr3 = PMAP_NO_CR3;
10295 }
10296 PCPU_SET(kcr3, kcr3);
10297 PCPU_SET(ucr3, PMAP_NO_CR3);
10298 }
10299
10300 void
pmap_active_cpus(pmap_t pmap,cpuset_t * res)10301 pmap_active_cpus(pmap_t pmap, cpuset_t *res)
10302 {
10303 *res = pmap->pm_active;
10304 }
10305
10306 void
pmap_sync_icache(pmap_t pm,vm_offset_t va,vm_size_t sz)10307 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
10308 {
10309 }
10310
10311 /*
10312 * Increase the starting virtual address of the given mapping if a
10313 * different alignment might result in more superpage mappings.
10314 */
10315 void
pmap_align_superpage(vm_object_t object,vm_ooffset_t offset,vm_offset_t * addr,vm_size_t size)10316 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
10317 vm_offset_t *addr, vm_size_t size)
10318 {
10319 vm_offset_t superpage_offset;
10320
10321 if (size < NBPDR)
10322 return;
10323 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
10324 offset += ptoa(object->pg_color);
10325 superpage_offset = offset & PDRMASK;
10326 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
10327 (*addr & PDRMASK) == superpage_offset)
10328 return;
10329 if ((*addr & PDRMASK) < superpage_offset)
10330 *addr = (*addr & ~PDRMASK) + superpage_offset;
10331 else
10332 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
10333 }
10334
10335 #ifdef INVARIANTS
10336 static unsigned long num_dirty_emulations;
10337 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
10338 &num_dirty_emulations, 0, NULL);
10339
10340 static unsigned long num_accessed_emulations;
10341 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
10342 &num_accessed_emulations, 0, NULL);
10343
10344 static unsigned long num_superpage_accessed_emulations;
10345 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
10346 &num_superpage_accessed_emulations, 0, NULL);
10347
10348 static unsigned long ad_emulation_superpage_promotions;
10349 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
10350 &ad_emulation_superpage_promotions, 0, NULL);
10351 #endif /* INVARIANTS */
10352
10353 int
pmap_emulate_accessed_dirty(pmap_t pmap,vm_offset_t va,int ftype)10354 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
10355 {
10356 int rv;
10357 struct rwlock *lock;
10358 #if VM_NRESERVLEVEL > 0
10359 vm_page_t m, mpte;
10360 #endif
10361 pd_entry_t *pde;
10362 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
10363
10364 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
10365 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
10366
10367 if (!pmap_emulate_ad_bits(pmap))
10368 return (-1);
10369
10370 PG_A = pmap_accessed_bit(pmap);
10371 PG_M = pmap_modified_bit(pmap);
10372 PG_V = pmap_valid_bit(pmap);
10373 PG_RW = pmap_rw_bit(pmap);
10374
10375 rv = -1;
10376 lock = NULL;
10377 PMAP_LOCK(pmap);
10378
10379 pde = pmap_pde(pmap, va);
10380 if (pde == NULL || (*pde & PG_V) == 0)
10381 goto done;
10382
10383 if ((*pde & PG_PS) != 0) {
10384 if (ftype == VM_PROT_READ) {
10385 #ifdef INVARIANTS
10386 atomic_add_long(&num_superpage_accessed_emulations, 1);
10387 #endif
10388 *pde |= PG_A;
10389 rv = 0;
10390 }
10391 goto done;
10392 }
10393
10394 pte = pmap_pde_to_pte(pde, va);
10395 if ((*pte & PG_V) == 0)
10396 goto done;
10397
10398 if (ftype == VM_PROT_WRITE) {
10399 if ((*pte & PG_RW) == 0)
10400 goto done;
10401 /*
10402 * Set the modified and accessed bits simultaneously.
10403 *
10404 * Intel EPT PTEs that do software emulation of A/D bits map
10405 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
10406 * An EPT misconfiguration is triggered if the PTE is writable
10407 * but not readable (WR=10). This is avoided by setting PG_A
10408 * and PG_M simultaneously.
10409 */
10410 *pte |= PG_M | PG_A;
10411 } else {
10412 *pte |= PG_A;
10413 }
10414
10415 #if VM_NRESERVLEVEL > 0
10416 /* try to promote the mapping */
10417 if (va < VM_MAXUSER_ADDRESS)
10418 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
10419 else
10420 mpte = NULL;
10421
10422 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
10423
10424 if ((mpte == NULL || mpte->ref_count == NPTEPG) &&
10425 (m->flags & PG_FICTITIOUS) == 0 &&
10426 vm_reserv_level_iffullpop(m) == 0 &&
10427 pmap_promote_pde(pmap, pde, va, mpte, &lock)) {
10428 #ifdef INVARIANTS
10429 atomic_add_long(&ad_emulation_superpage_promotions, 1);
10430 #endif
10431 }
10432 #endif
10433
10434 #ifdef INVARIANTS
10435 if (ftype == VM_PROT_WRITE)
10436 atomic_add_long(&num_dirty_emulations, 1);
10437 else
10438 atomic_add_long(&num_accessed_emulations, 1);
10439 #endif
10440 rv = 0; /* success */
10441 done:
10442 if (lock != NULL)
10443 rw_wunlock(lock);
10444 PMAP_UNLOCK(pmap);
10445 return (rv);
10446 }
10447
10448 void
pmap_get_mapping(pmap_t pmap,vm_offset_t va,uint64_t * ptr,int * num)10449 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
10450 {
10451 pml4_entry_t *pml4;
10452 pdp_entry_t *pdp;
10453 pd_entry_t *pde;
10454 pt_entry_t *pte, PG_V;
10455 int idx;
10456
10457 idx = 0;
10458 PG_V = pmap_valid_bit(pmap);
10459 PMAP_LOCK(pmap);
10460
10461 pml4 = pmap_pml4e(pmap, va);
10462 if (pml4 == NULL)
10463 goto done;
10464 ptr[idx++] = *pml4;
10465 if ((*pml4 & PG_V) == 0)
10466 goto done;
10467
10468 pdp = pmap_pml4e_to_pdpe(pml4, va);
10469 ptr[idx++] = *pdp;
10470 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
10471 goto done;
10472
10473 pde = pmap_pdpe_to_pde(pdp, va);
10474 ptr[idx++] = *pde;
10475 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
10476 goto done;
10477
10478 pte = pmap_pde_to_pte(pde, va);
10479 ptr[idx++] = *pte;
10480
10481 done:
10482 PMAP_UNLOCK(pmap);
10483 *num = idx;
10484 }
10485
10486 /**
10487 * Get the kernel virtual address of a set of physical pages. If there are
10488 * physical addresses not covered by the DMAP perform a transient mapping
10489 * that will be removed when calling pmap_unmap_io_transient.
10490 *
10491 * \param page The pages the caller wishes to obtain the virtual
10492 * address on the kernel memory map.
10493 * \param vaddr On return contains the kernel virtual memory address
10494 * of the pages passed in the page parameter.
10495 * \param count Number of pages passed in.
10496 * \param can_fault true if the thread using the mapped pages can take
10497 * page faults, false otherwise.
10498 *
10499 * \returns true if the caller must call pmap_unmap_io_transient when
10500 * finished or false otherwise.
10501 *
10502 */
10503 bool
pmap_map_io_transient(vm_page_t page[],vm_offset_t vaddr[],int count,bool can_fault)10504 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
10505 bool can_fault)
10506 {
10507 vm_paddr_t paddr;
10508 bool needs_mapping;
10509 pt_entry_t *pte;
10510 int cache_bits, error __unused, i;
10511
10512 /*
10513 * Allocate any KVA space that we need, this is done in a separate
10514 * loop to prevent calling vmem_alloc while pinned.
10515 */
10516 needs_mapping = false;
10517 for (i = 0; i < count; i++) {
10518 paddr = VM_PAGE_TO_PHYS(page[i]);
10519 if (__predict_false(paddr >= dmaplimit)) {
10520 error = vmem_alloc(kernel_arena, PAGE_SIZE,
10521 M_BESTFIT | M_WAITOK, &vaddr[i]);
10522 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
10523 needs_mapping = true;
10524 } else {
10525 vaddr[i] = PHYS_TO_DMAP(paddr);
10526 }
10527 }
10528
10529 /* Exit early if everything is covered by the DMAP */
10530 if (!needs_mapping)
10531 return (false);
10532
10533 /*
10534 * NB: The sequence of updating a page table followed by accesses
10535 * to the corresponding pages used in the !DMAP case is subject to
10536 * the situation described in the "AMD64 Architecture Programmer's
10537 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
10538 * Coherency Considerations". Therefore, issuing the INVLPG right
10539 * after modifying the PTE bits is crucial.
10540 */
10541 if (!can_fault)
10542 sched_pin();
10543 for (i = 0; i < count; i++) {
10544 paddr = VM_PAGE_TO_PHYS(page[i]);
10545 if (paddr >= dmaplimit) {
10546 if (can_fault) {
10547 /*
10548 * Slow path, since we can get page faults
10549 * while mappings are active don't pin the
10550 * thread to the CPU and instead add a global
10551 * mapping visible to all CPUs.
10552 */
10553 pmap_qenter(vaddr[i], &page[i], 1);
10554 } else {
10555 pte = vtopte(vaddr[i]);
10556 cache_bits = pmap_cache_bits(kernel_pmap,
10557 page[i]->md.pat_mode, false);
10558 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
10559 cache_bits);
10560 pmap_invlpg(kernel_pmap, vaddr[i]);
10561 }
10562 }
10563 }
10564
10565 return (needs_mapping);
10566 }
10567
10568 void
pmap_unmap_io_transient(vm_page_t page[],vm_offset_t vaddr[],int count,bool can_fault)10569 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
10570 bool can_fault)
10571 {
10572 vm_paddr_t paddr;
10573 int i;
10574
10575 if (!can_fault)
10576 sched_unpin();
10577 for (i = 0; i < count; i++) {
10578 paddr = VM_PAGE_TO_PHYS(page[i]);
10579 if (paddr >= dmaplimit) {
10580 if (can_fault)
10581 pmap_qremove(vaddr[i], 1);
10582 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
10583 }
10584 }
10585 }
10586
10587 vm_offset_t
pmap_quick_enter_page(vm_page_t m)10588 pmap_quick_enter_page(vm_page_t m)
10589 {
10590 vm_paddr_t paddr;
10591
10592 paddr = VM_PAGE_TO_PHYS(m);
10593 if (paddr < dmaplimit)
10594 return (PHYS_TO_DMAP(paddr));
10595 mtx_lock_spin(&qframe_mtx);
10596 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
10597
10598 /*
10599 * Since qframe is exclusively mapped by us, and we do not set
10600 * PG_G, we can use INVLPG here.
10601 */
10602 invlpg(qframe);
10603
10604 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
10605 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, false));
10606 return (qframe);
10607 }
10608
10609 void
pmap_quick_remove_page(vm_offset_t addr)10610 pmap_quick_remove_page(vm_offset_t addr)
10611 {
10612
10613 if (addr != qframe)
10614 return;
10615 pte_store(vtopte(qframe), 0);
10616 mtx_unlock_spin(&qframe_mtx);
10617 }
10618
10619 /*
10620 * Pdp pages from the large map are managed differently from either
10621 * kernel or user page table pages. They are permanently allocated at
10622 * initialization time, and their reference count is permanently set to
10623 * zero. The pml4 entries pointing to those pages are copied into
10624 * each allocated pmap.
10625 *
10626 * In contrast, pd and pt pages are managed like user page table
10627 * pages. They are dynamically allocated, and their reference count
10628 * represents the number of valid entries within the page.
10629 */
10630 static vm_page_t
pmap_large_map_getptp_unlocked(void)10631 pmap_large_map_getptp_unlocked(void)
10632 {
10633 return (pmap_alloc_pt_page(kernel_pmap, 0, VM_ALLOC_ZERO));
10634 }
10635
10636 static vm_page_t
pmap_large_map_getptp(void)10637 pmap_large_map_getptp(void)
10638 {
10639 vm_page_t m;
10640
10641 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
10642 m = pmap_large_map_getptp_unlocked();
10643 if (m == NULL) {
10644 PMAP_UNLOCK(kernel_pmap);
10645 vm_wait(NULL);
10646 PMAP_LOCK(kernel_pmap);
10647 /* Callers retry. */
10648 }
10649 return (m);
10650 }
10651
10652 static pdp_entry_t *
pmap_large_map_pdpe(vm_offset_t va)10653 pmap_large_map_pdpe(vm_offset_t va)
10654 {
10655 vm_pindex_t pml4_idx;
10656 vm_paddr_t mphys;
10657
10658 pml4_idx = pmap_pml4e_index(va);
10659 KASSERT(LMSPML4I <= pml4_idx && pml4_idx < LMSPML4I + lm_ents,
10660 ("pmap_large_map_pdpe: va %#jx out of range idx %#jx LMSPML4I "
10661 "%#jx lm_ents %d",
10662 (uintmax_t)va, (uintmax_t)pml4_idx, LMSPML4I, lm_ents));
10663 KASSERT((kernel_pml4[pml4_idx] & X86_PG_V) != 0,
10664 ("pmap_large_map_pdpe: invalid pml4 for va %#jx idx %#jx "
10665 "LMSPML4I %#jx lm_ents %d",
10666 (uintmax_t)va, (uintmax_t)pml4_idx, LMSPML4I, lm_ents));
10667 mphys = kernel_pml4[pml4_idx] & PG_FRAME;
10668 return ((pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va));
10669 }
10670
10671 static pd_entry_t *
pmap_large_map_pde(vm_offset_t va)10672 pmap_large_map_pde(vm_offset_t va)
10673 {
10674 pdp_entry_t *pdpe;
10675 vm_page_t m;
10676 vm_paddr_t mphys;
10677
10678 retry:
10679 pdpe = pmap_large_map_pdpe(va);
10680 if (*pdpe == 0) {
10681 m = pmap_large_map_getptp();
10682 if (m == NULL)
10683 goto retry;
10684 mphys = VM_PAGE_TO_PHYS(m);
10685 *pdpe = mphys | X86_PG_A | X86_PG_RW | X86_PG_V | pg_nx;
10686 } else {
10687 MPASS((*pdpe & X86_PG_PS) == 0);
10688 mphys = *pdpe & PG_FRAME;
10689 }
10690 return ((pd_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pde_index(va));
10691 }
10692
10693 static pt_entry_t *
pmap_large_map_pte(vm_offset_t va)10694 pmap_large_map_pte(vm_offset_t va)
10695 {
10696 pd_entry_t *pde;
10697 vm_page_t m;
10698 vm_paddr_t mphys;
10699
10700 retry:
10701 pde = pmap_large_map_pde(va);
10702 if (*pde == 0) {
10703 m = pmap_large_map_getptp();
10704 if (m == NULL)
10705 goto retry;
10706 mphys = VM_PAGE_TO_PHYS(m);
10707 *pde = mphys | X86_PG_A | X86_PG_RW | X86_PG_V | pg_nx;
10708 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde))->ref_count++;
10709 } else {
10710 MPASS((*pde & X86_PG_PS) == 0);
10711 mphys = *pde & PG_FRAME;
10712 }
10713 return ((pt_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pte_index(va));
10714 }
10715
10716 static vm_paddr_t
pmap_large_map_kextract(vm_offset_t va)10717 pmap_large_map_kextract(vm_offset_t va)
10718 {
10719 pdp_entry_t *pdpe, pdp;
10720 pd_entry_t *pde, pd;
10721 pt_entry_t *pte, pt;
10722
10723 KASSERT(PMAP_ADDRESS_IN_LARGEMAP(va),
10724 ("not largemap range %#lx", (u_long)va));
10725 pdpe = pmap_large_map_pdpe(va);
10726 pdp = *pdpe;
10727 KASSERT((pdp & X86_PG_V) != 0,
10728 ("invalid pdp va %#lx pdpe %#lx pdp %#lx", va,
10729 (u_long)pdpe, pdp));
10730 if ((pdp & X86_PG_PS) != 0) {
10731 KASSERT((amd_feature & AMDID_PAGE1GB) != 0,
10732 ("no 1G pages, va %#lx pdpe %#lx pdp %#lx", va,
10733 (u_long)pdpe, pdp));
10734 return ((pdp & PG_PS_PDP_FRAME) | (va & PDPMASK));
10735 }
10736 pde = pmap_pdpe_to_pde(pdpe, va);
10737 pd = *pde;
10738 KASSERT((pd & X86_PG_V) != 0,
10739 ("invalid pd va %#lx pde %#lx pd %#lx", va, (u_long)pde, pd));
10740 if ((pd & X86_PG_PS) != 0)
10741 return ((pd & PG_PS_FRAME) | (va & PDRMASK));
10742 pte = pmap_pde_to_pte(pde, va);
10743 pt = *pte;
10744 KASSERT((pt & X86_PG_V) != 0,
10745 ("invalid pte va %#lx pte %#lx pt %#lx", va, (u_long)pte, pt));
10746 return ((pt & PG_FRAME) | (va & PAGE_MASK));
10747 }
10748
10749 static int
pmap_large_map_getva(vm_size_t len,vm_offset_t align,vm_offset_t phase,vmem_addr_t * vmem_res)10750 pmap_large_map_getva(vm_size_t len, vm_offset_t align, vm_offset_t phase,
10751 vmem_addr_t *vmem_res)
10752 {
10753
10754 /*
10755 * Large mappings are all but static. Consequently, there
10756 * is no point in waiting for an earlier allocation to be
10757 * freed.
10758 */
10759 return (vmem_xalloc(large_vmem, len, align, phase, 0, VMEM_ADDR_MIN,
10760 VMEM_ADDR_MAX, M_NOWAIT | M_BESTFIT, vmem_res));
10761 }
10762
10763 int
pmap_large_map(vm_paddr_t spa,vm_size_t len,void ** addr,vm_memattr_t mattr)10764 pmap_large_map(vm_paddr_t spa, vm_size_t len, void **addr,
10765 vm_memattr_t mattr)
10766 {
10767 pdp_entry_t *pdpe;
10768 pd_entry_t *pde;
10769 pt_entry_t *pte;
10770 vm_offset_t va, inc;
10771 vmem_addr_t vmem_res;
10772 vm_paddr_t pa;
10773 int error;
10774
10775 if (len == 0 || spa + len < spa)
10776 return (EINVAL);
10777
10778 /* See if DMAP can serve. */
10779 if (spa + len <= dmaplimit) {
10780 va = PHYS_TO_DMAP(spa);
10781 *addr = (void *)va;
10782 return (pmap_change_attr(va, len, mattr));
10783 }
10784
10785 /*
10786 * No, allocate KVA. Fit the address with best possible
10787 * alignment for superpages. Fall back to worse align if
10788 * failed.
10789 */
10790 error = ENOMEM;
10791 if ((amd_feature & AMDID_PAGE1GB) != 0 && rounddown2(spa + len,
10792 NBPDP) >= roundup2(spa, NBPDP) + NBPDP)
10793 error = pmap_large_map_getva(len, NBPDP, spa & PDPMASK,
10794 &vmem_res);
10795 if (error != 0 && rounddown2(spa + len, NBPDR) >= roundup2(spa,
10796 NBPDR) + NBPDR)
10797 error = pmap_large_map_getva(len, NBPDR, spa & PDRMASK,
10798 &vmem_res);
10799 if (error != 0)
10800 error = pmap_large_map_getva(len, PAGE_SIZE, 0, &vmem_res);
10801 if (error != 0)
10802 return (error);
10803
10804 /*
10805 * Fill pagetable. PG_M is not pre-set, we scan modified bits
10806 * in the pagetable to minimize flushing. No need to
10807 * invalidate TLB, since we only update invalid entries.
10808 */
10809 PMAP_LOCK(kernel_pmap);
10810 for (pa = spa, va = vmem_res; len > 0; pa += inc, va += inc,
10811 len -= inc) {
10812 if ((amd_feature & AMDID_PAGE1GB) != 0 && len >= NBPDP &&
10813 (pa & PDPMASK) == 0 && (va & PDPMASK) == 0) {
10814 pdpe = pmap_large_map_pdpe(va);
10815 MPASS(*pdpe == 0);
10816 *pdpe = pa | pg_g | X86_PG_PS | X86_PG_RW |
10817 X86_PG_V | X86_PG_A | pg_nx |
10818 pmap_cache_bits(kernel_pmap, mattr, true);
10819 inc = NBPDP;
10820 } else if (len >= NBPDR && (pa & PDRMASK) == 0 &&
10821 (va & PDRMASK) == 0) {
10822 pde = pmap_large_map_pde(va);
10823 MPASS(*pde == 0);
10824 *pde = pa | pg_g | X86_PG_PS | X86_PG_RW |
10825 X86_PG_V | X86_PG_A | pg_nx |
10826 pmap_cache_bits(kernel_pmap, mattr, true);
10827 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde))->
10828 ref_count++;
10829 inc = NBPDR;
10830 } else {
10831 pte = pmap_large_map_pte(va);
10832 MPASS(*pte == 0);
10833 *pte = pa | pg_g | X86_PG_RW | X86_PG_V |
10834 X86_PG_A | pg_nx | pmap_cache_bits(kernel_pmap,
10835 mattr, false);
10836 PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte))->
10837 ref_count++;
10838 inc = PAGE_SIZE;
10839 }
10840 }
10841 PMAP_UNLOCK(kernel_pmap);
10842 MPASS(len == 0);
10843
10844 *addr = (void *)vmem_res;
10845 return (0);
10846 }
10847
10848 void
pmap_large_unmap(void * svaa,vm_size_t len)10849 pmap_large_unmap(void *svaa, vm_size_t len)
10850 {
10851 vm_offset_t sva, va;
10852 vm_size_t inc;
10853 pdp_entry_t *pdpe, pdp;
10854 pd_entry_t *pde, pd;
10855 pt_entry_t *pte;
10856 vm_page_t m;
10857 struct spglist spgf;
10858
10859 sva = (vm_offset_t)svaa;
10860 if (len == 0 || sva + len < sva || (sva >= DMAP_MIN_ADDRESS &&
10861 sva + len <= DMAP_MIN_ADDRESS + dmaplimit))
10862 return;
10863
10864 SLIST_INIT(&spgf);
10865 KASSERT(PMAP_ADDRESS_IN_LARGEMAP(sva) &&
10866 PMAP_ADDRESS_IN_LARGEMAP(sva + len - 1),
10867 ("not largemap range %#lx %#lx", (u_long)svaa, (u_long)svaa + len));
10868 PMAP_LOCK(kernel_pmap);
10869 for (va = sva; va < sva + len; va += inc) {
10870 pdpe = pmap_large_map_pdpe(va);
10871 pdp = *pdpe;
10872 KASSERT((pdp & X86_PG_V) != 0,
10873 ("invalid pdp va %#lx pdpe %#lx pdp %#lx", va,
10874 (u_long)pdpe, pdp));
10875 if ((pdp & X86_PG_PS) != 0) {
10876 KASSERT((amd_feature & AMDID_PAGE1GB) != 0,
10877 ("no 1G pages, va %#lx pdpe %#lx pdp %#lx", va,
10878 (u_long)pdpe, pdp));
10879 KASSERT((va & PDPMASK) == 0,
10880 ("PDPMASK bit set, va %#lx pdpe %#lx pdp %#lx", va,
10881 (u_long)pdpe, pdp));
10882 KASSERT(va + NBPDP <= sva + len,
10883 ("unmap covers partial 1GB page, sva %#lx va %#lx "
10884 "pdpe %#lx pdp %#lx len %#lx", sva, va,
10885 (u_long)pdpe, pdp, len));
10886 *pdpe = 0;
10887 inc = NBPDP;
10888 continue;
10889 }
10890 pde = pmap_pdpe_to_pde(pdpe, va);
10891 pd = *pde;
10892 KASSERT((pd & X86_PG_V) != 0,
10893 ("invalid pd va %#lx pde %#lx pd %#lx", va,
10894 (u_long)pde, pd));
10895 if ((pd & X86_PG_PS) != 0) {
10896 KASSERT((va & PDRMASK) == 0,
10897 ("PDRMASK bit set, va %#lx pde %#lx pd %#lx", va,
10898 (u_long)pde, pd));
10899 KASSERT(va + NBPDR <= sva + len,
10900 ("unmap covers partial 2MB page, sva %#lx va %#lx "
10901 "pde %#lx pd %#lx len %#lx", sva, va, (u_long)pde,
10902 pd, len));
10903 pde_store(pde, 0);
10904 inc = NBPDR;
10905 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pde));
10906 m->ref_count--;
10907 if (m->ref_count == 0) {
10908 *pdpe = 0;
10909 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10910 }
10911 continue;
10912 }
10913 pte = pmap_pde_to_pte(pde, va);
10914 KASSERT((*pte & X86_PG_V) != 0,
10915 ("invalid pte va %#lx pte %#lx pt %#lx", va,
10916 (u_long)pte, *pte));
10917 pte_clear(pte);
10918 inc = PAGE_SIZE;
10919 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pte));
10920 m->ref_count--;
10921 if (m->ref_count == 0) {
10922 *pde = 0;
10923 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10924 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pde));
10925 m->ref_count--;
10926 if (m->ref_count == 0) {
10927 *pdpe = 0;
10928 SLIST_INSERT_HEAD(&spgf, m, plinks.s.ss);
10929 }
10930 }
10931 }
10932 pmap_invalidate_range(kernel_pmap, sva, sva + len);
10933 PMAP_UNLOCK(kernel_pmap);
10934 vm_page_free_pages_toq(&spgf, false);
10935 vmem_free(large_vmem, sva, len);
10936 }
10937
10938 static void
pmap_large_map_wb_fence_mfence(void)10939 pmap_large_map_wb_fence_mfence(void)
10940 {
10941
10942 mfence();
10943 }
10944
10945 static void
pmap_large_map_wb_fence_atomic(void)10946 pmap_large_map_wb_fence_atomic(void)
10947 {
10948
10949 atomic_thread_fence_seq_cst();
10950 }
10951
10952 static void
pmap_large_map_wb_fence_nop(void)10953 pmap_large_map_wb_fence_nop(void)
10954 {
10955 }
10956
10957 DEFINE_IFUNC(static, void, pmap_large_map_wb_fence, (void))
10958 {
10959
10960 if (cpu_vendor_id != CPU_VENDOR_INTEL)
10961 return (pmap_large_map_wb_fence_mfence);
10962 else if ((cpu_stdext_feature & (CPUID_STDEXT_CLWB |
10963 CPUID_STDEXT_CLFLUSHOPT)) == 0)
10964 return (pmap_large_map_wb_fence_atomic);
10965 else
10966 /* clflush is strongly enough ordered */
10967 return (pmap_large_map_wb_fence_nop);
10968 }
10969
10970 static void
pmap_large_map_flush_range_clwb(vm_offset_t va,vm_size_t len)10971 pmap_large_map_flush_range_clwb(vm_offset_t va, vm_size_t len)
10972 {
10973
10974 for (; len > 0; len -= cpu_clflush_line_size,
10975 va += cpu_clflush_line_size)
10976 clwb(va);
10977 }
10978
10979 static void
pmap_large_map_flush_range_clflushopt(vm_offset_t va,vm_size_t len)10980 pmap_large_map_flush_range_clflushopt(vm_offset_t va, vm_size_t len)
10981 {
10982
10983 for (; len > 0; len -= cpu_clflush_line_size,
10984 va += cpu_clflush_line_size)
10985 clflushopt(va);
10986 }
10987
10988 static void
pmap_large_map_flush_range_clflush(vm_offset_t va,vm_size_t len)10989 pmap_large_map_flush_range_clflush(vm_offset_t va, vm_size_t len)
10990 {
10991
10992 for (; len > 0; len -= cpu_clflush_line_size,
10993 va += cpu_clflush_line_size)
10994 clflush(va);
10995 }
10996
10997 static void
pmap_large_map_flush_range_nop(vm_offset_t sva __unused,vm_size_t len __unused)10998 pmap_large_map_flush_range_nop(vm_offset_t sva __unused, vm_size_t len __unused)
10999 {
11000 }
11001
11002 DEFINE_IFUNC(static, void, pmap_large_map_flush_range, (vm_offset_t, vm_size_t))
11003 {
11004
11005 if ((cpu_stdext_feature & CPUID_STDEXT_CLWB) != 0)
11006 return (pmap_large_map_flush_range_clwb);
11007 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0)
11008 return (pmap_large_map_flush_range_clflushopt);
11009 else if ((cpu_feature & CPUID_CLFSH) != 0)
11010 return (pmap_large_map_flush_range_clflush);
11011 else
11012 return (pmap_large_map_flush_range_nop);
11013 }
11014
11015 static void
pmap_large_map_wb_large(vm_offset_t sva,vm_offset_t eva)11016 pmap_large_map_wb_large(vm_offset_t sva, vm_offset_t eva)
11017 {
11018 volatile u_long *pe;
11019 u_long p;
11020 vm_offset_t va;
11021 vm_size_t inc;
11022 bool seen_other;
11023
11024 for (va = sva; va < eva; va += inc) {
11025 inc = 0;
11026 if ((amd_feature & AMDID_PAGE1GB) != 0) {
11027 pe = (volatile u_long *)pmap_large_map_pdpe(va);
11028 p = *pe;
11029 if ((p & X86_PG_PS) != 0)
11030 inc = NBPDP;
11031 }
11032 if (inc == 0) {
11033 pe = (volatile u_long *)pmap_large_map_pde(va);
11034 p = *pe;
11035 if ((p & X86_PG_PS) != 0)
11036 inc = NBPDR;
11037 }
11038 if (inc == 0) {
11039 pe = (volatile u_long *)pmap_large_map_pte(va);
11040 p = *pe;
11041 inc = PAGE_SIZE;
11042 }
11043 seen_other = false;
11044 for (;;) {
11045 if ((p & X86_PG_AVAIL1) != 0) {
11046 /*
11047 * Spin-wait for the end of a parallel
11048 * write-back.
11049 */
11050 cpu_spinwait();
11051 p = *pe;
11052
11053 /*
11054 * If we saw other write-back
11055 * occurring, we cannot rely on PG_M to
11056 * indicate state of the cache. The
11057 * PG_M bit is cleared before the
11058 * flush to avoid ignoring new writes,
11059 * and writes which are relevant for
11060 * us might happen after.
11061 */
11062 seen_other = true;
11063 continue;
11064 }
11065
11066 if ((p & X86_PG_M) != 0 || seen_other) {
11067 if (!atomic_fcmpset_long(pe, &p,
11068 (p & ~X86_PG_M) | X86_PG_AVAIL1))
11069 /*
11070 * If we saw PG_M without
11071 * PG_AVAIL1, and then on the
11072 * next attempt we do not
11073 * observe either PG_M or
11074 * PG_AVAIL1, the other
11075 * write-back started after us
11076 * and finished before us. We
11077 * can rely on it doing our
11078 * work.
11079 */
11080 continue;
11081 pmap_large_map_flush_range(va, inc);
11082 atomic_clear_long(pe, X86_PG_AVAIL1);
11083 }
11084 break;
11085 }
11086 maybe_yield();
11087 }
11088 }
11089
11090 /*
11091 * Write-back cache lines for the given address range.
11092 *
11093 * Must be called only on the range or sub-range returned from
11094 * pmap_large_map(). Must not be called on the coalesced ranges.
11095 *
11096 * Does nothing on CPUs without CLWB, CLFLUSHOPT, or CLFLUSH
11097 * instructions support.
11098 */
11099 void
pmap_large_map_wb(void * svap,vm_size_t len)11100 pmap_large_map_wb(void *svap, vm_size_t len)
11101 {
11102 vm_offset_t eva, sva;
11103
11104 sva = (vm_offset_t)svap;
11105 eva = sva + len;
11106 pmap_large_map_wb_fence();
11107 if (sva >= DMAP_MIN_ADDRESS && eva <= DMAP_MIN_ADDRESS + dmaplimit) {
11108 pmap_large_map_flush_range(sva, len);
11109 } else {
11110 KASSERT(sva >= LARGEMAP_MIN_ADDRESS &&
11111 eva <= LARGEMAP_MIN_ADDRESS + lm_ents * NBPML4,
11112 ("pmap_large_map_wb: not largemap %#lx %#lx", sva, len));
11113 pmap_large_map_wb_large(sva, eva);
11114 }
11115 pmap_large_map_wb_fence();
11116 }
11117
11118 static vm_page_t
pmap_pti_alloc_page(void)11119 pmap_pti_alloc_page(void)
11120 {
11121 vm_page_t m;
11122
11123 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11124 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_WIRED | VM_ALLOC_ZERO);
11125 return (m);
11126 }
11127
11128 static bool
pmap_pti_free_page(vm_page_t m)11129 pmap_pti_free_page(vm_page_t m)
11130 {
11131 if (!vm_page_unwire_noq(m))
11132 return (false);
11133 vm_page_xbusy_claim(m);
11134 vm_page_free_zero(m);
11135 return (true);
11136 }
11137
11138 static void
pmap_pti_init(void)11139 pmap_pti_init(void)
11140 {
11141 vm_page_t pml4_pg;
11142 pdp_entry_t *pdpe;
11143 vm_offset_t va;
11144 int i;
11145
11146 if (!pti)
11147 return;
11148 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
11149 VM_OBJECT_WLOCK(pti_obj);
11150 pml4_pg = pmap_pti_alloc_page();
11151 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
11152 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
11153 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
11154 pdpe = pmap_pti_pdpe(va);
11155 pmap_pti_wire_pte(pdpe);
11156 }
11157 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
11158 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
11159 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
11160 sizeof(struct gate_descriptor) * NIDT, false);
11161 CPU_FOREACH(i) {
11162 /* Doublefault stack IST 1 */
11163 va = __pcpu[i].pc_common_tss.tss_ist1 + sizeof(struct nmi_pcpu);
11164 pmap_pti_add_kva_locked(va - DBLFAULT_STACK_SIZE, va, false);
11165 /* NMI stack IST 2 */
11166 va = __pcpu[i].pc_common_tss.tss_ist2 + sizeof(struct nmi_pcpu);
11167 pmap_pti_add_kva_locked(va - NMI_STACK_SIZE, va, false);
11168 /* MC# stack IST 3 */
11169 va = __pcpu[i].pc_common_tss.tss_ist3 +
11170 sizeof(struct nmi_pcpu);
11171 pmap_pti_add_kva_locked(va - MCE_STACK_SIZE, va, false);
11172 /* DB# stack IST 4 */
11173 va = __pcpu[i].pc_common_tss.tss_ist4 + sizeof(struct nmi_pcpu);
11174 pmap_pti_add_kva_locked(va - DBG_STACK_SIZE, va, false);
11175 }
11176 pmap_pti_add_kva_locked((vm_offset_t)KERNSTART, (vm_offset_t)etext,
11177 true);
11178 pti_finalized = true;
11179 VM_OBJECT_WUNLOCK(pti_obj);
11180 }
11181
11182 static void
pmap_cpu_init(void * arg __unused)11183 pmap_cpu_init(void *arg __unused)
11184 {
11185 CPU_COPY(&all_cpus, &kernel_pmap->pm_active);
11186 pmap_pti_init();
11187 }
11188 SYSINIT(pmap_cpu, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_cpu_init, NULL);
11189
11190 static pdp_entry_t *
pmap_pti_pdpe(vm_offset_t va)11191 pmap_pti_pdpe(vm_offset_t va)
11192 {
11193 pml4_entry_t *pml4e;
11194 pdp_entry_t *pdpe;
11195 vm_page_t m;
11196 vm_pindex_t pml4_idx;
11197 vm_paddr_t mphys;
11198
11199 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11200
11201 pml4_idx = pmap_pml4e_index(va);
11202 pml4e = &pti_pml4[pml4_idx];
11203 m = NULL;
11204 if (*pml4e == 0) {
11205 if (pti_finalized)
11206 panic("pml4 alloc after finalization\n");
11207 m = pmap_pti_alloc_page();
11208 if (*pml4e != 0) {
11209 pmap_pti_free_page(m);
11210 mphys = *pml4e & ~PAGE_MASK;
11211 } else {
11212 mphys = VM_PAGE_TO_PHYS(m);
11213 *pml4e = mphys | X86_PG_RW | X86_PG_V;
11214 }
11215 } else {
11216 mphys = *pml4e & ~PAGE_MASK;
11217 }
11218 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
11219 return (pdpe);
11220 }
11221
11222 static void
pmap_pti_wire_pte(void * pte)11223 pmap_pti_wire_pte(void *pte)
11224 {
11225 vm_page_t m;
11226
11227 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11228 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
11229 m->ref_count++;
11230 }
11231
11232 static void
pmap_pti_unwire_pde(void * pde,bool only_ref)11233 pmap_pti_unwire_pde(void *pde, bool only_ref)
11234 {
11235 vm_page_t m;
11236
11237 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11238 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
11239 MPASS(only_ref || m->ref_count > 1);
11240 pmap_pti_free_page(m);
11241 }
11242
11243 static void
pmap_pti_unwire_pte(void * pte,vm_offset_t va)11244 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
11245 {
11246 vm_page_t m;
11247 pd_entry_t *pde;
11248
11249 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11250 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
11251 if (pmap_pti_free_page(m)) {
11252 pde = pmap_pti_pde(va);
11253 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
11254 *pde = 0;
11255 pmap_pti_unwire_pde(pde, false);
11256 }
11257 }
11258
11259 static pd_entry_t *
pmap_pti_pde(vm_offset_t va)11260 pmap_pti_pde(vm_offset_t va)
11261 {
11262 pdp_entry_t *pdpe;
11263 pd_entry_t *pde;
11264 vm_page_t m;
11265 vm_pindex_t pd_idx;
11266 vm_paddr_t mphys;
11267
11268 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11269
11270 pdpe = pmap_pti_pdpe(va);
11271 if (*pdpe == 0) {
11272 m = pmap_pti_alloc_page();
11273 if (*pdpe != 0) {
11274 pmap_pti_free_page(m);
11275 MPASS((*pdpe & X86_PG_PS) == 0);
11276 mphys = *pdpe & ~PAGE_MASK;
11277 } else {
11278 mphys = VM_PAGE_TO_PHYS(m);
11279 *pdpe = mphys | X86_PG_RW | X86_PG_V;
11280 }
11281 } else {
11282 MPASS((*pdpe & X86_PG_PS) == 0);
11283 mphys = *pdpe & ~PAGE_MASK;
11284 }
11285
11286 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
11287 pd_idx = pmap_pde_index(va);
11288 pde += pd_idx;
11289 return (pde);
11290 }
11291
11292 static pt_entry_t *
pmap_pti_pte(vm_offset_t va,bool * unwire_pde)11293 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
11294 {
11295 pd_entry_t *pde;
11296 pt_entry_t *pte;
11297 vm_page_t m;
11298 vm_paddr_t mphys;
11299
11300 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11301
11302 pde = pmap_pti_pde(va);
11303 if (unwire_pde != NULL) {
11304 *unwire_pde = true;
11305 pmap_pti_wire_pte(pde);
11306 }
11307 if (*pde == 0) {
11308 m = pmap_pti_alloc_page();
11309 if (*pde != 0) {
11310 pmap_pti_free_page(m);
11311 MPASS((*pde & X86_PG_PS) == 0);
11312 mphys = *pde & ~(PAGE_MASK | pg_nx);
11313 } else {
11314 mphys = VM_PAGE_TO_PHYS(m);
11315 *pde = mphys | X86_PG_RW | X86_PG_V;
11316 if (unwire_pde != NULL)
11317 *unwire_pde = false;
11318 }
11319 } else {
11320 MPASS((*pde & X86_PG_PS) == 0);
11321 mphys = *pde & ~(PAGE_MASK | pg_nx);
11322 }
11323
11324 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
11325 pte += pmap_pte_index(va);
11326
11327 return (pte);
11328 }
11329
11330 static void
pmap_pti_add_kva_locked(vm_offset_t sva,vm_offset_t eva,bool exec)11331 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
11332 {
11333 vm_paddr_t pa;
11334 pd_entry_t *pde;
11335 pt_entry_t *pte, ptev;
11336 bool unwire_pde;
11337
11338 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
11339
11340 sva = trunc_page(sva);
11341 MPASS(sva > VM_MAXUSER_ADDRESS);
11342 eva = round_page(eva);
11343 MPASS(sva < eva);
11344 for (; sva < eva; sva += PAGE_SIZE) {
11345 pte = pmap_pti_pte(sva, &unwire_pde);
11346 pa = pmap_kextract(sva);
11347 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A | X86_PG_G |
11348 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
11349 VM_MEMATTR_DEFAULT, false);
11350 if (*pte == 0) {
11351 pte_store(pte, ptev);
11352 pmap_pti_wire_pte(pte);
11353 } else {
11354 KASSERT(!pti_finalized,
11355 ("pti overlap after fin %#lx %#lx %#lx",
11356 sva, *pte, ptev));
11357 KASSERT(*pte == ptev,
11358 ("pti non-identical pte after fin %#lx %#lx %#lx",
11359 sva, *pte, ptev));
11360 }
11361 if (unwire_pde) {
11362 pde = pmap_pti_pde(sva);
11363 pmap_pti_unwire_pde(pde, true);
11364 }
11365 }
11366 }
11367
11368 void
pmap_pti_add_kva(vm_offset_t sva,vm_offset_t eva,bool exec)11369 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
11370 {
11371
11372 if (!pti)
11373 return;
11374 VM_OBJECT_WLOCK(pti_obj);
11375 pmap_pti_add_kva_locked(sva, eva, exec);
11376 VM_OBJECT_WUNLOCK(pti_obj);
11377 }
11378
11379 void
pmap_pti_remove_kva(vm_offset_t sva,vm_offset_t eva)11380 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
11381 {
11382 pt_entry_t *pte;
11383 vm_offset_t va;
11384
11385 if (!pti)
11386 return;
11387 sva = rounddown2(sva, PAGE_SIZE);
11388 MPASS(sva > VM_MAXUSER_ADDRESS);
11389 eva = roundup2(eva, PAGE_SIZE);
11390 MPASS(sva < eva);
11391 VM_OBJECT_WLOCK(pti_obj);
11392 for (va = sva; va < eva; va += PAGE_SIZE) {
11393 pte = pmap_pti_pte(va, NULL);
11394 KASSERT((*pte & X86_PG_V) != 0,
11395 ("invalid pte va %#lx pte %#lx pt %#lx", va,
11396 (u_long)pte, *pte));
11397 pte_clear(pte);
11398 pmap_pti_unwire_pte(pte, va);
11399 }
11400 pmap_invalidate_range(kernel_pmap, sva, eva);
11401 VM_OBJECT_WUNLOCK(pti_obj);
11402 }
11403
11404 static void *
pkru_dup_range(void * ctx __unused,void * data)11405 pkru_dup_range(void *ctx __unused, void *data)
11406 {
11407 struct pmap_pkru_range *node, *new_node;
11408
11409 new_node = uma_zalloc(pmap_pkru_ranges_zone, M_NOWAIT);
11410 if (new_node == NULL)
11411 return (NULL);
11412 node = data;
11413 memcpy(new_node, node, sizeof(*node));
11414 return (new_node);
11415 }
11416
11417 static void
pkru_free_range(void * ctx __unused,void * node)11418 pkru_free_range(void *ctx __unused, void *node)
11419 {
11420
11421 uma_zfree(pmap_pkru_ranges_zone, node);
11422 }
11423
11424 static int
pmap_pkru_assign(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,u_int keyidx,int flags)11425 pmap_pkru_assign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, u_int keyidx,
11426 int flags)
11427 {
11428 struct pmap_pkru_range *ppr;
11429 int error;
11430
11431 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11432 MPASS(pmap->pm_type == PT_X86);
11433 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11434 if ((flags & AMD64_PKRU_EXCL) != 0 &&
11435 !rangeset_check_empty(&pmap->pm_pkru, sva, eva))
11436 return (EBUSY);
11437 ppr = uma_zalloc(pmap_pkru_ranges_zone, M_NOWAIT);
11438 if (ppr == NULL)
11439 return (ENOMEM);
11440 ppr->pkru_keyidx = keyidx;
11441 ppr->pkru_flags = flags & AMD64_PKRU_PERSIST;
11442 error = rangeset_insert(&pmap->pm_pkru, sva, eva, ppr);
11443 if (error != 0)
11444 uma_zfree(pmap_pkru_ranges_zone, ppr);
11445 return (error);
11446 }
11447
11448 static int
pmap_pkru_deassign(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)11449 pmap_pkru_deassign(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11450 {
11451
11452 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11453 MPASS(pmap->pm_type == PT_X86);
11454 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11455 return (rangeset_remove(&pmap->pm_pkru, sva, eva));
11456 }
11457
11458 static void
pmap_pkru_deassign_all(pmap_t pmap)11459 pmap_pkru_deassign_all(pmap_t pmap)
11460 {
11461
11462 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11463 if (pmap->pm_type == PT_X86 &&
11464 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0)
11465 rangeset_remove_all(&pmap->pm_pkru);
11466 }
11467
11468 /*
11469 * Returns true if the PKU setting is the same across the specified address
11470 * range, and false otherwise. When returning true, updates the referenced PTE
11471 * to reflect the PKU setting.
11472 */
11473 static bool
pmap_pkru_same(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,pt_entry_t * pte)11474 pmap_pkru_same(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, pt_entry_t *pte)
11475 {
11476 struct pmap_pkru_range *ppr;
11477 vm_offset_t va;
11478 u_int keyidx;
11479
11480 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11481 KASSERT(pmap->pm_type != PT_X86 || (*pte & X86_PG_PKU_MASK) == 0,
11482 ("pte %p has unexpected PKU %ld", pte, *pte & X86_PG_PKU_MASK));
11483 if (pmap->pm_type != PT_X86 ||
11484 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0 ||
11485 sva >= VM_MAXUSER_ADDRESS)
11486 return (true);
11487 MPASS(eva <= VM_MAXUSER_ADDRESS);
11488 ppr = rangeset_containing(&pmap->pm_pkru, sva);
11489 if (ppr == NULL)
11490 return (rangeset_empty(&pmap->pm_pkru, sva, eva));
11491 keyidx = ppr->pkru_keyidx;
11492 while ((va = ppr->pkru_rs_el.re_end) < eva) {
11493 if ((ppr = rangeset_beginning(&pmap->pm_pkru, va)) == NULL ||
11494 keyidx != ppr->pkru_keyidx)
11495 return (false);
11496 }
11497 *pte |= X86_PG_PKU(keyidx);
11498 return (true);
11499 }
11500
11501 static pt_entry_t
pmap_pkru_get(pmap_t pmap,vm_offset_t va)11502 pmap_pkru_get(pmap_t pmap, vm_offset_t va)
11503 {
11504 struct pmap_pkru_range *ppr;
11505
11506 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11507 if (pmap->pm_type != PT_X86 ||
11508 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0 ||
11509 va >= VM_MAXUSER_ADDRESS)
11510 return (0);
11511 ppr = rangeset_containing(&pmap->pm_pkru, va);
11512 if (ppr != NULL)
11513 return (X86_PG_PKU(ppr->pkru_keyidx));
11514 return (0);
11515 }
11516
11517 static bool
pred_pkru_on_remove(void * ctx __unused,void * r)11518 pred_pkru_on_remove(void *ctx __unused, void *r)
11519 {
11520 struct pmap_pkru_range *ppr;
11521
11522 ppr = r;
11523 return ((ppr->pkru_flags & AMD64_PKRU_PERSIST) == 0);
11524 }
11525
11526 static void
pmap_pkru_on_remove(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)11527 pmap_pkru_on_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11528 {
11529
11530 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11531 if (pmap->pm_type == PT_X86 &&
11532 (cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0) {
11533 rangeset_remove_pred(&pmap->pm_pkru, sva, eva,
11534 pred_pkru_on_remove);
11535 }
11536 }
11537
11538 static int
pmap_pkru_copy(pmap_t dst_pmap,pmap_t src_pmap)11539 pmap_pkru_copy(pmap_t dst_pmap, pmap_t src_pmap)
11540 {
11541
11542 PMAP_LOCK_ASSERT(dst_pmap, MA_OWNED);
11543 PMAP_LOCK_ASSERT(src_pmap, MA_OWNED);
11544 MPASS(dst_pmap->pm_type == PT_X86);
11545 MPASS(src_pmap->pm_type == PT_X86);
11546 MPASS((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) != 0);
11547 if (src_pmap->pm_pkru.rs_data_ctx == NULL)
11548 return (0);
11549 return (rangeset_copy(&dst_pmap->pm_pkru, &src_pmap->pm_pkru));
11550 }
11551
11552 static void
pmap_pkru_update_range(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,u_int keyidx)11553 pmap_pkru_update_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
11554 u_int keyidx)
11555 {
11556 pml4_entry_t *pml4e;
11557 pdp_entry_t *pdpe;
11558 pd_entry_t newpde, ptpaddr, *pde;
11559 pt_entry_t newpte, *ptep, pte;
11560 vm_offset_t va, va_next;
11561 bool changed;
11562
11563 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
11564 MPASS(pmap->pm_type == PT_X86);
11565 MPASS(keyidx <= PMAP_MAX_PKRU_IDX);
11566
11567 for (changed = false, va = sva; va < eva; va = va_next) {
11568 pml4e = pmap_pml4e(pmap, va);
11569 if (pml4e == NULL || (*pml4e & X86_PG_V) == 0) {
11570 va_next = (va + NBPML4) & ~PML4MASK;
11571 if (va_next < va)
11572 va_next = eva;
11573 continue;
11574 }
11575
11576 pdpe = pmap_pml4e_to_pdpe(pml4e, va);
11577 if ((*pdpe & X86_PG_V) == 0) {
11578 va_next = (va + NBPDP) & ~PDPMASK;
11579 if (va_next < va)
11580 va_next = eva;
11581 continue;
11582 }
11583
11584 va_next = (va + NBPDR) & ~PDRMASK;
11585 if (va_next < va)
11586 va_next = eva;
11587
11588 pde = pmap_pdpe_to_pde(pdpe, va);
11589 ptpaddr = *pde;
11590 if (ptpaddr == 0)
11591 continue;
11592
11593 MPASS((ptpaddr & X86_PG_V) != 0);
11594 if ((ptpaddr & PG_PS) != 0) {
11595 if (va + NBPDR == va_next && eva >= va_next) {
11596 newpde = (ptpaddr & ~X86_PG_PKU_MASK) |
11597 X86_PG_PKU(keyidx);
11598 if (newpde != ptpaddr) {
11599 *pde = newpde;
11600 changed = true;
11601 }
11602 continue;
11603 } else if (!pmap_demote_pde(pmap, pde, va)) {
11604 continue;
11605 }
11606 }
11607
11608 if (va_next > eva)
11609 va_next = eva;
11610
11611 for (ptep = pmap_pde_to_pte(pde, va); va != va_next;
11612 ptep++, va += PAGE_SIZE) {
11613 pte = *ptep;
11614 if ((pte & X86_PG_V) == 0)
11615 continue;
11616 newpte = (pte & ~X86_PG_PKU_MASK) | X86_PG_PKU(keyidx);
11617 if (newpte != pte) {
11618 *ptep = newpte;
11619 changed = true;
11620 }
11621 }
11622 }
11623 if (changed)
11624 pmap_invalidate_range(pmap, sva, eva);
11625 }
11626
11627 static int
pmap_pkru_check_uargs(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,u_int keyidx,int flags)11628 pmap_pkru_check_uargs(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
11629 u_int keyidx, int flags)
11630 {
11631
11632 if (pmap->pm_type != PT_X86 || keyidx > PMAP_MAX_PKRU_IDX ||
11633 (flags & ~(AMD64_PKRU_PERSIST | AMD64_PKRU_EXCL)) != 0)
11634 return (EINVAL);
11635 if (eva <= sva || eva > VM_MAXUSER_ADDRESS)
11636 return (EFAULT);
11637 if ((cpu_stdext_feature2 & CPUID_STDEXT2_PKU) == 0)
11638 return (ENOTSUP);
11639 return (0);
11640 }
11641
11642 int
pmap_pkru_set(pmap_t pmap,vm_offset_t sva,vm_offset_t eva,u_int keyidx,int flags)11643 pmap_pkru_set(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, u_int keyidx,
11644 int flags)
11645 {
11646 int error;
11647
11648 sva = trunc_page(sva);
11649 eva = round_page(eva);
11650 error = pmap_pkru_check_uargs(pmap, sva, eva, keyidx, flags);
11651 if (error != 0)
11652 return (error);
11653 for (;;) {
11654 PMAP_LOCK(pmap);
11655 error = pmap_pkru_assign(pmap, sva, eva, keyidx, flags);
11656 if (error == 0)
11657 pmap_pkru_update_range(pmap, sva, eva, keyidx);
11658 PMAP_UNLOCK(pmap);
11659 if (error != ENOMEM)
11660 break;
11661 vm_wait(NULL);
11662 }
11663 return (error);
11664 }
11665
11666 int
pmap_pkru_clear(pmap_t pmap,vm_offset_t sva,vm_offset_t eva)11667 pmap_pkru_clear(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
11668 {
11669 int error;
11670
11671 sva = trunc_page(sva);
11672 eva = round_page(eva);
11673 error = pmap_pkru_check_uargs(pmap, sva, eva, 0, 0);
11674 if (error != 0)
11675 return (error);
11676 for (;;) {
11677 PMAP_LOCK(pmap);
11678 error = pmap_pkru_deassign(pmap, sva, eva);
11679 if (error == 0)
11680 pmap_pkru_update_range(pmap, sva, eva, 0);
11681 PMAP_UNLOCK(pmap);
11682 if (error != ENOMEM)
11683 break;
11684 vm_wait(NULL);
11685 }
11686 return (error);
11687 }
11688
11689 #if defined(KASAN) || defined(KMSAN)
11690
11691 /*
11692 * Reserve enough memory to:
11693 * 1) allocate PDP pages for the shadow map(s),
11694 * 2) shadow the boot stack of KSTACK_PAGES pages,
11695 * 3) assuming that the kernel stack does not cross a 1GB boundary,
11696 * so we need one or two PD pages, one or two PT pages, and KSTACK_PAGES shadow
11697 * pages per shadow map.
11698 */
11699 #ifdef KASAN
11700 #define SAN_EARLY_PAGES \
11701 (NKASANPML4E + 2 + 2 + howmany(KSTACK_PAGES, KASAN_SHADOW_SCALE))
11702 #else
11703 #define SAN_EARLY_PAGES \
11704 (NKMSANSHADPML4E + NKMSANORIGPML4E + 2 * (2 + 2 + KSTACK_PAGES))
11705 #endif
11706
11707 static uint64_t __nosanitizeaddress __nosanitizememory
pmap_san_enter_early_alloc_4k(uint64_t pabase)11708 pmap_san_enter_early_alloc_4k(uint64_t pabase)
11709 {
11710 static uint8_t data[PAGE_SIZE * SAN_EARLY_PAGES] __aligned(PAGE_SIZE);
11711 static size_t offset = 0;
11712 uint64_t pa;
11713
11714 if (offset == sizeof(data)) {
11715 panic("%s: ran out of memory for the bootstrap shadow map",
11716 __func__);
11717 }
11718
11719 pa = pabase + ((vm_offset_t)&data[offset] - KERNSTART);
11720 offset += PAGE_SIZE;
11721 return (pa);
11722 }
11723
11724 /*
11725 * Map a shadow page, before the kernel has bootstrapped its page tables. This
11726 * is currently only used to shadow the temporary boot stack set up by locore.
11727 */
11728 static void __nosanitizeaddress __nosanitizememory
pmap_san_enter_early(vm_offset_t va)11729 pmap_san_enter_early(vm_offset_t va)
11730 {
11731 static bool first = true;
11732 pml4_entry_t *pml4e;
11733 pdp_entry_t *pdpe;
11734 pd_entry_t *pde;
11735 pt_entry_t *pte;
11736 uint64_t cr3, pa, base;
11737 int i;
11738
11739 base = amd64_loadaddr();
11740 cr3 = rcr3();
11741
11742 if (first) {
11743 /*
11744 * If this the first call, we need to allocate new PML4Es for
11745 * the bootstrap shadow map(s). We don't know how the PML4 page
11746 * was initialized by the boot loader, so we can't simply test
11747 * whether the shadow map's PML4Es are zero.
11748 */
11749 first = false;
11750 #ifdef KASAN
11751 for (i = 0; i < NKASANPML4E; i++) {
11752 pa = pmap_san_enter_early_alloc_4k(base);
11753
11754 pml4e = (pml4_entry_t *)cr3 +
11755 pmap_pml4e_index(KASAN_MIN_ADDRESS + i * NBPML4);
11756 *pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11757 }
11758 #else
11759 for (i = 0; i < NKMSANORIGPML4E; i++) {
11760 pa = pmap_san_enter_early_alloc_4k(base);
11761
11762 pml4e = (pml4_entry_t *)cr3 +
11763 pmap_pml4e_index(KMSAN_ORIG_MIN_ADDRESS +
11764 i * NBPML4);
11765 *pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11766 }
11767 for (i = 0; i < NKMSANSHADPML4E; i++) {
11768 pa = pmap_san_enter_early_alloc_4k(base);
11769
11770 pml4e = (pml4_entry_t *)cr3 +
11771 pmap_pml4e_index(KMSAN_SHAD_MIN_ADDRESS +
11772 i * NBPML4);
11773 *pml4e = (pml4_entry_t)(pa | X86_PG_RW | X86_PG_V);
11774 }
11775 #endif
11776 }
11777 pml4e = (pml4_entry_t *)cr3 + pmap_pml4e_index(va);
11778 pdpe = (pdp_entry_t *)(*pml4e & PG_FRAME) + pmap_pdpe_index(va);
11779 if (*pdpe == 0) {
11780 pa = pmap_san_enter_early_alloc_4k(base);
11781 *pdpe = (pdp_entry_t)(pa | X86_PG_RW | X86_PG_V);
11782 }
11783 pde = (pd_entry_t *)(*pdpe & PG_FRAME) + pmap_pde_index(va);
11784 if (*pde == 0) {
11785 pa = pmap_san_enter_early_alloc_4k(base);
11786 *pde = (pd_entry_t)(pa | X86_PG_RW | X86_PG_V);
11787 }
11788 pte = (pt_entry_t *)(*pde & PG_FRAME) + pmap_pte_index(va);
11789 if (*pte != 0)
11790 panic("%s: PTE for %#lx is already initialized", __func__, va);
11791 pa = pmap_san_enter_early_alloc_4k(base);
11792 *pte = (pt_entry_t)(pa | X86_PG_A | X86_PG_M | X86_PG_RW | X86_PG_V);
11793 }
11794
11795 static vm_page_t
pmap_san_enter_alloc_4k(void)11796 pmap_san_enter_alloc_4k(void)
11797 {
11798 vm_page_t m;
11799
11800 m = vm_page_alloc_noobj(VM_ALLOC_INTERRUPT | VM_ALLOC_WIRED |
11801 VM_ALLOC_ZERO);
11802 if (m == NULL)
11803 panic("%s: no memory to grow shadow map", __func__);
11804 return (m);
11805 }
11806
11807 static vm_page_t
pmap_san_enter_alloc_2m(void)11808 pmap_san_enter_alloc_2m(void)
11809 {
11810 return (vm_page_alloc_noobj_contig(VM_ALLOC_WIRED | VM_ALLOC_ZERO,
11811 NPTEPG, 0, ~0ul, NBPDR, 0, VM_MEMATTR_DEFAULT));
11812 }
11813
11814 /*
11815 * Grow a shadow map by at least one 4KB page at the specified address. Use 2MB
11816 * pages when possible.
11817 */
11818 void __nosanitizeaddress __nosanitizememory
pmap_san_enter(vm_offset_t va)11819 pmap_san_enter(vm_offset_t va)
11820 {
11821 pdp_entry_t *pdpe;
11822 pd_entry_t *pde;
11823 pt_entry_t *pte;
11824 vm_page_t m;
11825
11826 if (kernphys == 0) {
11827 /*
11828 * We're creating a temporary shadow map for the boot stack.
11829 */
11830 pmap_san_enter_early(va);
11831 return;
11832 }
11833
11834 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
11835
11836 pdpe = pmap_pdpe(kernel_pmap, va);
11837 if ((*pdpe & X86_PG_V) == 0) {
11838 m = pmap_san_enter_alloc_4k();
11839 *pdpe = (pdp_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11840 X86_PG_V | pg_nx);
11841 }
11842 pde = pmap_pdpe_to_pde(pdpe, va);
11843 if ((*pde & X86_PG_V) == 0) {
11844 m = pmap_san_enter_alloc_2m();
11845 if (m != NULL) {
11846 *pde = (pd_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11847 X86_PG_PS | X86_PG_V | X86_PG_A | X86_PG_M | pg_nx);
11848 } else {
11849 m = pmap_san_enter_alloc_4k();
11850 *pde = (pd_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW |
11851 X86_PG_V | pg_nx);
11852 }
11853 }
11854 if ((*pde & X86_PG_PS) != 0)
11855 return;
11856 pte = pmap_pde_to_pte(pde, va);
11857 if ((*pte & X86_PG_V) != 0)
11858 return;
11859 m = pmap_san_enter_alloc_4k();
11860 *pte = (pt_entry_t)(VM_PAGE_TO_PHYS(m) | X86_PG_RW | X86_PG_V |
11861 X86_PG_M | X86_PG_A | pg_nx);
11862 }
11863 #endif
11864
11865 /*
11866 * Track a range of the kernel's virtual address space that is contiguous
11867 * in various mapping attributes.
11868 */
11869 struct pmap_kernel_map_range {
11870 vm_offset_t sva;
11871 pt_entry_t attrs;
11872 int ptes;
11873 int pdes;
11874 int pdpes;
11875 };
11876
11877 static void
sysctl_kmaps_dump(struct sbuf * sb,struct pmap_kernel_map_range * range,vm_offset_t eva)11878 sysctl_kmaps_dump(struct sbuf *sb, struct pmap_kernel_map_range *range,
11879 vm_offset_t eva)
11880 {
11881 const char *mode;
11882 int i, pat_idx;
11883
11884 if (eva <= range->sva)
11885 return;
11886
11887 pat_idx = pmap_pat_index(kernel_pmap, range->attrs, true);
11888 for (i = 0; i < PAT_INDEX_SIZE; i++)
11889 if (pat_index[i] == pat_idx)
11890 break;
11891
11892 switch (i) {
11893 case PAT_WRITE_BACK:
11894 mode = "WB";
11895 break;
11896 case PAT_WRITE_THROUGH:
11897 mode = "WT";
11898 break;
11899 case PAT_UNCACHEABLE:
11900 mode = "UC";
11901 break;
11902 case PAT_UNCACHED:
11903 mode = "U-";
11904 break;
11905 case PAT_WRITE_PROTECTED:
11906 mode = "WP";
11907 break;
11908 case PAT_WRITE_COMBINING:
11909 mode = "WC";
11910 break;
11911 default:
11912 printf("%s: unknown PAT mode %#x for range 0x%016lx-0x%016lx\n",
11913 __func__, pat_idx, range->sva, eva);
11914 mode = "??";
11915 break;
11916 }
11917
11918 sbuf_printf(sb, "0x%016lx-0x%016lx r%c%c%c%c %s %d %d %d\n",
11919 range->sva, eva,
11920 (range->attrs & X86_PG_RW) != 0 ? 'w' : '-',
11921 (range->attrs & pg_nx) != 0 ? '-' : 'x',
11922 (range->attrs & X86_PG_U) != 0 ? 'u' : 's',
11923 (range->attrs & X86_PG_G) != 0 ? 'g' : '-',
11924 mode, range->pdpes, range->pdes, range->ptes);
11925
11926 /* Reset to sentinel value. */
11927 range->sva = la57 ? KV5ADDR(NPML5EPG - 1, NPML4EPG - 1, NPDPEPG - 1,
11928 NPDEPG - 1, NPTEPG - 1) : KV4ADDR(NPML4EPG - 1, NPDPEPG - 1,
11929 NPDEPG - 1, NPTEPG - 1);
11930 }
11931
11932 /*
11933 * Determine whether the attributes specified by a page table entry match those
11934 * being tracked by the current range. This is not quite as simple as a direct
11935 * flag comparison since some PAT modes have multiple representations.
11936 */
11937 static bool
sysctl_kmaps_match(struct pmap_kernel_map_range * range,pt_entry_t attrs)11938 sysctl_kmaps_match(struct pmap_kernel_map_range *range, pt_entry_t attrs)
11939 {
11940 pt_entry_t diff, mask;
11941
11942 mask = X86_PG_G | X86_PG_RW | X86_PG_U | X86_PG_PDE_CACHE | pg_nx;
11943 diff = (range->attrs ^ attrs) & mask;
11944 if (diff == 0)
11945 return (true);
11946 if ((diff & ~X86_PG_PDE_PAT) == 0 &&
11947 pmap_pat_index(kernel_pmap, range->attrs, true) ==
11948 pmap_pat_index(kernel_pmap, attrs, true))
11949 return (true);
11950 return (false);
11951 }
11952
11953 static void
sysctl_kmaps_reinit(struct pmap_kernel_map_range * range,vm_offset_t va,pt_entry_t attrs)11954 sysctl_kmaps_reinit(struct pmap_kernel_map_range *range, vm_offset_t va,
11955 pt_entry_t attrs)
11956 {
11957
11958 memset(range, 0, sizeof(*range));
11959 range->sva = va;
11960 range->attrs = attrs;
11961 }
11962
11963 /*
11964 * Given a leaf PTE, derive the mapping's attributes. If they do not match
11965 * those of the current run, dump the address range and its attributes, and
11966 * begin a new run.
11967 */
11968 static void
sysctl_kmaps_check(struct sbuf * sb,struct pmap_kernel_map_range * range,vm_offset_t va,pml4_entry_t pml4e,pdp_entry_t pdpe,pd_entry_t pde,pt_entry_t pte)11969 sysctl_kmaps_check(struct sbuf *sb, struct pmap_kernel_map_range *range,
11970 vm_offset_t va, pml4_entry_t pml4e, pdp_entry_t pdpe, pd_entry_t pde,
11971 pt_entry_t pte)
11972 {
11973 pt_entry_t attrs;
11974
11975 attrs = pml4e & (X86_PG_RW | X86_PG_U | pg_nx);
11976
11977 attrs |= pdpe & pg_nx;
11978 attrs &= pg_nx | (pdpe & (X86_PG_RW | X86_PG_U));
11979 if ((pdpe & PG_PS) != 0) {
11980 attrs |= pdpe & (X86_PG_G | X86_PG_PDE_CACHE);
11981 } else if (pde != 0) {
11982 attrs |= pde & pg_nx;
11983 attrs &= pg_nx | (pde & (X86_PG_RW | X86_PG_U));
11984 }
11985 if ((pde & PG_PS) != 0) {
11986 attrs |= pde & (X86_PG_G | X86_PG_PDE_CACHE);
11987 } else if (pte != 0) {
11988 attrs |= pte & pg_nx;
11989 attrs &= pg_nx | (pte & (X86_PG_RW | X86_PG_U));
11990 attrs |= pte & (X86_PG_G | X86_PG_PTE_CACHE);
11991
11992 /* Canonicalize by always using the PDE PAT bit. */
11993 if ((attrs & X86_PG_PTE_PAT) != 0)
11994 attrs ^= X86_PG_PDE_PAT | X86_PG_PTE_PAT;
11995 }
11996
11997 if (range->sva > va || !sysctl_kmaps_match(range, attrs)) {
11998 sysctl_kmaps_dump(sb, range, va);
11999 sysctl_kmaps_reinit(range, va, attrs);
12000 }
12001 }
12002
12003 static int
sysctl_kmaps(SYSCTL_HANDLER_ARGS)12004 sysctl_kmaps(SYSCTL_HANDLER_ARGS)
12005 {
12006 struct pmap_kernel_map_range range;
12007 struct sbuf sbuf, *sb;
12008 pml4_entry_t pml4e;
12009 pdp_entry_t *pdp, pdpe;
12010 pd_entry_t *pd, pde;
12011 pt_entry_t *pt, pte;
12012 vm_offset_t sva;
12013 vm_paddr_t pa;
12014 int error, i, j, k, l;
12015
12016 error = sysctl_wire_old_buffer(req, 0);
12017 if (error != 0)
12018 return (error);
12019 sb = &sbuf;
12020 sbuf_new_for_sysctl(sb, NULL, PAGE_SIZE, req);
12021
12022 /* Sentinel value. */
12023 range.sva = la57 ? KV5ADDR(NPML5EPG - 1, NPML4EPG - 1, NPDPEPG - 1,
12024 NPDEPG - 1, NPTEPG - 1) : KV4ADDR(NPML4EPG - 1, NPDPEPG - 1,
12025 NPDEPG - 1, NPTEPG - 1);
12026
12027 /*
12028 * Iterate over the kernel page tables without holding the kernel pmap
12029 * lock. Outside of the large map, kernel page table pages are never
12030 * freed, so at worst we will observe inconsistencies in the output.
12031 * Within the large map, ensure that PDP and PD page addresses are
12032 * valid before descending.
12033 */
12034 for (sva = 0, i = pmap_pml4e_index(sva); i < NPML4EPG; i++) {
12035 switch (i) {
12036 case PML4PML4I:
12037 sbuf_printf(sb, "\nRecursive map:\n");
12038 break;
12039 case DMPML4I:
12040 sbuf_printf(sb, "\nDirect map:\n");
12041 break;
12042 #ifdef KASAN
12043 case KASANPML4I:
12044 sbuf_printf(sb, "\nKASAN shadow map:\n");
12045 break;
12046 #endif
12047 #ifdef KMSAN
12048 case KMSANSHADPML4I:
12049 sbuf_printf(sb, "\nKMSAN shadow map:\n");
12050 break;
12051 case KMSANORIGPML4I:
12052 sbuf_printf(sb, "\nKMSAN origin map:\n");
12053 break;
12054 #endif
12055 case KPML4BASE:
12056 sbuf_printf(sb, "\nKernel map:\n");
12057 break;
12058 case LMSPML4I:
12059 sbuf_printf(sb, "\nLarge map:\n");
12060 break;
12061 }
12062
12063 /* Convert to canonical form. */
12064 if (sva == 1ul << 47)
12065 sva |= -1ul << 48;
12066
12067 restart:
12068 pml4e = kernel_pml4[i];
12069 if ((pml4e & X86_PG_V) == 0) {
12070 sva = rounddown2(sva, NBPML4);
12071 sysctl_kmaps_dump(sb, &range, sva);
12072 sva += NBPML4;
12073 continue;
12074 }
12075 pa = pml4e & PG_FRAME;
12076 pdp = (pdp_entry_t *)PHYS_TO_DMAP(pa);
12077
12078 for (j = pmap_pdpe_index(sva); j < NPDPEPG; j++) {
12079 pdpe = pdp[j];
12080 if ((pdpe & X86_PG_V) == 0) {
12081 sva = rounddown2(sva, NBPDP);
12082 sysctl_kmaps_dump(sb, &range, sva);
12083 sva += NBPDP;
12084 continue;
12085 }
12086 pa = pdpe & PG_FRAME;
12087 if ((pdpe & PG_PS) != 0) {
12088 sva = rounddown2(sva, NBPDP);
12089 sysctl_kmaps_check(sb, &range, sva, pml4e, pdpe,
12090 0, 0);
12091 range.pdpes++;
12092 sva += NBPDP;
12093 continue;
12094 }
12095 if (PMAP_ADDRESS_IN_LARGEMAP(sva) &&
12096 vm_phys_paddr_to_vm_page(pa) == NULL) {
12097 /*
12098 * Page table pages for the large map may be
12099 * freed. Validate the next-level address
12100 * before descending.
12101 */
12102 goto restart;
12103 }
12104 pd = (pd_entry_t *)PHYS_TO_DMAP(pa);
12105
12106 for (k = pmap_pde_index(sva); k < NPDEPG; k++) {
12107 pde = pd[k];
12108 if ((pde & X86_PG_V) == 0) {
12109 sva = rounddown2(sva, NBPDR);
12110 sysctl_kmaps_dump(sb, &range, sva);
12111 sva += NBPDR;
12112 continue;
12113 }
12114 pa = pde & PG_FRAME;
12115 if ((pde & PG_PS) != 0) {
12116 sva = rounddown2(sva, NBPDR);
12117 sysctl_kmaps_check(sb, &range, sva,
12118 pml4e, pdpe, pde, 0);
12119 range.pdes++;
12120 sva += NBPDR;
12121 continue;
12122 }
12123 if (PMAP_ADDRESS_IN_LARGEMAP(sva) &&
12124 vm_phys_paddr_to_vm_page(pa) == NULL) {
12125 /*
12126 * Page table pages for the large map
12127 * may be freed. Validate the
12128 * next-level address before descending.
12129 */
12130 goto restart;
12131 }
12132 pt = (pt_entry_t *)PHYS_TO_DMAP(pa);
12133
12134 for (l = pmap_pte_index(sva); l < NPTEPG; l++,
12135 sva += PAGE_SIZE) {
12136 pte = pt[l];
12137 if ((pte & X86_PG_V) == 0) {
12138 sysctl_kmaps_dump(sb, &range,
12139 sva);
12140 continue;
12141 }
12142 sysctl_kmaps_check(sb, &range, sva,
12143 pml4e, pdpe, pde, pte);
12144 range.ptes++;
12145 }
12146 }
12147 }
12148 }
12149
12150 error = sbuf_finish(sb);
12151 sbuf_delete(sb);
12152 return (error);
12153 }
12154 SYSCTL_OID(_vm_pmap, OID_AUTO, kernel_maps,
12155 CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
12156 NULL, 0, sysctl_kmaps, "A",
12157 "Dump kernel address layout");
12158
12159 #ifdef DDB
DB_SHOW_COMMAND(pte,pmap_print_pte)12160 DB_SHOW_COMMAND(pte, pmap_print_pte)
12161 {
12162 pmap_t pmap;
12163 pml5_entry_t *pml5;
12164 pml4_entry_t *pml4;
12165 pdp_entry_t *pdp;
12166 pd_entry_t *pde;
12167 pt_entry_t *pte, PG_V;
12168 vm_offset_t va;
12169
12170 if (!have_addr) {
12171 db_printf("show pte addr\n");
12172 return;
12173 }
12174 va = (vm_offset_t)addr;
12175
12176 if (kdb_thread != NULL)
12177 pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
12178 else
12179 pmap = PCPU_GET(curpmap);
12180
12181 PG_V = pmap_valid_bit(pmap);
12182 db_printf("VA 0x%016lx", va);
12183
12184 if (pmap_is_la57(pmap)) {
12185 pml5 = pmap_pml5e(pmap, va);
12186 db_printf(" pml5e 0x%016lx", *pml5);
12187 if ((*pml5 & PG_V) == 0) {
12188 db_printf("\n");
12189 return;
12190 }
12191 pml4 = pmap_pml5e_to_pml4e(pml5, va);
12192 } else {
12193 pml4 = pmap_pml4e(pmap, va);
12194 }
12195 db_printf(" pml4e 0x%016lx", *pml4);
12196 if ((*pml4 & PG_V) == 0) {
12197 db_printf("\n");
12198 return;
12199 }
12200 pdp = pmap_pml4e_to_pdpe(pml4, va);
12201 db_printf(" pdpe 0x%016lx", *pdp);
12202 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
12203 db_printf("\n");
12204 return;
12205 }
12206 pde = pmap_pdpe_to_pde(pdp, va);
12207 db_printf(" pde 0x%016lx", *pde);
12208 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
12209 db_printf("\n");
12210 return;
12211 }
12212 pte = pmap_pde_to_pte(pde, va);
12213 db_printf(" pte 0x%016lx\n", *pte);
12214 }
12215
DB_SHOW_COMMAND(phys2dmap,pmap_phys2dmap)12216 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
12217 {
12218 vm_paddr_t a;
12219
12220 if (have_addr) {
12221 a = (vm_paddr_t)addr;
12222 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
12223 } else {
12224 db_printf("show phys2dmap addr\n");
12225 }
12226 }
12227
12228 static void
ptpages_show_page(int level,int idx,vm_page_t pg)12229 ptpages_show_page(int level, int idx, vm_page_t pg)
12230 {
12231 db_printf("l %d i %d pg %p phys %#lx ref %x\n",
12232 level, idx, pg, VM_PAGE_TO_PHYS(pg), pg->ref_count);
12233 }
12234
12235 static void
ptpages_show_complain(int level,int idx,uint64_t pte)12236 ptpages_show_complain(int level, int idx, uint64_t pte)
12237 {
12238 db_printf("l %d i %d pte %#lx\n", level, idx, pte);
12239 }
12240
12241 static void
ptpages_show_pml4(vm_page_t pg4,int num_entries,uint64_t PG_V)12242 ptpages_show_pml4(vm_page_t pg4, int num_entries, uint64_t PG_V)
12243 {
12244 vm_page_t pg3, pg2, pg1;
12245 pml4_entry_t *pml4;
12246 pdp_entry_t *pdp;
12247 pd_entry_t *pd;
12248 int i4, i3, i2;
12249
12250 pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg4));
12251 for (i4 = 0; i4 < num_entries; i4++) {
12252 if ((pml4[i4] & PG_V) == 0)
12253 continue;
12254 pg3 = PHYS_TO_VM_PAGE(pml4[i4] & PG_FRAME);
12255 if (pg3 == NULL) {
12256 ptpages_show_complain(3, i4, pml4[i4]);
12257 continue;
12258 }
12259 ptpages_show_page(3, i4, pg3);
12260 pdp = (pdp_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg3));
12261 for (i3 = 0; i3 < NPDPEPG; i3++) {
12262 if ((pdp[i3] & PG_V) == 0)
12263 continue;
12264 pg2 = PHYS_TO_VM_PAGE(pdp[i3] & PG_FRAME);
12265 if (pg3 == NULL) {
12266 ptpages_show_complain(2, i3, pdp[i3]);
12267 continue;
12268 }
12269 ptpages_show_page(2, i3, pg2);
12270 pd = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pg2));
12271 for (i2 = 0; i2 < NPDEPG; i2++) {
12272 if ((pd[i2] & PG_V) == 0)
12273 continue;
12274 pg1 = PHYS_TO_VM_PAGE(pd[i2] & PG_FRAME);
12275 if (pg1 == NULL) {
12276 ptpages_show_complain(1, i2, pd[i2]);
12277 continue;
12278 }
12279 ptpages_show_page(1, i2, pg1);
12280 }
12281 }
12282 }
12283 }
12284
DB_SHOW_COMMAND(ptpages,pmap_ptpages)12285 DB_SHOW_COMMAND(ptpages, pmap_ptpages)
12286 {
12287 pmap_t pmap;
12288 vm_page_t pg;
12289 pml5_entry_t *pml5;
12290 uint64_t PG_V;
12291 int i5;
12292
12293 if (have_addr)
12294 pmap = (pmap_t)addr;
12295 else
12296 pmap = PCPU_GET(curpmap);
12297
12298 PG_V = pmap_valid_bit(pmap);
12299
12300 if (pmap_is_la57(pmap)) {
12301 pml5 = pmap->pm_pmltop;
12302 for (i5 = 0; i5 < NUPML5E; i5++) {
12303 if ((pml5[i5] & PG_V) == 0)
12304 continue;
12305 pg = PHYS_TO_VM_PAGE(pml5[i5] & PG_FRAME);
12306 if (pg == NULL) {
12307 ptpages_show_complain(4, i5, pml5[i5]);
12308 continue;
12309 }
12310 ptpages_show_page(4, i5, pg);
12311 ptpages_show_pml4(pg, NPML4EPG, PG_V);
12312 }
12313 } else {
12314 ptpages_show_pml4(PHYS_TO_VM_PAGE(DMAP_TO_PHYS(
12315 (vm_offset_t)pmap->pm_pmltop)), NUP4ML4E, PG_V);
12316 }
12317 }
12318 #endif
12319