FreeBSD/Linux Kernel Cross Reference
sys/amd64/amd64/pmap.c
1 /*-
2 * Copyright (c) 1991 Regents of the University of California.
3 * All rights reserved.
4 * Copyright (c) 1994 John S. Dyson
5 * All rights reserved.
6 * Copyright (c) 1994 David Greenman
7 * All rights reserved.
8 * Copyright (c) 2003 Peter Wemm
9 * All rights reserved.
10 * Copyright (c) 2005-2010 Alan L. Cox <alc@cs.rice.edu>
11 * All rights reserved.
12 * Copyright (c) 2014-2018 The FreeBSD Foundation
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 * Portions of this software were developed by
20 * Konstantin Belousov <kib@FreeBSD.org> under sponsorship from
21 * the FreeBSD Foundation.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 * must display the following acknowledgement:
33 * This product includes software developed by the University of
34 * California, Berkeley and its contributors.
35 * 4. Neither the name of the University nor the names of its contributors
36 * may be used to endorse or promote products derived from this software
37 * without specific prior written permission.
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
40 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
42 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
43 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
44 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
45 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
46 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
47 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
48 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
49 * SUCH DAMAGE.
50 *
51 * from: @(#)pmap.c 7.7 (Berkeley) 5/12/91
52 */
53 /*-
54 * Copyright (c) 2003 Networks Associates Technology, Inc.
55 * All rights reserved.
56 *
57 * This software was developed for the FreeBSD Project by Jake Burkholder,
58 * Safeport Network Services, and Network Associates Laboratories, the
59 * Security Research Division of Network Associates, Inc. under
60 * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
61 * CHATS research program.
62 *
63 * Redistribution and use in source and binary forms, with or without
64 * modification, are permitted provided that the following conditions
65 * are met:
66 * 1. Redistributions of source code must retain the above copyright
67 * notice, this list of conditions and the following disclaimer.
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in the
70 * documentation and/or other materials provided with the distribution.
71 *
72 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
73 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
74 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
75 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
76 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
77 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
78 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
79 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
80 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
81 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
82 * SUCH DAMAGE.
83 */
84
85 #define AMD64_NPT_AWARE
86
87 #include <sys/cdefs.h>
88 __FBSDID("$FreeBSD$");
89
90 /*
91 * Manages physical address maps.
92 *
93 * Since the information managed by this module is
94 * also stored by the logical address mapping module,
95 * this module may throw away valid virtual-to-physical
96 * mappings at almost any time. However, invalidations
97 * of virtual-to-physical mappings must be done as
98 * requested.
99 *
100 * In order to cope with hardware architectures which
101 * make virtual-to-physical map invalidates expensive,
102 * this module may delay invalidate or reduced protection
103 * operations until such time as they are actually
104 * necessary. This module is given full information as
105 * to which processors are currently using which maps,
106 * and to when physical maps must be made correct.
107 */
108
109 #include "opt_pmap.h"
110 #include "opt_vm.h"
111
112 #include <sys/param.h>
113 #include <sys/bitstring.h>
114 #include <sys/bus.h>
115 #include <sys/systm.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/mutex.h>
122 #include <sys/proc.h>
123 #include <sys/rwlock.h>
124 #include <sys/sx.h>
125 #include <sys/turnstile.h>
126 #include <sys/vmem.h>
127 #include <sys/vmmeter.h>
128 #include <sys/sched.h>
129 #include <sys/sysctl.h>
130 #include <sys/smp.h>
131
132 #include <vm/vm.h>
133 #include <vm/vm_param.h>
134 #include <vm/vm_kern.h>
135 #include <vm/vm_page.h>
136 #include <vm/vm_map.h>
137 #include <vm/vm_object.h>
138 #include <vm/vm_extern.h>
139 #include <vm/vm_pageout.h>
140 #include <vm/vm_pager.h>
141 #include <vm/vm_phys.h>
142 #include <vm/vm_radix.h>
143 #include <vm/vm_reserv.h>
144 #include <vm/uma.h>
145
146 #include <machine/intr_machdep.h>
147 #include <x86/apicvar.h>
148 #include <machine/cpu.h>
149 #include <machine/cputypes.h>
150 #include <machine/md_var.h>
151 #include <machine/pcb.h>
152 #include <machine/specialreg.h>
153 #ifdef SMP
154 #include <machine/smp.h>
155 #endif
156 #include <machine/tss.h>
157
158 static __inline boolean_t
159 pmap_type_guest(pmap_t pmap)
160 {
161
162 return ((pmap->pm_type == PT_EPT) || (pmap->pm_type == PT_RVI));
163 }
164
165 static __inline boolean_t
166 pmap_emulate_ad_bits(pmap_t pmap)
167 {
168
169 return ((pmap->pm_flags & PMAP_EMULATE_AD_BITS) != 0);
170 }
171
172 static __inline pt_entry_t
173 pmap_valid_bit(pmap_t pmap)
174 {
175 pt_entry_t mask;
176
177 switch (pmap->pm_type) {
178 case PT_X86:
179 case PT_RVI:
180 mask = X86_PG_V;
181 break;
182 case PT_EPT:
183 if (pmap_emulate_ad_bits(pmap))
184 mask = EPT_PG_EMUL_V;
185 else
186 mask = EPT_PG_READ;
187 break;
188 default:
189 panic("pmap_valid_bit: invalid pm_type %d", pmap->pm_type);
190 }
191
192 return (mask);
193 }
194
195 static __inline pt_entry_t
196 pmap_rw_bit(pmap_t pmap)
197 {
198 pt_entry_t mask;
199
200 switch (pmap->pm_type) {
201 case PT_X86:
202 case PT_RVI:
203 mask = X86_PG_RW;
204 break;
205 case PT_EPT:
206 if (pmap_emulate_ad_bits(pmap))
207 mask = EPT_PG_EMUL_RW;
208 else
209 mask = EPT_PG_WRITE;
210 break;
211 default:
212 panic("pmap_rw_bit: invalid pm_type %d", pmap->pm_type);
213 }
214
215 return (mask);
216 }
217
218 static pt_entry_t pg_g;
219
220 static __inline pt_entry_t
221 pmap_global_bit(pmap_t pmap)
222 {
223 pt_entry_t mask;
224
225 switch (pmap->pm_type) {
226 case PT_X86:
227 mask = pg_g;
228 break;
229 case PT_RVI:
230 case PT_EPT:
231 mask = 0;
232 break;
233 default:
234 panic("pmap_global_bit: invalid pm_type %d", pmap->pm_type);
235 }
236
237 return (mask);
238 }
239
240 static __inline pt_entry_t
241 pmap_accessed_bit(pmap_t pmap)
242 {
243 pt_entry_t mask;
244
245 switch (pmap->pm_type) {
246 case PT_X86:
247 case PT_RVI:
248 mask = X86_PG_A;
249 break;
250 case PT_EPT:
251 if (pmap_emulate_ad_bits(pmap))
252 mask = EPT_PG_READ;
253 else
254 mask = EPT_PG_A;
255 break;
256 default:
257 panic("pmap_accessed_bit: invalid pm_type %d", pmap->pm_type);
258 }
259
260 return (mask);
261 }
262
263 static __inline pt_entry_t
264 pmap_modified_bit(pmap_t pmap)
265 {
266 pt_entry_t mask;
267
268 switch (pmap->pm_type) {
269 case PT_X86:
270 case PT_RVI:
271 mask = X86_PG_M;
272 break;
273 case PT_EPT:
274 if (pmap_emulate_ad_bits(pmap))
275 mask = EPT_PG_WRITE;
276 else
277 mask = EPT_PG_M;
278 break;
279 default:
280 panic("pmap_modified_bit: invalid pm_type %d", pmap->pm_type);
281 }
282
283 return (mask);
284 }
285
286 extern struct pcpu __pcpu[];
287
288 #if !defined(DIAGNOSTIC)
289 #ifdef __GNUC_GNU_INLINE__
290 #define PMAP_INLINE __attribute__((__gnu_inline__)) inline
291 #else
292 #define PMAP_INLINE extern inline
293 #endif
294 #else
295 #define PMAP_INLINE
296 #endif
297
298 #ifdef PV_STATS
299 #define PV_STAT(x) do { x ; } while (0)
300 #else
301 #define PV_STAT(x) do { } while (0)
302 #endif
303
304 #define pa_index(pa) ((pa) >> PDRSHIFT)
305 #define pa_to_pvh(pa) (&pv_table[pa_index(pa)])
306
307 #define NPV_LIST_LOCKS MAXCPU
308
309 #define PHYS_TO_PV_LIST_LOCK(pa) \
310 (&pv_list_locks[pa_index(pa) % NPV_LIST_LOCKS])
311
312 #define CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa) do { \
313 struct rwlock **_lockp = (lockp); \
314 struct rwlock *_new_lock; \
315 \
316 _new_lock = PHYS_TO_PV_LIST_LOCK(pa); \
317 if (_new_lock != *_lockp) { \
318 if (*_lockp != NULL) \
319 rw_wunlock(*_lockp); \
320 *_lockp = _new_lock; \
321 rw_wlock(*_lockp); \
322 } \
323 } while (0)
324
325 #define CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m) \
326 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, VM_PAGE_TO_PHYS(m))
327
328 #define RELEASE_PV_LIST_LOCK(lockp) do { \
329 struct rwlock **_lockp = (lockp); \
330 \
331 if (*_lockp != NULL) { \
332 rw_wunlock(*_lockp); \
333 *_lockp = NULL; \
334 } \
335 } while (0)
336
337 #define VM_PAGE_TO_PV_LIST_LOCK(m) \
338 PHYS_TO_PV_LIST_LOCK(VM_PAGE_TO_PHYS(m))
339
340 struct pmap kernel_pmap_store;
341
342 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
343 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
344
345 int nkpt;
346 SYSCTL_INT(_machdep, OID_AUTO, nkpt, CTLFLAG_RD, &nkpt, 0,
347 "Number of kernel page table pages allocated on bootup");
348
349 static int ndmpdp;
350 vm_paddr_t dmaplimit;
351 vm_offset_t kernel_vm_end = VM_MIN_KERNEL_ADDRESS;
352 pt_entry_t pg_nx;
353
354 static SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
355
356 static int pat_works = 1;
357 SYSCTL_INT(_vm_pmap, OID_AUTO, pat_works, CTLFLAG_RD, &pat_works, 1,
358 "Is page attribute table fully functional?");
359
360 static int pg_ps_enabled = 1;
361 SYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
362 &pg_ps_enabled, 0, "Are large page mappings enabled?");
363
364 #define PAT_INDEX_SIZE 8
365 static int pat_index[PAT_INDEX_SIZE]; /* cache mode to PAT index conversion */
366
367 static u_int64_t KPTphys; /* phys addr of kernel level 1 */
368 static u_int64_t KPDphys; /* phys addr of kernel level 2 */
369 u_int64_t KPDPphys; /* phys addr of kernel level 3 */
370 u_int64_t KPML4phys; /* phys addr of kernel level 4 */
371
372 static u_int64_t DMPDphys; /* phys addr of direct mapped level 2 */
373 static u_int64_t DMPDPphys; /* phys addr of direct mapped level 3 */
374 static int ndmpdpphys; /* number of DMPDPphys pages */
375
376 static vm_paddr_t KERNend; /* phys addr of end of bootstrap data */
377
378 /*
379 * pmap_mapdev support pre initialization (i.e. console)
380 */
381 #define PMAP_PREINIT_MAPPING_COUNT 8
382 static struct pmap_preinit_mapping {
383 vm_paddr_t pa;
384 vm_offset_t va;
385 vm_size_t sz;
386 int mode;
387 } pmap_preinit_mapping[PMAP_PREINIT_MAPPING_COUNT];
388 static int pmap_initialized;
389
390 /*
391 * Data for the pv entry allocation mechanism.
392 * Updates to pv_invl_gen are protected by the pv_list_locks[]
393 * elements, but reads are not.
394 */
395 static TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
396 static struct mtx pv_chunks_mutex;
397 static struct rwlock pv_list_locks[NPV_LIST_LOCKS];
398 static u_long pv_invl_gen[NPV_LIST_LOCKS];
399 static struct md_page *pv_table;
400 static struct md_page pv_dummy;
401
402 /*
403 * All those kernel PT submaps that BSD is so fond of
404 */
405 pt_entry_t *CMAP1 = NULL;
406 caddr_t CADDR1 = 0;
407 static vm_offset_t qframe = 0;
408 static struct mtx qframe_mtx;
409
410 static int pmap_flags = PMAP_PDE_SUPERPAGE; /* flags for x86 pmaps */
411
412 int pmap_pcid_enabled = 1;
413 SYSCTL_INT(_vm_pmap, OID_AUTO, pcid_enabled, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
414 &pmap_pcid_enabled, 0, "Is TLB Context ID enabled ?");
415 int invpcid_works = 0;
416 SYSCTL_INT(_vm_pmap, OID_AUTO, invpcid_works, CTLFLAG_RD, &invpcid_works, 0,
417 "Is the invpcid instruction available ?");
418
419 int pti = 0;
420 SYSCTL_INT(_vm_pmap, OID_AUTO, pti, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
421 &pti, 0,
422 "Page Table Isolation enabled");
423 static vm_object_t pti_obj;
424 static pml4_entry_t *pti_pml4;
425 static vm_pindex_t pti_pg_idx;
426 static bool pti_finalized;
427
428 static int
429 pmap_pcid_save_cnt_proc(SYSCTL_HANDLER_ARGS)
430 {
431 int i;
432 uint64_t res;
433
434 res = 0;
435 CPU_FOREACH(i) {
436 res += cpuid_to_pcpu[i]->pc_pm_save_cnt;
437 }
438 return (sysctl_handle_64(oidp, &res, 0, req));
439 }
440 SYSCTL_PROC(_vm_pmap, OID_AUTO, pcid_save_cnt, CTLTYPE_U64 | CTLFLAG_RW |
441 CTLFLAG_MPSAFE, NULL, 0, pmap_pcid_save_cnt_proc, "QU",
442 "Count of saved TLB context on switch");
443
444 static LIST_HEAD(, pmap_invl_gen) pmap_invl_gen_tracker =
445 LIST_HEAD_INITIALIZER(&pmap_invl_gen_tracker);
446 static struct mtx invl_gen_mtx;
447 static u_long pmap_invl_gen = 0;
448 /* Fake lock object to satisfy turnstiles interface. */
449 static struct lock_object invl_gen_ts = {
450 .lo_name = "invlts",
451 };
452
453 static bool
454 pmap_not_in_di(void)
455 {
456
457 return (curthread->td_md.md_invl_gen.gen == 0);
458 }
459
460 #define PMAP_ASSERT_NOT_IN_DI() \
461 KASSERT(pmap_not_in_di(), ("DI already started"))
462
463 /*
464 * Start a new Delayed Invalidation (DI) block of code, executed by
465 * the current thread. Within a DI block, the current thread may
466 * destroy both the page table and PV list entries for a mapping and
467 * then release the corresponding PV list lock before ensuring that
468 * the mapping is flushed from the TLBs of any processors with the
469 * pmap active.
470 */
471 static void
472 pmap_delayed_invl_started(void)
473 {
474 struct pmap_invl_gen *invl_gen;
475 u_long currgen;
476
477 invl_gen = &curthread->td_md.md_invl_gen;
478 PMAP_ASSERT_NOT_IN_DI();
479 mtx_lock(&invl_gen_mtx);
480 if (LIST_EMPTY(&pmap_invl_gen_tracker))
481 currgen = pmap_invl_gen;
482 else
483 currgen = LIST_FIRST(&pmap_invl_gen_tracker)->gen;
484 invl_gen->gen = currgen + 1;
485 LIST_INSERT_HEAD(&pmap_invl_gen_tracker, invl_gen, link);
486 mtx_unlock(&invl_gen_mtx);
487 }
488
489 /*
490 * Finish the DI block, previously started by the current thread. All
491 * required TLB flushes for the pages marked by
492 * pmap_delayed_invl_page() must be finished before this function is
493 * called.
494 *
495 * This function works by bumping the global DI generation number to
496 * the generation number of the current thread's DI, unless there is a
497 * pending DI that started earlier. In the latter case, bumping the
498 * global DI generation number would incorrectly signal that the
499 * earlier DI had finished. Instead, this function bumps the earlier
500 * DI's generation number to match the generation number of the
501 * current thread's DI.
502 */
503 static void
504 pmap_delayed_invl_finished(void)
505 {
506 struct pmap_invl_gen *invl_gen, *next;
507 struct turnstile *ts;
508
509 invl_gen = &curthread->td_md.md_invl_gen;
510 KASSERT(invl_gen->gen != 0, ("missed invl_started"));
511 mtx_lock(&invl_gen_mtx);
512 next = LIST_NEXT(invl_gen, link);
513 if (next == NULL) {
514 turnstile_chain_lock(&invl_gen_ts);
515 ts = turnstile_lookup(&invl_gen_ts);
516 pmap_invl_gen = invl_gen->gen;
517 if (ts != NULL) {
518 turnstile_broadcast(ts, TS_SHARED_QUEUE);
519 turnstile_unpend(ts, TS_SHARED_LOCK);
520 }
521 turnstile_chain_unlock(&invl_gen_ts);
522 } else {
523 next->gen = invl_gen->gen;
524 }
525 LIST_REMOVE(invl_gen, link);
526 mtx_unlock(&invl_gen_mtx);
527 invl_gen->gen = 0;
528 }
529
530 #ifdef PV_STATS
531 static long invl_wait;
532 SYSCTL_LONG(_vm_pmap, OID_AUTO, invl_wait, CTLFLAG_RD, &invl_wait, 0,
533 "Number of times DI invalidation blocked pmap_remove_all/write");
534 #endif
535
536 static u_long *
537 pmap_delayed_invl_genp(vm_page_t m)
538 {
539
540 return (&pv_invl_gen[pa_index(VM_PAGE_TO_PHYS(m)) % NPV_LIST_LOCKS]);
541 }
542
543 /*
544 * Ensure that all currently executing DI blocks, that need to flush
545 * TLB for the given page m, actually flushed the TLB at the time the
546 * function returned. If the page m has an empty PV list and we call
547 * pmap_delayed_invl_wait(), upon its return we know that no CPU has a
548 * valid mapping for the page m in either its page table or TLB.
549 *
550 * This function works by blocking until the global DI generation
551 * number catches up with the generation number associated with the
552 * given page m and its PV list. Since this function's callers
553 * typically own an object lock and sometimes own a page lock, it
554 * cannot sleep. Instead, it blocks on a turnstile to relinquish the
555 * processor.
556 */
557 static void
558 pmap_delayed_invl_wait(vm_page_t m)
559 {
560 struct turnstile *ts;
561 u_long *m_gen;
562 #ifdef PV_STATS
563 bool accounted = false;
564 #endif
565
566 m_gen = pmap_delayed_invl_genp(m);
567 while (*m_gen > pmap_invl_gen) {
568 #ifdef PV_STATS
569 if (!accounted) {
570 atomic_add_long(&invl_wait, 1);
571 accounted = true;
572 }
573 #endif
574 ts = turnstile_trywait(&invl_gen_ts);
575 if (*m_gen > pmap_invl_gen)
576 turnstile_wait(ts, NULL, TS_SHARED_QUEUE);
577 else
578 turnstile_cancel(ts);
579 }
580 }
581
582 /*
583 * Mark the page m's PV list as participating in the current thread's
584 * DI block. Any threads concurrently using m's PV list to remove or
585 * restrict all mappings to m will wait for the current thread's DI
586 * block to complete before proceeding.
587 *
588 * The function works by setting the DI generation number for m's PV
589 * list to at least the DI generation number of the current thread.
590 * This forces a caller of pmap_delayed_invl_wait() to block until
591 * current thread calls pmap_delayed_invl_finished().
592 */
593 static void
594 pmap_delayed_invl_page(vm_page_t m)
595 {
596 u_long gen, *m_gen;
597
598 rw_assert(VM_PAGE_TO_PV_LIST_LOCK(m), RA_WLOCKED);
599 gen = curthread->td_md.md_invl_gen.gen;
600 if (gen == 0)
601 return;
602 m_gen = pmap_delayed_invl_genp(m);
603 if (*m_gen < gen)
604 *m_gen = gen;
605 }
606
607 /*
608 * Crashdump maps.
609 */
610 static caddr_t crashdumpmap;
611
612 /*
613 * Internal flags for pmap_enter()'s helper functions.
614 */
615 #define PMAP_ENTER_NORECLAIM 0x1000000 /* Don't reclaim PV entries. */
616 #define PMAP_ENTER_NOREPLACE 0x2000000 /* Don't replace mappings. */
617
618 /*
619 * Internal flags for pmap_mapdev_internal() and
620 * pmap_change_attr_locked().
621 */
622 #define MAPDEV_FLUSHCACHE 0x0000001 /* Flush cache after mapping. */
623 #define MAPDEV_SETATTR 0x0000002 /* Modify existing attrs. */
624
625 static void free_pv_chunk(struct pv_chunk *pc);
626 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
627 static pv_entry_t get_pv_entry(pmap_t pmap, struct rwlock **lockp);
628 static int popcnt_pc_map_pq(uint64_t *map);
629 static vm_page_t reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp);
630 static void reserve_pv_entries(pmap_t pmap, int needed,
631 struct rwlock **lockp);
632 static void pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
633 struct rwlock **lockp);
634 static bool pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde,
635 u_int flags, struct rwlock **lockp);
636 #if VM_NRESERVLEVEL > 0
637 static void pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
638 struct rwlock **lockp);
639 #endif
640 static void pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
641 static pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
642 vm_offset_t va);
643
644 static int pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode,
645 int flags);
646 static boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
647 static boolean_t pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde,
648 vm_offset_t va, struct rwlock **lockp);
649 static boolean_t pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe,
650 vm_offset_t va);
651 static bool pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m,
652 vm_prot_t prot, struct rwlock **lockp);
653 static int pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde,
654 u_int flags, vm_page_t m, struct rwlock **lockp);
655 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
656 vm_page_t m, vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp);
657 static void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
658 static int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
659 static void pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va,
660 pd_entry_t pde);
661 static void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
662 static void pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask);
663 #if VM_NRESERVLEVEL > 0
664 static void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
665 struct rwlock **lockp);
666 #endif
667 static boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
668 vm_prot_t prot);
669 static void pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask);
670 static void pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva,
671 bool exec);
672 static pdp_entry_t *pmap_pti_pdpe(vm_offset_t va);
673 static pd_entry_t *pmap_pti_pde(vm_offset_t va);
674 static void pmap_pti_wire_pte(void *pte);
675 static int pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
676 struct spglist *free, struct rwlock **lockp);
677 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
678 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp);
679 static vm_page_t pmap_remove_pt_page(pmap_t pmap, vm_offset_t va);
680 static void pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
681 struct spglist *free);
682 static bool pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
683 pd_entry_t *pde, struct spglist *free,
684 struct rwlock **lockp);
685 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
686 vm_page_t m, struct rwlock **lockp);
687 static void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
688 pd_entry_t newpde);
689 static void pmap_update_pde_invalidate(pmap_t, vm_offset_t va, pd_entry_t pde);
690
691 static vm_page_t _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex,
692 struct rwlock **lockp);
693 static vm_page_t pmap_allocpde(pmap_t pmap, vm_offset_t va,
694 struct rwlock **lockp);
695 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va,
696 struct rwlock **lockp);
697
698 static void _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m,
699 struct spglist *free);
700 static int pmap_unuse_pt(pmap_t, vm_offset_t, pd_entry_t, struct spglist *);
701
702 /********************/
703 /* Inline functions */
704 /********************/
705
706 /* Return a non-clipped PD index for a given VA */
707 static __inline vm_pindex_t
708 pmap_pde_pindex(vm_offset_t va)
709 {
710 return (va >> PDRSHIFT);
711 }
712
713
714 /* Return a pointer to the PML4 slot that corresponds to a VA */
715 static __inline pml4_entry_t *
716 pmap_pml4e(pmap_t pmap, vm_offset_t va)
717 {
718
719 return (&pmap->pm_pml4[pmap_pml4e_index(va)]);
720 }
721
722 /* Return a pointer to the PDP slot that corresponds to a VA */
723 static __inline pdp_entry_t *
724 pmap_pml4e_to_pdpe(pml4_entry_t *pml4e, vm_offset_t va)
725 {
726 pdp_entry_t *pdpe;
727
728 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(*pml4e & PG_FRAME);
729 return (&pdpe[pmap_pdpe_index(va)]);
730 }
731
732 /* Return a pointer to the PDP slot that corresponds to a VA */
733 static __inline pdp_entry_t *
734 pmap_pdpe(pmap_t pmap, vm_offset_t va)
735 {
736 pml4_entry_t *pml4e;
737 pt_entry_t PG_V;
738
739 PG_V = pmap_valid_bit(pmap);
740 pml4e = pmap_pml4e(pmap, va);
741 if ((*pml4e & PG_V) == 0)
742 return (NULL);
743 return (pmap_pml4e_to_pdpe(pml4e, va));
744 }
745
746 /* Return a pointer to the PD slot that corresponds to a VA */
747 static __inline pd_entry_t *
748 pmap_pdpe_to_pde(pdp_entry_t *pdpe, vm_offset_t va)
749 {
750 pd_entry_t *pde;
751
752 pde = (pd_entry_t *)PHYS_TO_DMAP(*pdpe & PG_FRAME);
753 return (&pde[pmap_pde_index(va)]);
754 }
755
756 /* Return a pointer to the PD slot that corresponds to a VA */
757 static __inline pd_entry_t *
758 pmap_pde(pmap_t pmap, vm_offset_t va)
759 {
760 pdp_entry_t *pdpe;
761 pt_entry_t PG_V;
762
763 PG_V = pmap_valid_bit(pmap);
764 pdpe = pmap_pdpe(pmap, va);
765 if (pdpe == NULL || (*pdpe & PG_V) == 0)
766 return (NULL);
767 return (pmap_pdpe_to_pde(pdpe, va));
768 }
769
770 /* Return a pointer to the PT slot that corresponds to a VA */
771 static __inline pt_entry_t *
772 pmap_pde_to_pte(pd_entry_t *pde, vm_offset_t va)
773 {
774 pt_entry_t *pte;
775
776 pte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
777 return (&pte[pmap_pte_index(va)]);
778 }
779
780 /* Return a pointer to the PT slot that corresponds to a VA */
781 static __inline pt_entry_t *
782 pmap_pte(pmap_t pmap, vm_offset_t va)
783 {
784 pd_entry_t *pde;
785 pt_entry_t PG_V;
786
787 PG_V = pmap_valid_bit(pmap);
788 pde = pmap_pde(pmap, va);
789 if (pde == NULL || (*pde & PG_V) == 0)
790 return (NULL);
791 if ((*pde & PG_PS) != 0) /* compat with i386 pmap_pte() */
792 return ((pt_entry_t *)pde);
793 return (pmap_pde_to_pte(pde, va));
794 }
795
796 static __inline void
797 pmap_resident_count_inc(pmap_t pmap, int count)
798 {
799
800 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
801 pmap->pm_stats.resident_count += count;
802 }
803
804 static __inline void
805 pmap_resident_count_dec(pmap_t pmap, int count)
806 {
807
808 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
809 KASSERT(pmap->pm_stats.resident_count >= count,
810 ("pmap %p resident count underflow %ld %d", pmap,
811 pmap->pm_stats.resident_count, count));
812 pmap->pm_stats.resident_count -= count;
813 }
814
815 PMAP_INLINE pt_entry_t *
816 vtopte(vm_offset_t va)
817 {
818 u_int64_t mask = ((1ul << (NPTEPGSHIFT + NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
819
820 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopte on a uva/gpa 0x%0lx", va));
821
822 return (PTmap + ((va >> PAGE_SHIFT) & mask));
823 }
824
825 static __inline pd_entry_t *
826 vtopde(vm_offset_t va)
827 {
828 u_int64_t mask = ((1ul << (NPDEPGSHIFT + NPDPEPGSHIFT + NPML4EPGSHIFT)) - 1);
829
830 KASSERT(va >= VM_MAXUSER_ADDRESS, ("vtopde on a uva/gpa 0x%0lx", va));
831
832 return (PDmap + ((va >> PDRSHIFT) & mask));
833 }
834
835 static u_int64_t
836 allocpages(vm_paddr_t *firstaddr, int n)
837 {
838 u_int64_t ret;
839
840 ret = *firstaddr;
841 bzero((void *)ret, n * PAGE_SIZE);
842 *firstaddr += n * PAGE_SIZE;
843 return (ret);
844 }
845
846 CTASSERT(powerof2(NDMPML4E));
847
848 /* number of kernel PDP slots */
849 #define NKPDPE(ptpgs) howmany(ptpgs, NPDEPG)
850
851 static void
852 nkpt_init(vm_paddr_t addr)
853 {
854 int pt_pages;
855
856 #ifdef NKPT
857 pt_pages = NKPT;
858 #else
859 pt_pages = howmany(addr, 1 << PDRSHIFT);
860 pt_pages += NKPDPE(pt_pages);
861
862 /*
863 * Add some slop beyond the bare minimum required for bootstrapping
864 * the kernel.
865 *
866 * This is quite important when allocating KVA for kernel modules.
867 * The modules are required to be linked in the negative 2GB of
868 * the address space. If we run out of KVA in this region then
869 * pmap_growkernel() will need to allocate page table pages to map
870 * the entire 512GB of KVA space which is an unnecessary tax on
871 * physical memory.
872 *
873 * Secondly, device memory mapped as part of setting up the low-
874 * level console(s) is taken from KVA, starting at virtual_avail.
875 * This is because cninit() is called after pmap_bootstrap() but
876 * before vm_init() and pmap_init(). 20MB for a frame buffer is
877 * not uncommon.
878 */
879 pt_pages += 32; /* 64MB additional slop. */
880 #endif
881 nkpt = pt_pages;
882 }
883
884 static void
885 create_pagetables(vm_paddr_t *firstaddr)
886 {
887 int i, j, ndm1g, nkpdpe;
888 pt_entry_t *pt_p;
889 pd_entry_t *pd_p;
890 pdp_entry_t *pdp_p;
891 pml4_entry_t *p4_p;
892
893 /* Allocate page table pages for the direct map */
894 ndmpdp = howmany(ptoa(Maxmem), NBPDP);
895 if (ndmpdp < 4) /* Minimum 4GB of dirmap */
896 ndmpdp = 4;
897 ndmpdpphys = howmany(ndmpdp, NPDPEPG);
898 if (ndmpdpphys > NDMPML4E) {
899 /*
900 * Each NDMPML4E allows 512 GB, so limit to that,
901 * and then readjust ndmpdp and ndmpdpphys.
902 */
903 printf("NDMPML4E limits system to %d GB\n", NDMPML4E * 512);
904 Maxmem = atop(NDMPML4E * NBPML4);
905 ndmpdpphys = NDMPML4E;
906 ndmpdp = NDMPML4E * NPDEPG;
907 }
908 DMPDPphys = allocpages(firstaddr, ndmpdpphys);
909 ndm1g = 0;
910 if ((amd_feature & AMDID_PAGE1GB) != 0)
911 ndm1g = ptoa(Maxmem) >> PDPSHIFT;
912 if (ndm1g < ndmpdp)
913 DMPDphys = allocpages(firstaddr, ndmpdp - ndm1g);
914 dmaplimit = (vm_paddr_t)ndmpdp << PDPSHIFT;
915
916 /* Allocate pages */
917 KPML4phys = allocpages(firstaddr, 1);
918 KPDPphys = allocpages(firstaddr, NKPML4E);
919
920 /*
921 * Allocate the initial number of kernel page table pages required to
922 * bootstrap. We defer this until after all memory-size dependent
923 * allocations are done (e.g. direct map), so that we don't have to
924 * build in too much slop in our estimate.
925 *
926 * Note that when NKPML4E > 1, we have an empty page underneath
927 * all but the KPML4I'th one, so we need NKPML4E-1 extra (zeroed)
928 * pages. (pmap_enter requires a PD page to exist for each KPML4E.)
929 */
930 nkpt_init(*firstaddr);
931 nkpdpe = NKPDPE(nkpt);
932
933 KPTphys = allocpages(firstaddr, nkpt);
934 KPDphys = allocpages(firstaddr, nkpdpe);
935
936 /* Fill in the underlying page table pages */
937 /* Nominally read-only (but really R/W) from zero to physfree */
938 /* XXX not fully used, underneath 2M pages */
939 pt_p = (pt_entry_t *)KPTphys;
940 for (i = 0; ptoa(i) < *firstaddr; i++)
941 pt_p[i] = ptoa(i) | X86_PG_RW | X86_PG_V | pg_g;
942
943 /* Now map the page tables at their location within PTmap */
944 pd_p = (pd_entry_t *)KPDphys;
945 for (i = 0; i < nkpt; i++)
946 pd_p[i] = (KPTphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
947
948 /* Map from zero to end of allocations under 2M pages */
949 /* This replaces some of the KPTphys entries above */
950 for (i = 0; (i << PDRSHIFT) < *firstaddr; i++)
951 /* Preset PG_M and PG_A because demotion expects it. */
952 pd_p[i] = (i << PDRSHIFT) | X86_PG_RW | X86_PG_V | PG_PS |
953 X86_PG_M | X86_PG_A | pg_g;
954
955 /*
956 * Because we map the physical blocks in 2M pages, adjust firstaddr
957 * to record the physical blocks we've actually mapped into kernel
958 * virtual address space.
959 */
960 *firstaddr = round_2mpage(*firstaddr);
961
962 /* And connect up the PD to the PDP (leaving room for L4 pages) */
963 pdp_p = (pdp_entry_t *)(KPDPphys + ptoa(KPML4I - KPML4BASE));
964 for (i = 0; i < nkpdpe; i++)
965 pdp_p[i + KPDPI] = (KPDphys + ptoa(i)) | X86_PG_RW | X86_PG_V;
966
967 /*
968 * Now, set up the direct map region using 2MB and/or 1GB pages. If
969 * the end of physical memory is not aligned to a 1GB page boundary,
970 * then the residual physical memory is mapped with 2MB pages. Later,
971 * if pmap_mapdev{_attr}() uses the direct map for non-write-back
972 * memory, pmap_change_attr() will demote any 2MB or 1GB page mappings
973 * that are partially used.
974 */
975 pd_p = (pd_entry_t *)DMPDphys;
976 for (i = NPDEPG * ndm1g, j = 0; i < NPDEPG * ndmpdp; i++, j++) {
977 pd_p[j] = (vm_paddr_t)i << PDRSHIFT;
978 /* Preset PG_M and PG_A because demotion expects it. */
979 pd_p[j] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
980 X86_PG_M | X86_PG_A;
981 }
982 pdp_p = (pdp_entry_t *)DMPDPphys;
983 for (i = 0; i < ndm1g; i++) {
984 pdp_p[i] = (vm_paddr_t)i << PDPSHIFT;
985 /* Preset PG_M and PG_A because demotion expects it. */
986 pdp_p[i] |= X86_PG_RW | X86_PG_V | PG_PS | pg_g |
987 X86_PG_M | X86_PG_A;
988 }
989 for (j = 0; i < ndmpdp; i++, j++) {
990 pdp_p[i] = DMPDphys + ptoa(j);
991 pdp_p[i] |= X86_PG_RW | X86_PG_V;
992 }
993
994 /* And recursively map PML4 to itself in order to get PTmap */
995 p4_p = (pml4_entry_t *)KPML4phys;
996 p4_p[PML4PML4I] = KPML4phys;
997 p4_p[PML4PML4I] |= X86_PG_RW | X86_PG_V | pg_nx;
998
999 /* Connect the Direct Map slot(s) up to the PML4. */
1000 for (i = 0; i < ndmpdpphys; i++) {
1001 p4_p[DMPML4I + i] = DMPDPphys + ptoa(i);
1002 p4_p[DMPML4I + i] |= X86_PG_RW | X86_PG_V;
1003 }
1004
1005 /* Connect the KVA slots up to the PML4 */
1006 for (i = 0; i < NKPML4E; i++) {
1007 p4_p[KPML4BASE + i] = KPDPphys + ptoa(i);
1008 p4_p[KPML4BASE + i] |= X86_PG_RW | X86_PG_V;
1009 }
1010 }
1011
1012 /*
1013 * Bootstrap the system enough to run with virtual memory.
1014 *
1015 * On amd64 this is called after mapping has already been enabled
1016 * and just syncs the pmap module with what has already been done.
1017 * [We can't call it easily with mapping off since the kernel is not
1018 * mapped with PA == VA, hence we would have to relocate every address
1019 * from the linked base (virtual) address "KERNBASE" to the actual
1020 * (physical) address starting relative to 0]
1021 */
1022 void
1023 pmap_bootstrap(vm_paddr_t *firstaddr)
1024 {
1025 vm_offset_t va;
1026 pt_entry_t *pte;
1027 u_long res;
1028 int i;
1029
1030 KERNend = *firstaddr;
1031 res = atop(KERNend - (vm_paddr_t)kernphys);
1032
1033 if (!pti)
1034 pg_g = X86_PG_G;
1035
1036 /*
1037 * Create an initial set of page tables to run the kernel in.
1038 */
1039 create_pagetables(firstaddr);
1040
1041 /*
1042 * Add a physical memory segment (vm_phys_seg) corresponding to the
1043 * preallocated kernel page table pages so that vm_page structures
1044 * representing these pages will be created. The vm_page structures
1045 * are required for promotion of the corresponding kernel virtual
1046 * addresses to superpage mappings.
1047 */
1048 vm_phys_add_seg(KPTphys, KPTphys + ptoa(nkpt));
1049
1050 virtual_avail = (vm_offset_t) KERNBASE + *firstaddr;
1051 virtual_end = VM_MAX_KERNEL_ADDRESS;
1052
1053 /* XXX do %cr0 as well */
1054 load_cr4(rcr4() | CR4_PGE);
1055 load_cr3(KPML4phys);
1056 if (cpu_stdext_feature & CPUID_STDEXT_SMEP)
1057 load_cr4(rcr4() | CR4_SMEP);
1058
1059 /*
1060 * Initialize the kernel pmap (which is statically allocated).
1061 * Count bootstrap data as being resident in case any of this data is
1062 * later unmapped (using pmap_remove()) and freed.
1063 */
1064 PMAP_LOCK_INIT(kernel_pmap);
1065 kernel_pmap->pm_pml4 = (pdp_entry_t *)PHYS_TO_DMAP(KPML4phys);
1066 kernel_pmap->pm_cr3 = KPML4phys;
1067 kernel_pmap->pm_ucr3 = PMAP_NO_CR3;
1068 CPU_FILL(&kernel_pmap->pm_active); /* don't allow deactivation */
1069 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
1070 kernel_pmap->pm_stats.resident_count = res;
1071 kernel_pmap->pm_flags = pmap_flags;
1072
1073 /*
1074 * Initialize the TLB invalidations generation number lock.
1075 */
1076 mtx_init(&invl_gen_mtx, "invlgn", NULL, MTX_DEF);
1077
1078 /*
1079 * Reserve some special page table entries/VA space for temporary
1080 * mapping of pages.
1081 */
1082 #define SYSMAP(c, p, v, n) \
1083 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
1084
1085 va = virtual_avail;
1086 pte = vtopte(va);
1087
1088 /*
1089 * Crashdump maps. The first page is reused as CMAP1 for the
1090 * memory test.
1091 */
1092 SYSMAP(caddr_t, CMAP1, crashdumpmap, MAXDUMPPGS)
1093 CADDR1 = crashdumpmap;
1094
1095 virtual_avail = va;
1096
1097 /*
1098 * Initialize the PAT MSR.
1099 * pmap_init_pat() clears and sets CR4_PGE, which, as a
1100 * side-effect, invalidates stale PG_G TLB entries that might
1101 * have been created in our pre-boot environment.
1102 */
1103 pmap_init_pat();
1104
1105 /* Initialize TLB Context Id. */
1106 TUNABLE_INT_FETCH("vm.pmap.pcid_enabled", &pmap_pcid_enabled);
1107 if ((cpu_feature2 & CPUID2_PCID) != 0 && pmap_pcid_enabled) {
1108 /* Check for INVPCID support */
1109 invpcid_works = (cpu_stdext_feature & CPUID_STDEXT_INVPCID)
1110 != 0;
1111 for (i = 0; i < MAXCPU; i++) {
1112 kernel_pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN;
1113 kernel_pmap->pm_pcids[i].pm_gen = 1;
1114 }
1115
1116 /*
1117 * PMAP_PCID_KERN + 1 is used for initialization of
1118 * proc0 pmap. The pmap' pcid state might be used by
1119 * EFIRT entry before first context switch, so it
1120 * needs to be valid.
1121 */
1122 PCPU_SET(pcid_next, PMAP_PCID_KERN + 2);
1123 PCPU_SET(pcid_gen, 1);
1124
1125 /*
1126 * pcpu area for APs is zeroed during AP startup.
1127 * pc_pcid_next and pc_pcid_gen are initialized by AP
1128 * during pcpu setup.
1129 */
1130 load_cr4(rcr4() | CR4_PCIDE);
1131 } else {
1132 pmap_pcid_enabled = 0;
1133 }
1134 }
1135
1136 /*
1137 * Setup the PAT MSR.
1138 */
1139 void
1140 pmap_init_pat(void)
1141 {
1142 int pat_table[PAT_INDEX_SIZE];
1143 uint64_t pat_msr;
1144 u_long cr0, cr4;
1145 int i;
1146
1147 /* Bail if this CPU doesn't implement PAT. */
1148 if ((cpu_feature & CPUID_PAT) == 0)
1149 panic("no PAT??");
1150
1151 /* Set default PAT index table. */
1152 for (i = 0; i < PAT_INDEX_SIZE; i++)
1153 pat_table[i] = -1;
1154 pat_table[PAT_WRITE_BACK] = 0;
1155 pat_table[PAT_WRITE_THROUGH] = 1;
1156 pat_table[PAT_UNCACHEABLE] = 3;
1157 pat_table[PAT_WRITE_COMBINING] = 3;
1158 pat_table[PAT_WRITE_PROTECTED] = 3;
1159 pat_table[PAT_UNCACHED] = 3;
1160
1161 /* Initialize default PAT entries. */
1162 pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
1163 PAT_VALUE(1, PAT_WRITE_THROUGH) |
1164 PAT_VALUE(2, PAT_UNCACHED) |
1165 PAT_VALUE(3, PAT_UNCACHEABLE) |
1166 PAT_VALUE(4, PAT_WRITE_BACK) |
1167 PAT_VALUE(5, PAT_WRITE_THROUGH) |
1168 PAT_VALUE(6, PAT_UNCACHED) |
1169 PAT_VALUE(7, PAT_UNCACHEABLE);
1170
1171 if (pat_works) {
1172 /*
1173 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
1174 * Program 5 and 6 as WP and WC.
1175 * Leave 4 and 7 as WB and UC.
1176 */
1177 pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
1178 pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
1179 PAT_VALUE(6, PAT_WRITE_COMBINING);
1180 pat_table[PAT_UNCACHED] = 2;
1181 pat_table[PAT_WRITE_PROTECTED] = 5;
1182 pat_table[PAT_WRITE_COMBINING] = 6;
1183 } else {
1184 /*
1185 * Just replace PAT Index 2 with WC instead of UC-.
1186 */
1187 pat_msr &= ~PAT_MASK(2);
1188 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
1189 pat_table[PAT_WRITE_COMBINING] = 2;
1190 }
1191
1192 /* Disable PGE. */
1193 cr4 = rcr4();
1194 load_cr4(cr4 & ~CR4_PGE);
1195
1196 /* Disable caches (CD = 1, NW = 0). */
1197 cr0 = rcr0();
1198 load_cr0((cr0 & ~CR0_NW) | CR0_CD);
1199
1200 /* Flushes caches and TLBs. */
1201 wbinvd();
1202 invltlb();
1203
1204 /* Update PAT and index table. */
1205 wrmsr(MSR_PAT, pat_msr);
1206 for (i = 0; i < PAT_INDEX_SIZE; i++)
1207 pat_index[i] = pat_table[i];
1208
1209 /* Flush caches and TLBs again. */
1210 wbinvd();
1211 invltlb();
1212
1213 /* Restore caches and PGE. */
1214 load_cr0(cr0);
1215 load_cr4(cr4);
1216 }
1217
1218 /*
1219 * Initialize a vm_page's machine-dependent fields.
1220 */
1221 void
1222 pmap_page_init(vm_page_t m)
1223 {
1224
1225 TAILQ_INIT(&m->md.pv_list);
1226 m->md.pat_mode = PAT_WRITE_BACK;
1227 }
1228
1229 static int pmap_allow_2m_x_ept;
1230 SYSCTL_INT(_vm_pmap, OID_AUTO, allow_2m_x_ept, CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
1231 &pmap_allow_2m_x_ept, 0,
1232 "Allow executable superpage mappings in EPT");
1233
1234 void
1235 pmap_allow_2m_x_ept_recalculate(void)
1236 {
1237 /*
1238 * SKL002, SKL012S. Since the EPT format is only used by
1239 * Intel CPUs, the vendor check is merely a formality.
1240 */
1241 if (!(cpu_vendor_id != CPU_VENDOR_INTEL ||
1242 (cpu_ia32_arch_caps & IA32_ARCH_CAP_IF_PSCHANGE_MC_NO) != 0 ||
1243 (CPUID_TO_FAMILY(cpu_id) == 0x6 &&
1244 (CPUID_TO_MODEL(cpu_id) == 0x26 || /* Atoms */
1245 CPUID_TO_MODEL(cpu_id) == 0x27 ||
1246 CPUID_TO_MODEL(cpu_id) == 0x35 ||
1247 CPUID_TO_MODEL(cpu_id) == 0x36 ||
1248 CPUID_TO_MODEL(cpu_id) == 0x37 ||
1249 CPUID_TO_MODEL(cpu_id) == 0x86 ||
1250 CPUID_TO_MODEL(cpu_id) == 0x1c ||
1251 CPUID_TO_MODEL(cpu_id) == 0x4a ||
1252 CPUID_TO_MODEL(cpu_id) == 0x4c ||
1253 CPUID_TO_MODEL(cpu_id) == 0x4d ||
1254 CPUID_TO_MODEL(cpu_id) == 0x5a ||
1255 CPUID_TO_MODEL(cpu_id) == 0x5c ||
1256 CPUID_TO_MODEL(cpu_id) == 0x5d ||
1257 CPUID_TO_MODEL(cpu_id) == 0x5f ||
1258 CPUID_TO_MODEL(cpu_id) == 0x6e ||
1259 CPUID_TO_MODEL(cpu_id) == 0x7a ||
1260 CPUID_TO_MODEL(cpu_id) == 0x57 || /* Knights */
1261 CPUID_TO_MODEL(cpu_id) == 0x85))))
1262 pmap_allow_2m_x_ept = 1;
1263 TUNABLE_INT_FETCH("hw.allow_2m_x_ept", &pmap_allow_2m_x_ept);
1264 }
1265
1266 static bool
1267 pmap_allow_2m_x_page(pmap_t pmap, bool executable)
1268 {
1269
1270 return (pmap->pm_type != PT_EPT || !executable ||
1271 !pmap_allow_2m_x_ept);
1272 }
1273
1274 /*
1275 * Initialize the pmap module.
1276 * Called by vm_init, to initialize any structures that the pmap
1277 * system needs to map virtual memory.
1278 */
1279 void
1280 pmap_init(void)
1281 {
1282 struct pmap_preinit_mapping *ppim;
1283 vm_page_t mpte;
1284 vm_size_t s;
1285 int error, i, pv_npg, ret, skz63;
1286
1287 /* L1TF, reserve page @0 unconditionally */
1288 vm_page_blacklist_add(0, bootverbose);
1289
1290 /* Detect bare-metal Skylake Server and Skylake-X. */
1291 if (vm_guest == VM_GUEST_NO && cpu_vendor_id == CPU_VENDOR_INTEL &&
1292 CPUID_TO_FAMILY(cpu_id) == 0x6 && CPUID_TO_MODEL(cpu_id) == 0x55) {
1293 /*
1294 * Skylake-X errata SKZ63. Processor May Hang When
1295 * Executing Code In an HLE Transaction Region between
1296 * 40000000H and 403FFFFFH.
1297 *
1298 * Mark the pages in the range as preallocated. It
1299 * seems to be impossible to distinguish between
1300 * Skylake Server and Skylake X.
1301 */
1302 skz63 = 1;
1303 TUNABLE_INT_FETCH("hw.skz63_enable", &skz63);
1304 if (skz63 != 0) {
1305 if (bootverbose)
1306 printf("SKZ63: skipping 4M RAM starting "
1307 "at physical 1G\n");
1308 for (i = 0; i < atop(0x400000); i++) {
1309 ret = vm_page_blacklist_add(0x40000000 +
1310 ptoa(i), FALSE);
1311 if (!ret && bootverbose)
1312 printf("page at %#lx already used\n",
1313 0x40000000 + ptoa(i));
1314 }
1315 }
1316 }
1317
1318 /* IFU */
1319 pmap_allow_2m_x_ept_recalculate();
1320
1321 /*
1322 * Initialize the vm page array entries for the kernel pmap's
1323 * page table pages.
1324 */
1325 PMAP_LOCK(kernel_pmap);
1326 for (i = 0; i < nkpt; i++) {
1327 mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
1328 KASSERT(mpte >= vm_page_array &&
1329 mpte < &vm_page_array[vm_page_array_size],
1330 ("pmap_init: page table page is out of range"));
1331 mpte->pindex = pmap_pde_pindex(KERNBASE) + i;
1332 mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
1333 mpte->wire_count = 1;
1334 if (i << PDRSHIFT < KERNend &&
1335 pmap_insert_pt_page(kernel_pmap, mpte))
1336 panic("pmap_init: pmap_insert_pt_page failed");
1337 }
1338 PMAP_UNLOCK(kernel_pmap);
1339 atomic_add_int(&vm_cnt.v_wire_count, nkpt);
1340
1341 /*
1342 * If the kernel is running on a virtual machine, then it must assume
1343 * that MCA is enabled by the hypervisor. Moreover, the kernel must
1344 * be prepared for the hypervisor changing the vendor and family that
1345 * are reported by CPUID. Consequently, the workaround for AMD Family
1346 * 10h Erratum 383 is enabled if the processor's feature set does not
1347 * include at least one feature that is only supported by older Intel
1348 * or newer AMD processors.
1349 */
1350 if (vm_guest != VM_GUEST_NO && (cpu_feature & CPUID_SS) == 0 &&
1351 (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
1352 CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
1353 AMDID2_FMA4)) == 0)
1354 workaround_erratum383 = 1;
1355
1356 /*
1357 * Are large page mappings enabled?
1358 */
1359 TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
1360 if (pg_ps_enabled) {
1361 KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
1362 ("pmap_init: can't assign to pagesizes[1]"));
1363 pagesizes[1] = NBPDR;
1364 }
1365
1366 /*
1367 * Initialize the pv chunk list mutex.
1368 */
1369 mtx_init(&pv_chunks_mutex, "pmap pv chunk list", NULL, MTX_DEF);
1370
1371 /*
1372 * Initialize the pool of pv list locks.
1373 */
1374 for (i = 0; i < NPV_LIST_LOCKS; i++)
1375 rw_init(&pv_list_locks[i], "pmap pv list");
1376
1377 /*
1378 * Calculate the size of the pv head table for superpages.
1379 */
1380 pv_npg = howmany(vm_phys_segs[vm_phys_nsegs - 1].end, NBPDR);
1381
1382 /*
1383 * Allocate memory for the pv head table for superpages.
1384 */
1385 s = (vm_size_t)(pv_npg * sizeof(struct md_page));
1386 s = round_page(s);
1387 pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
1388 M_WAITOK | M_ZERO);
1389 for (i = 0; i < pv_npg; i++)
1390 TAILQ_INIT(&pv_table[i].pv_list);
1391 TAILQ_INIT(&pv_dummy.pv_list);
1392
1393 pmap_initialized = 1;
1394 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
1395 ppim = pmap_preinit_mapping + i;
1396 if (ppim->va == 0)
1397 continue;
1398 /* Make the direct map consistent */
1399 if (ppim->pa < dmaplimit && ppim->pa + ppim->sz <= dmaplimit) {
1400 (void)pmap_change_attr(PHYS_TO_DMAP(ppim->pa),
1401 ppim->sz, ppim->mode);
1402 }
1403 if (!bootverbose)
1404 continue;
1405 printf("PPIM %u: PA=%#lx, VA=%#lx, size=%#lx, mode=%#x\n", i,
1406 ppim->pa, ppim->va, ppim->sz, ppim->mode);
1407 }
1408
1409 mtx_init(&qframe_mtx, "qfrmlk", NULL, MTX_SPIN);
1410 error = vmem_alloc(kernel_arena, PAGE_SIZE, M_BESTFIT | M_WAITOK,
1411 (vmem_addr_t *)&qframe);
1412 if (error != 0)
1413 panic("qframe allocation failed");
1414 }
1415
1416 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
1417 "2MB page mapping counters");
1418
1419 static u_long pmap_pde_demotions;
1420 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
1421 &pmap_pde_demotions, 0, "2MB page demotions");
1422
1423 static u_long pmap_pde_mappings;
1424 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
1425 &pmap_pde_mappings, 0, "2MB page mappings");
1426
1427 static u_long pmap_pde_p_failures;
1428 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
1429 &pmap_pde_p_failures, 0, "2MB page promotion failures");
1430
1431 static u_long pmap_pde_promotions;
1432 SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
1433 &pmap_pde_promotions, 0, "2MB page promotions");
1434
1435 static SYSCTL_NODE(_vm_pmap, OID_AUTO, pdpe, CTLFLAG_RD, 0,
1436 "1GB page mapping counters");
1437
1438 static u_long pmap_pdpe_demotions;
1439 SYSCTL_ULONG(_vm_pmap_pdpe, OID_AUTO, demotions, CTLFLAG_RD,
1440 &pmap_pdpe_demotions, 0, "1GB page demotions");
1441
1442 /***************************************************
1443 * Low level helper routines.....
1444 ***************************************************/
1445
1446 static pt_entry_t
1447 pmap_swap_pat(pmap_t pmap, pt_entry_t entry)
1448 {
1449 int x86_pat_bits = X86_PG_PTE_PAT | X86_PG_PDE_PAT;
1450
1451 switch (pmap->pm_type) {
1452 case PT_X86:
1453 case PT_RVI:
1454 /* Verify that both PAT bits are not set at the same time */
1455 KASSERT((entry & x86_pat_bits) != x86_pat_bits,
1456 ("Invalid PAT bits in entry %#lx", entry));
1457
1458 /* Swap the PAT bits if one of them is set */
1459 if ((entry & x86_pat_bits) != 0)
1460 entry ^= x86_pat_bits;
1461 break;
1462 case PT_EPT:
1463 /*
1464 * Nothing to do - the memory attributes are represented
1465 * the same way for regular pages and superpages.
1466 */
1467 break;
1468 default:
1469 panic("pmap_switch_pat_bits: bad pm_type %d", pmap->pm_type);
1470 }
1471
1472 return (entry);
1473 }
1474
1475 /*
1476 * Determine the appropriate bits to set in a PTE or PDE for a specified
1477 * caching mode.
1478 */
1479 int
1480 pmap_cache_bits(pmap_t pmap, int mode, boolean_t is_pde)
1481 {
1482 int cache_bits, pat_flag, pat_idx;
1483
1484 if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
1485 panic("Unknown caching mode %d\n", mode);
1486
1487 switch (pmap->pm_type) {
1488 case PT_X86:
1489 case PT_RVI:
1490 /* The PAT bit is different for PTE's and PDE's. */
1491 pat_flag = is_pde ? X86_PG_PDE_PAT : X86_PG_PTE_PAT;
1492
1493 /* Map the caching mode to a PAT index. */
1494 pat_idx = pat_index[mode];
1495
1496 /* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
1497 cache_bits = 0;
1498 if (pat_idx & 0x4)
1499 cache_bits |= pat_flag;
1500 if (pat_idx & 0x2)
1501 cache_bits |= PG_NC_PCD;
1502 if (pat_idx & 0x1)
1503 cache_bits |= PG_NC_PWT;
1504 break;
1505
1506 case PT_EPT:
1507 cache_bits = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(mode);
1508 break;
1509
1510 default:
1511 panic("unsupported pmap type %d", pmap->pm_type);
1512 }
1513
1514 return (cache_bits);
1515 }
1516
1517 static int
1518 pmap_cache_mask(pmap_t pmap, boolean_t is_pde)
1519 {
1520 int mask;
1521
1522 switch (pmap->pm_type) {
1523 case PT_X86:
1524 case PT_RVI:
1525 mask = is_pde ? X86_PG_PDE_CACHE : X86_PG_PTE_CACHE;
1526 break;
1527 case PT_EPT:
1528 mask = EPT_PG_IGNORE_PAT | EPT_PG_MEMORY_TYPE(0x7);
1529 break;
1530 default:
1531 panic("pmap_cache_mask: invalid pm_type %d", pmap->pm_type);
1532 }
1533
1534 return (mask);
1535 }
1536
1537 bool
1538 pmap_ps_enabled(pmap_t pmap)
1539 {
1540
1541 return (pg_ps_enabled && (pmap->pm_flags & PMAP_PDE_SUPERPAGE) != 0);
1542 }
1543
1544 static void
1545 pmap_update_pde_store(pmap_t pmap, pd_entry_t *pde, pd_entry_t newpde)
1546 {
1547
1548 switch (pmap->pm_type) {
1549 case PT_X86:
1550 break;
1551 case PT_RVI:
1552 case PT_EPT:
1553 /*
1554 * XXX
1555 * This is a little bogus since the generation number is
1556 * supposed to be bumped up when a region of the address
1557 * space is invalidated in the page tables.
1558 *
1559 * In this case the old PDE entry is valid but yet we want
1560 * to make sure that any mappings using the old entry are
1561 * invalidated in the TLB.
1562 *
1563 * The reason this works as expected is because we rendezvous
1564 * "all" host cpus and force any vcpu context to exit as a
1565 * side-effect.
1566 */
1567 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1568 break;
1569 default:
1570 panic("pmap_update_pde_store: bad pm_type %d", pmap->pm_type);
1571 }
1572 pde_store(pde, newpde);
1573 }
1574
1575 /*
1576 * After changing the page size for the specified virtual address in the page
1577 * table, flush the corresponding entries from the processor's TLB. Only the
1578 * calling processor's TLB is affected.
1579 *
1580 * The calling thread must be pinned to a processor.
1581 */
1582 static void
1583 pmap_update_pde_invalidate(pmap_t pmap, vm_offset_t va, pd_entry_t newpde)
1584 {
1585 pt_entry_t PG_G;
1586
1587 if (pmap_type_guest(pmap))
1588 return;
1589
1590 KASSERT(pmap->pm_type == PT_X86,
1591 ("pmap_update_pde_invalidate: invalid type %d", pmap->pm_type));
1592
1593 PG_G = pmap_global_bit(pmap);
1594
1595 if ((newpde & PG_PS) == 0)
1596 /* Demotion: flush a specific 2MB page mapping. */
1597 invlpg(va);
1598 else if ((newpde & PG_G) == 0)
1599 /*
1600 * Promotion: flush every 4KB page mapping from the TLB
1601 * because there are too many to flush individually.
1602 */
1603 invltlb();
1604 else {
1605 /*
1606 * Promotion: flush every 4KB page mapping from the TLB,
1607 * including any global (PG_G) mappings.
1608 */
1609 invltlb_glob();
1610 }
1611 }
1612 #ifdef SMP
1613
1614 /*
1615 * For SMP, these functions have to use the IPI mechanism for coherence.
1616 *
1617 * N.B.: Before calling any of the following TLB invalidation functions,
1618 * the calling processor must ensure that all stores updating a non-
1619 * kernel page table are globally performed. Otherwise, another
1620 * processor could cache an old, pre-update entry without being
1621 * invalidated. This can happen one of two ways: (1) The pmap becomes
1622 * active on another processor after its pm_active field is checked by
1623 * one of the following functions but before a store updating the page
1624 * table is globally performed. (2) The pmap becomes active on another
1625 * processor before its pm_active field is checked but due to
1626 * speculative loads one of the following functions stills reads the
1627 * pmap as inactive on the other processor.
1628 *
1629 * The kernel page table is exempt because its pm_active field is
1630 * immutable. The kernel page table is always active on every
1631 * processor.
1632 */
1633
1634 /*
1635 * Interrupt the cpus that are executing in the guest context.
1636 * This will force the vcpu to exit and the cached EPT mappings
1637 * will be invalidated by the host before the next vmresume.
1638 */
1639 static __inline void
1640 pmap_invalidate_ept(pmap_t pmap)
1641 {
1642 int ipinum;
1643
1644 sched_pin();
1645 KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1646 ("pmap_invalidate_ept: absurd pm_active"));
1647
1648 /*
1649 * The TLB mappings associated with a vcpu context are not
1650 * flushed each time a different vcpu is chosen to execute.
1651 *
1652 * This is in contrast with a process's vtop mappings that
1653 * are flushed from the TLB on each context switch.
1654 *
1655 * Therefore we need to do more than just a TLB shootdown on
1656 * the active cpus in 'pmap->pm_active'. To do this we keep
1657 * track of the number of invalidations performed on this pmap.
1658 *
1659 * Each vcpu keeps a cache of this counter and compares it
1660 * just before a vmresume. If the counter is out-of-date an
1661 * invept will be done to flush stale mappings from the TLB.
1662 */
1663 atomic_add_acq_long(&pmap->pm_eptgen, 1);
1664
1665 /*
1666 * Force the vcpu to exit and trap back into the hypervisor.
1667 */
1668 ipinum = pmap->pm_flags & PMAP_NESTED_IPIMASK;
1669 ipi_selected(pmap->pm_active, ipinum);
1670 sched_unpin();
1671 }
1672
1673 void
1674 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1675 {
1676 cpuset_t *mask;
1677 struct invpcid_descr d;
1678 uint64_t kcr3, ucr3;
1679 uint32_t pcid;
1680 u_int cpuid, i;
1681
1682 if (pmap_type_guest(pmap)) {
1683 pmap_invalidate_ept(pmap);
1684 return;
1685 }
1686
1687 KASSERT(pmap->pm_type == PT_X86,
1688 ("pmap_invalidate_page: invalid type %d", pmap->pm_type));
1689
1690 sched_pin();
1691 if (pmap == kernel_pmap) {
1692 invlpg(va);
1693 mask = &all_cpus;
1694 } else {
1695 cpuid = PCPU_GET(cpuid);
1696 if (pmap == PCPU_GET(curpmap)) {
1697 invlpg(va);
1698 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1699 /*
1700 * Disable context switching. pm_pcid
1701 * is recalculated on switch, which
1702 * might make us use wrong pcid below.
1703 */
1704 critical_enter();
1705 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1706
1707 if (invpcid_works) {
1708 d.pcid = pcid | PMAP_PCID_USER_PT;
1709 d.pad = 0;
1710 d.addr = va;
1711 invpcid(&d, INVPCID_ADDR);
1712 } else {
1713 kcr3 = pmap->pm_cr3 | pcid |
1714 CR3_PCID_SAVE;
1715 ucr3 = pmap->pm_ucr3 | pcid |
1716 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1717 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
1718 }
1719 critical_exit();
1720 }
1721 } else if (pmap_pcid_enabled)
1722 pmap->pm_pcids[cpuid].pm_gen = 0;
1723 if (pmap_pcid_enabled) {
1724 CPU_FOREACH(i) {
1725 if (cpuid != i)
1726 pmap->pm_pcids[i].pm_gen = 0;
1727 }
1728
1729 /*
1730 * The fence is between stores to pm_gen and the read of
1731 * the pm_active mask. We need to ensure that it is
1732 * impossible for us to miss the bit update in pm_active
1733 * and simultaneously observe a non-zero pm_gen in
1734 * pmap_activate_sw(), otherwise TLB update is missed.
1735 * Without the fence, IA32 allows such an outcome.
1736 * Note that pm_active is updated by a locked operation,
1737 * which provides the reciprocal fence.
1738 */
1739 atomic_thread_fence_seq_cst();
1740 }
1741 mask = &pmap->pm_active;
1742 }
1743 smp_masked_invlpg(*mask, va, pmap);
1744 sched_unpin();
1745 }
1746
1747 /* 4k PTEs -- Chosen to exceed the total size of Broadwell L2 TLB */
1748 #define PMAP_INVLPG_THRESHOLD (4 * 1024 * PAGE_SIZE)
1749
1750 void
1751 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1752 {
1753 cpuset_t *mask;
1754 struct invpcid_descr d;
1755 vm_offset_t addr;
1756 uint64_t kcr3, ucr3;
1757 uint32_t pcid;
1758 u_int cpuid, i;
1759
1760 if (eva - sva >= PMAP_INVLPG_THRESHOLD) {
1761 pmap_invalidate_all(pmap);
1762 return;
1763 }
1764
1765 if (pmap_type_guest(pmap)) {
1766 pmap_invalidate_ept(pmap);
1767 return;
1768 }
1769
1770 KASSERT(pmap->pm_type == PT_X86,
1771 ("pmap_invalidate_range: invalid type %d", pmap->pm_type));
1772
1773 sched_pin();
1774 cpuid = PCPU_GET(cpuid);
1775 if (pmap == kernel_pmap) {
1776 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1777 invlpg(addr);
1778 mask = &all_cpus;
1779 } else {
1780 if (pmap == PCPU_GET(curpmap)) {
1781 for (addr = sva; addr < eva; addr += PAGE_SIZE)
1782 invlpg(addr);
1783 if (pmap_pcid_enabled && pmap->pm_ucr3 != PMAP_NO_CR3) {
1784 critical_enter();
1785 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1786 if (invpcid_works) {
1787 d.pcid = pcid | PMAP_PCID_USER_PT;
1788 d.pad = 0;
1789 d.addr = sva;
1790 for (; d.addr < eva; d.addr +=
1791 PAGE_SIZE)
1792 invpcid(&d, INVPCID_ADDR);
1793 } else {
1794 kcr3 = pmap->pm_cr3 | pcid |
1795 CR3_PCID_SAVE;
1796 ucr3 = pmap->pm_ucr3 | pcid |
1797 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
1798 pmap_pti_pcid_invlrng(ucr3, kcr3, sva,
1799 eva);
1800 }
1801 critical_exit();
1802 }
1803 } else if (pmap_pcid_enabled) {
1804 pmap->pm_pcids[cpuid].pm_gen = 0;
1805 }
1806 if (pmap_pcid_enabled) {
1807 CPU_FOREACH(i) {
1808 if (cpuid != i)
1809 pmap->pm_pcids[i].pm_gen = 0;
1810 }
1811 /* See the comment in pmap_invalidate_page(). */
1812 atomic_thread_fence_seq_cst();
1813 }
1814 mask = &pmap->pm_active;
1815 }
1816 smp_masked_invlpg_range(*mask, sva, eva, pmap);
1817 sched_unpin();
1818 }
1819
1820 void
1821 pmap_invalidate_all(pmap_t pmap)
1822 {
1823 cpuset_t *mask;
1824 struct invpcid_descr d;
1825 uint64_t kcr3, ucr3;
1826 uint32_t pcid;
1827 u_int cpuid, i;
1828
1829 if (pmap_type_guest(pmap)) {
1830 pmap_invalidate_ept(pmap);
1831 return;
1832 }
1833
1834 KASSERT(pmap->pm_type == PT_X86,
1835 ("pmap_invalidate_all: invalid type %d", pmap->pm_type));
1836
1837 sched_pin();
1838 if (pmap == kernel_pmap) {
1839 if (pmap_pcid_enabled && invpcid_works) {
1840 bzero(&d, sizeof(d));
1841 invpcid(&d, INVPCID_CTXGLOB);
1842 } else {
1843 invltlb_glob();
1844 }
1845 mask = &all_cpus;
1846 } else {
1847 cpuid = PCPU_GET(cpuid);
1848 if (pmap == PCPU_GET(curpmap)) {
1849 if (pmap_pcid_enabled) {
1850 critical_enter();
1851 pcid = pmap->pm_pcids[cpuid].pm_pcid;
1852 if (invpcid_works) {
1853 d.pcid = pcid;
1854 d.pad = 0;
1855 d.addr = 0;
1856 invpcid(&d, INVPCID_CTX);
1857 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
1858 d.pcid |= PMAP_PCID_USER_PT;
1859 invpcid(&d, INVPCID_CTX);
1860 }
1861 } else {
1862 kcr3 = pmap->pm_cr3 | pcid;
1863 ucr3 = pmap->pm_ucr3;
1864 if (ucr3 != PMAP_NO_CR3) {
1865 ucr3 |= pcid | PMAP_PCID_USER_PT;
1866 pmap_pti_pcid_invalidate(ucr3,
1867 kcr3);
1868 } else {
1869 load_cr3(kcr3);
1870 }
1871 }
1872 critical_exit();
1873 } else {
1874 invltlb();
1875 }
1876 } else if (pmap_pcid_enabled) {
1877 pmap->pm_pcids[cpuid].pm_gen = 0;
1878 }
1879 if (pmap_pcid_enabled) {
1880 CPU_FOREACH(i) {
1881 if (cpuid != i)
1882 pmap->pm_pcids[i].pm_gen = 0;
1883 }
1884 /* See the comment in pmap_invalidate_page(). */
1885 atomic_thread_fence_seq_cst();
1886 }
1887 mask = &pmap->pm_active;
1888 }
1889 smp_masked_invltlb(*mask, pmap);
1890 sched_unpin();
1891 }
1892
1893 void
1894 pmap_invalidate_cache(void)
1895 {
1896
1897 sched_pin();
1898 wbinvd();
1899 smp_cache_flush();
1900 sched_unpin();
1901 }
1902
1903 struct pde_action {
1904 cpuset_t invalidate; /* processors that invalidate their TLB */
1905 pmap_t pmap;
1906 vm_offset_t va;
1907 pd_entry_t *pde;
1908 pd_entry_t newpde;
1909 u_int store; /* processor that updates the PDE */
1910 };
1911
1912 static void
1913 pmap_update_pde_action(void *arg)
1914 {
1915 struct pde_action *act = arg;
1916
1917 if (act->store == PCPU_GET(cpuid))
1918 pmap_update_pde_store(act->pmap, act->pde, act->newpde);
1919 }
1920
1921 static void
1922 pmap_update_pde_teardown(void *arg)
1923 {
1924 struct pde_action *act = arg;
1925
1926 if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1927 pmap_update_pde_invalidate(act->pmap, act->va, act->newpde);
1928 }
1929
1930 /*
1931 * Change the page size for the specified virtual address in a way that
1932 * prevents any possibility of the TLB ever having two entries that map the
1933 * same virtual address using different page sizes. This is the recommended
1934 * workaround for Erratum 383 on AMD Family 10h processors. It prevents a
1935 * machine check exception for a TLB state that is improperly diagnosed as a
1936 * hardware error.
1937 */
1938 static void
1939 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1940 {
1941 struct pde_action act;
1942 cpuset_t active, other_cpus;
1943 u_int cpuid;
1944
1945 sched_pin();
1946 cpuid = PCPU_GET(cpuid);
1947 other_cpus = all_cpus;
1948 CPU_CLR(cpuid, &other_cpus);
1949 if (pmap == kernel_pmap || pmap_type_guest(pmap))
1950 active = all_cpus;
1951 else {
1952 active = pmap->pm_active;
1953 }
1954 if (CPU_OVERLAP(&active, &other_cpus)) {
1955 act.store = cpuid;
1956 act.invalidate = active;
1957 act.va = va;
1958 act.pmap = pmap;
1959 act.pde = pde;
1960 act.newpde = newpde;
1961 CPU_SET(cpuid, &active);
1962 smp_rendezvous_cpus(active,
1963 smp_no_rendezvous_barrier, pmap_update_pde_action,
1964 pmap_update_pde_teardown, &act);
1965 } else {
1966 pmap_update_pde_store(pmap, pde, newpde);
1967 if (CPU_ISSET(cpuid, &active))
1968 pmap_update_pde_invalidate(pmap, va, newpde);
1969 }
1970 sched_unpin();
1971 }
1972 #else /* !SMP */
1973 /*
1974 * Normal, non-SMP, invalidation functions.
1975 */
1976 void
1977 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1978 {
1979 struct invpcid_descr d;
1980 uint64_t kcr3, ucr3;
1981 uint32_t pcid;
1982
1983 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
1984 pmap->pm_eptgen++;
1985 return;
1986 }
1987 KASSERT(pmap->pm_type == PT_X86,
1988 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
1989
1990 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
1991 invlpg(va);
1992 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
1993 pmap->pm_ucr3 != PMAP_NO_CR3) {
1994 critical_enter();
1995 pcid = pmap->pm_pcids[0].pm_pcid;
1996 if (invpcid_works) {
1997 d.pcid = pcid | PMAP_PCID_USER_PT;
1998 d.pad = 0;
1999 d.addr = va;
2000 invpcid(&d, INVPCID_ADDR);
2001 } else {
2002 kcr3 = pmap->pm_cr3 | pcid | CR3_PCID_SAVE;
2003 ucr3 = pmap->pm_ucr3 | pcid |
2004 PMAP_PCID_USER_PT | CR3_PCID_SAVE;
2005 pmap_pti_pcid_invlpg(ucr3, kcr3, va);
2006 }
2007 critical_exit();
2008 }
2009 } else if (pmap_pcid_enabled)
2010 pmap->pm_pcids[0].pm_gen = 0;
2011 }
2012
2013 void
2014 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2015 {
2016 struct invpcid_descr d;
2017 vm_offset_t addr;
2018 uint64_t kcr3, ucr3;
2019
2020 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
2021 pmap->pm_eptgen++;
2022 return;
2023 }
2024 KASSERT(pmap->pm_type == PT_X86,
2025 ("pmap_invalidate_range: unknown type %d", pmap->pm_type));
2026
2027 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap)) {
2028 for (addr = sva; addr < eva; addr += PAGE_SIZE)
2029 invlpg(addr);
2030 if (pmap == PCPU_GET(curpmap) && pmap_pcid_enabled &&
2031 pmap->pm_ucr3 != PMAP_NO_CR3) {
2032 critical_enter();
2033 if (invpcid_works) {
2034 d.pcid = pmap->pm_pcids[0].pm_pcid |
2035 PMAP_PCID_USER_PT;
2036 d.pad = 0;
2037 d.addr = sva;
2038 for (; d.addr < eva; d.addr += PAGE_SIZE)
2039 invpcid(&d, INVPCID_ADDR);
2040 } else {
2041 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].
2042 pm_pcid | CR3_PCID_SAVE;
2043 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[0].
2044 pm_pcid | PMAP_PCID_USER_PT | CR3_PCID_SAVE;
2045 pmap_pti_pcid_invlrng(ucr3, kcr3, sva, eva);
2046 }
2047 critical_exit();
2048 }
2049 } else if (pmap_pcid_enabled) {
2050 pmap->pm_pcids[0].pm_gen = 0;
2051 }
2052 }
2053
2054 void
2055 pmap_invalidate_all(pmap_t pmap)
2056 {
2057 struct invpcid_descr d;
2058 uint64_t kcr3, ucr3;
2059
2060 if (pmap->pm_type == PT_RVI || pmap->pm_type == PT_EPT) {
2061 pmap->pm_eptgen++;
2062 return;
2063 }
2064 KASSERT(pmap->pm_type == PT_X86,
2065 ("pmap_invalidate_all: unknown type %d", pmap->pm_type));
2066
2067 if (pmap == kernel_pmap) {
2068 if (pmap_pcid_enabled && invpcid_works) {
2069 bzero(&d, sizeof(d));
2070 invpcid(&d, INVPCID_CTXGLOB);
2071 } else {
2072 invltlb_glob();
2073 }
2074 } else if (pmap == PCPU_GET(curpmap)) {
2075 if (pmap_pcid_enabled) {
2076 critical_enter();
2077 if (invpcid_works) {
2078 d.pcid = pmap->pm_pcids[0].pm_pcid;
2079 d.pad = 0;
2080 d.addr = 0;
2081 invpcid(&d, INVPCID_CTX);
2082 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2083 d.pcid |= PMAP_PCID_USER_PT;
2084 invpcid(&d, INVPCID_CTX);
2085 }
2086 } else {
2087 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[0].pm_pcid;
2088 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
2089 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[
2090 0].pm_pcid | PMAP_PCID_USER_PT;
2091 pmap_pti_pcid_invalidate(ucr3, kcr3);
2092 } else
2093 load_cr3(kcr3);
2094 }
2095 critical_exit();
2096 } else {
2097 invltlb();
2098 }
2099 } else if (pmap_pcid_enabled) {
2100 pmap->pm_pcids[0].pm_gen = 0;
2101 }
2102 }
2103
2104 PMAP_INLINE void
2105 pmap_invalidate_cache(void)
2106 {
2107
2108 wbinvd();
2109 }
2110
2111 static void
2112 pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
2113 {
2114
2115 pmap_update_pde_store(pmap, pde, newpde);
2116 if (pmap == kernel_pmap || pmap == PCPU_GET(curpmap))
2117 pmap_update_pde_invalidate(pmap, va, newpde);
2118 else
2119 pmap->pm_pcids[0].pm_gen = 0;
2120 }
2121 #endif /* !SMP */
2122
2123 static void
2124 pmap_invalidate_pde_page(pmap_t pmap, vm_offset_t va, pd_entry_t pde)
2125 {
2126
2127 /*
2128 * When the PDE has PG_PROMOTED set, the 2MB page mapping was created
2129 * by a promotion that did not invalidate the 512 4KB page mappings
2130 * that might exist in the TLB. Consequently, at this point, the TLB
2131 * may hold both 4KB and 2MB page mappings for the address range [va,
2132 * va + NBPDR). Therefore, the entire range must be invalidated here.
2133 * In contrast, when PG_PROMOTED is clear, the TLB will not hold any
2134 * 4KB page mappings for the address range [va, va + NBPDR), and so a
2135 * single INVLPG suffices to invalidate the 2MB page mapping from the
2136 * TLB.
2137 */
2138 if ((pde & PG_PROMOTED) != 0)
2139 pmap_invalidate_range(pmap, va, va + NBPDR - 1);
2140 else
2141 pmap_invalidate_page(pmap, va);
2142 }
2143
2144 #define PMAP_CLFLUSH_THRESHOLD (2 * 1024 * 1024)
2145
2146 void
2147 pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva, boolean_t force)
2148 {
2149
2150 if (force) {
2151 sva &= ~(vm_offset_t)(cpu_clflush_line_size - 1);
2152 } else {
2153 KASSERT((sva & PAGE_MASK) == 0,
2154 ("pmap_invalidate_cache_range: sva not page-aligned"));
2155 KASSERT((eva & PAGE_MASK) == 0,
2156 ("pmap_invalidate_cache_range: eva not page-aligned"));
2157 }
2158
2159 if ((cpu_feature & CPUID_SS) != 0 && !force)
2160 ; /* If "Self Snoop" is supported and allowed, do nothing. */
2161 else if ((cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0 &&
2162 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2163 /*
2164 * XXX: Some CPUs fault, hang, or trash the local APIC
2165 * registers if we use CLFLUSH on the local APIC
2166 * range. The local APIC is always uncached, so we
2167 * don't need to flush for that range anyway.
2168 */
2169 if (pmap_kextract(sva) == lapic_paddr)
2170 return;
2171
2172 /*
2173 * Otherwise, do per-cache line flush. Use the sfence
2174 * instruction to insure that previous stores are
2175 * included in the write-back. The processor
2176 * propagates flush to other processors in the cache
2177 * coherence domain.
2178 */
2179 sfence();
2180 for (; sva < eva; sva += cpu_clflush_line_size)
2181 clflushopt(sva);
2182 sfence();
2183 } else if ((cpu_feature & CPUID_CLFSH) != 0 &&
2184 eva - sva < PMAP_CLFLUSH_THRESHOLD) {
2185 if (pmap_kextract(sva) == lapic_paddr)
2186 return;
2187 /*
2188 * Writes are ordered by CLFLUSH on Intel CPUs.
2189 */
2190 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2191 mfence();
2192 for (; sva < eva; sva += cpu_clflush_line_size)
2193 clflush(sva);
2194 if (cpu_vendor_id != CPU_VENDOR_INTEL)
2195 mfence();
2196 } else {
2197
2198 /*
2199 * No targeted cache flush methods are supported by CPU,
2200 * or the supplied range is bigger than 2MB.
2201 * Globally invalidate cache.
2202 */
2203 pmap_invalidate_cache();
2204 }
2205 }
2206
2207 /*
2208 * Remove the specified set of pages from the data and instruction caches.
2209 *
2210 * In contrast to pmap_invalidate_cache_range(), this function does not
2211 * rely on the CPU's self-snoop feature, because it is intended for use
2212 * when moving pages into a different cache domain.
2213 */
2214 void
2215 pmap_invalidate_cache_pages(vm_page_t *pages, int count)
2216 {
2217 vm_offset_t daddr, eva;
2218 int i;
2219 bool useclflushopt;
2220
2221 useclflushopt = (cpu_stdext_feature & CPUID_STDEXT_CLFLUSHOPT) != 0;
2222 if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
2223 ((cpu_feature & CPUID_CLFSH) == 0 && !useclflushopt))
2224 pmap_invalidate_cache();
2225 else {
2226 if (useclflushopt)
2227 sfence();
2228 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2229 mfence();
2230 for (i = 0; i < count; i++) {
2231 daddr = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pages[i]));
2232 eva = daddr + PAGE_SIZE;
2233 for (; daddr < eva; daddr += cpu_clflush_line_size) {
2234 if (useclflushopt)
2235 clflushopt(daddr);
2236 else
2237 clflush(daddr);
2238 }
2239 }
2240 if (useclflushopt)
2241 sfence();
2242 else if (cpu_vendor_id != CPU_VENDOR_INTEL)
2243 mfence();
2244 }
2245 }
2246
2247 /*
2248 * Routine: pmap_extract
2249 * Function:
2250 * Extract the physical page address associated
2251 * with the given map/virtual_address pair.
2252 */
2253 vm_paddr_t
2254 pmap_extract(pmap_t pmap, vm_offset_t va)
2255 {
2256 pdp_entry_t *pdpe;
2257 pd_entry_t *pde;
2258 pt_entry_t *pte, PG_V;
2259 vm_paddr_t pa;
2260
2261 pa = 0;
2262 PG_V = pmap_valid_bit(pmap);
2263 PMAP_LOCK(pmap);
2264 pdpe = pmap_pdpe(pmap, va);
2265 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2266 if ((*pdpe & PG_PS) != 0)
2267 pa = (*pdpe & PG_PS_FRAME) | (va & PDPMASK);
2268 else {
2269 pde = pmap_pdpe_to_pde(pdpe, va);
2270 if ((*pde & PG_V) != 0) {
2271 if ((*pde & PG_PS) != 0) {
2272 pa = (*pde & PG_PS_FRAME) |
2273 (va & PDRMASK);
2274 } else {
2275 pte = pmap_pde_to_pte(pde, va);
2276 pa = (*pte & PG_FRAME) |
2277 (va & PAGE_MASK);
2278 }
2279 }
2280 }
2281 }
2282 PMAP_UNLOCK(pmap);
2283 return (pa);
2284 }
2285
2286 /*
2287 * Routine: pmap_extract_and_hold
2288 * Function:
2289 * Atomically extract and hold the physical page
2290 * with the given pmap and virtual address pair
2291 * if that mapping permits the given protection.
2292 */
2293 vm_page_t
2294 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
2295 {
2296 pd_entry_t pde, *pdep;
2297 pt_entry_t pte, PG_RW, PG_V;
2298 vm_paddr_t pa;
2299 vm_page_t m;
2300
2301 pa = 0;
2302 m = NULL;
2303 PG_RW = pmap_rw_bit(pmap);
2304 PG_V = pmap_valid_bit(pmap);
2305 PMAP_LOCK(pmap);
2306 retry:
2307 pdep = pmap_pde(pmap, va);
2308 if (pdep != NULL && (pde = *pdep)) {
2309 if (pde & PG_PS) {
2310 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
2311 if (vm_page_pa_tryrelock(pmap, (pde &
2312 PG_PS_FRAME) | (va & PDRMASK), &pa))
2313 goto retry;
2314 m = PHYS_TO_VM_PAGE(pa);
2315 }
2316 } else {
2317 pte = *pmap_pde_to_pte(pdep, va);
2318 if ((pte & PG_V) &&
2319 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2320 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2321 &pa))
2322 goto retry;
2323 m = PHYS_TO_VM_PAGE(pa);
2324 }
2325 }
2326 if (m != NULL)
2327 vm_page_hold(m);
2328 }
2329 PA_UNLOCK_COND(pa);
2330 PMAP_UNLOCK(pmap);
2331 return (m);
2332 }
2333
2334 vm_paddr_t
2335 pmap_kextract(vm_offset_t va)
2336 {
2337 pd_entry_t pde;
2338 vm_paddr_t pa;
2339
2340 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2341 pa = DMAP_TO_PHYS(va);
2342 } else {
2343 pde = *vtopde(va);
2344 if (pde & PG_PS) {
2345 pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2346 } else {
2347 /*
2348 * Beware of a concurrent promotion that changes the
2349 * PDE at this point! For example, vtopte() must not
2350 * be used to access the PTE because it would use the
2351 * new PDE. It is, however, safe to use the old PDE
2352 * because the page table page is preserved by the
2353 * promotion.
2354 */
2355 pa = *pmap_pde_to_pte(&pde, va);
2356 pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2357 }
2358 }
2359 return (pa);
2360 }
2361
2362 /***************************************************
2363 * Low level mapping routines.....
2364 ***************************************************/
2365
2366 /*
2367 * Add a wired page to the kva.
2368 * Note: not SMP coherent.
2369 */
2370 PMAP_INLINE void
2371 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2372 {
2373 pt_entry_t *pte;
2374
2375 pte = vtopte(va);
2376 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g);
2377 }
2378
2379 static __inline void
2380 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2381 {
2382 pt_entry_t *pte;
2383 int cache_bits;
2384
2385 pte = vtopte(va);
2386 cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2387 pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | cache_bits);
2388 }
2389
2390 /*
2391 * Remove a page from the kernel pagetables.
2392 * Note: not SMP coherent.
2393 */
2394 PMAP_INLINE void
2395 pmap_kremove(vm_offset_t va)
2396 {
2397 pt_entry_t *pte;
2398
2399 pte = vtopte(va);
2400 pte_clear(pte);
2401 }
2402
2403 /*
2404 * Used to map a range of physical addresses into kernel
2405 * virtual address space.
2406 *
2407 * The value passed in '*virt' is a suggested virtual address for
2408 * the mapping. Architectures which can support a direct-mapped
2409 * physical to virtual region can return the appropriate address
2410 * within that region, leaving '*virt' unchanged. Other
2411 * architectures should map the pages starting at '*virt' and
2412 * update '*virt' with the first usable address after the mapped
2413 * region.
2414 */
2415 vm_offset_t
2416 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2417 {
2418 return PHYS_TO_DMAP(start);
2419 }
2420
2421
2422 /*
2423 * Add a list of wired pages to the kva
2424 * this routine is only used for temporary
2425 * kernel mappings that do not need to have
2426 * page modification or references recorded.
2427 * Note that old mappings are simply written
2428 * over. The page *must* be wired.
2429 * Note: SMP coherent. Uses a ranged shootdown IPI.
2430 */
2431 void
2432 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2433 {
2434 pt_entry_t *endpte, oldpte, pa, *pte;
2435 vm_page_t m;
2436 int cache_bits;
2437
2438 oldpte = 0;
2439 pte = vtopte(sva);
2440 endpte = pte + count;
2441 while (pte < endpte) {
2442 m = *ma++;
2443 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2444 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2445 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2446 oldpte |= *pte;
2447 pte_store(pte, pa | pg_g | X86_PG_RW | X86_PG_V);
2448 }
2449 pte++;
2450 }
2451 if (__predict_false((oldpte & X86_PG_V) != 0))
2452 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2453 PAGE_SIZE);
2454 }
2455
2456 /*
2457 * This routine tears out page mappings from the
2458 * kernel -- it is meant only for temporary mappings.
2459 * Note: SMP coherent. Uses a ranged shootdown IPI.
2460 */
2461 void
2462 pmap_qremove(vm_offset_t sva, int count)
2463 {
2464 vm_offset_t va;
2465
2466 va = sva;
2467 while (count-- > 0) {
2468 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2469 pmap_kremove(va);
2470 va += PAGE_SIZE;
2471 }
2472 pmap_invalidate_range(kernel_pmap, sva, va);
2473 }
2474
2475 /***************************************************
2476 * Page table page management routines.....
2477 ***************************************************/
2478 static __inline void
2479 pmap_free_zero_pages(struct spglist *free)
2480 {
2481 vm_page_t m;
2482 int count;
2483
2484 for (count = 0; (m = SLIST_FIRST(free)) != NULL; count++) {
2485 SLIST_REMOVE_HEAD(free, plinks.s.ss);
2486 /* Preserve the page's PG_ZERO setting. */
2487 vm_page_free_toq(m);
2488 }
2489 atomic_subtract_int(&vm_cnt.v_wire_count, count);
2490 }
2491
2492 /*
2493 * Schedule the specified unused page table page to be freed. Specifically,
2494 * add the page to the specified list of pages that will be released to the
2495 * physical memory manager after the TLB has been updated.
2496 */
2497 static __inline void
2498 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2499 boolean_t set_PG_ZERO)
2500 {
2501
2502 if (set_PG_ZERO)
2503 m->flags |= PG_ZERO;
2504 else
2505 m->flags &= ~PG_ZERO;
2506 SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2507 }
2508
2509 /*
2510 * Inserts the specified page table page into the specified pmap's collection
2511 * of idle page table pages. Each of a pmap's page table pages is responsible
2512 * for mapping a distinct range of virtual addresses. The pmap's collection is
2513 * ordered by this virtual address range.
2514 */
2515 static __inline int
2516 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2517 {
2518
2519 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2520 return (vm_radix_insert(&pmap->pm_root, mpte));
2521 }
2522
2523 /*
2524 * Removes the page table page mapping the specified virtual address from the
2525 * specified pmap's collection of idle page table pages, and returns it.
2526 * Otherwise, returns NULL if there is no page table page corresponding to the
2527 * specified virtual address.
2528 */
2529 static __inline vm_page_t
2530 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
2531 {
2532
2533 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2534 return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
2535 }
2536
2537 /*
2538 * Decrements a page table page's wire count, which is used to record the
2539 * number of valid page table entries within the page. If the wire count
2540 * drops to zero, then the page table page is unmapped. Returns TRUE if the
2541 * page table page was unmapped and FALSE otherwise.
2542 */
2543 static inline boolean_t
2544 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2545 {
2546
2547 --m->wire_count;
2548 if (m->wire_count == 0) {
2549 _pmap_unwire_ptp(pmap, va, m, free);
2550 return (TRUE);
2551 } else
2552 return (FALSE);
2553 }
2554
2555 static void
2556 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2557 {
2558
2559 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2560 /*
2561 * unmap the page table page
2562 */
2563 if (m->pindex >= (NUPDE + NUPDPE)) {
2564 /* PDP page */
2565 pml4_entry_t *pml4;
2566 pml4 = pmap_pml4e(pmap, va);
2567 *pml4 = 0;
2568 if (pmap->pm_pml4u != NULL && va <= VM_MAXUSER_ADDRESS) {
2569 pml4 = &pmap->pm_pml4u[pmap_pml4e_index(va)];
2570 *pml4 = 0;
2571 }
2572 } else if (m->pindex >= NUPDE) {
2573 /* PD page */
2574 pdp_entry_t *pdp;
2575 pdp = pmap_pdpe(pmap, va);
2576 *pdp = 0;
2577 } else {
2578 /* PTE page */
2579 pd_entry_t *pd;
2580 pd = pmap_pde(pmap, va);
2581 *pd = 0;
2582 }
2583 pmap_resident_count_dec(pmap, 1);
2584 if (m->pindex < NUPDE) {
2585 /* We just released a PT, unhold the matching PD */
2586 vm_page_t pdpg;
2587
2588 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2589 pmap_unwire_ptp(pmap, va, pdpg, free);
2590 }
2591 if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2592 /* We just released a PD, unhold the matching PDP */
2593 vm_page_t pdppg;
2594
2595 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2596 pmap_unwire_ptp(pmap, va, pdppg, free);
2597 }
2598
2599 /*
2600 * Put page on a list so that it is released after
2601 * *ALL* TLB shootdown is done
2602 */
2603 pmap_add_delayed_free_list(m, free, TRUE);
2604 }
2605
2606 /*
2607 * After removing a page table entry, this routine is used to
2608 * conditionally free the page, and manage the hold/wire counts.
2609 */
2610 static int
2611 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2612 struct spglist *free)
2613 {
2614 vm_page_t mpte;
2615
2616 if (va >= VM_MAXUSER_ADDRESS)
2617 return (0);
2618 KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2619 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2620 return (pmap_unwire_ptp(pmap, va, mpte, free));
2621 }
2622
2623 void
2624 pmap_pinit0(pmap_t pmap)
2625 {
2626 int i;
2627
2628 PMAP_LOCK_INIT(pmap);
2629 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2630 pmap->pm_pml4u = NULL;
2631 pmap->pm_cr3 = KPML4phys;
2632 /* hack to keep pmap_pti_pcid_invalidate() alive */
2633 pmap->pm_ucr3 = PMAP_NO_CR3;
2634 pmap->pm_root.rt_root = 0;
2635 CPU_ZERO(&pmap->pm_active);
2636 TAILQ_INIT(&pmap->pm_pvchunk);
2637 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2638 pmap->pm_flags = pmap_flags;
2639 CPU_FOREACH(i) {
2640 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_KERN + 1;
2641 pmap->pm_pcids[i].pm_gen = 1;
2642 }
2643 pmap_activate_boot(pmap);
2644 }
2645
2646 void
2647 pmap_pinit_pml4(vm_page_t pml4pg)
2648 {
2649 pml4_entry_t *pm_pml4;
2650 int i;
2651
2652 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2653
2654 /* Wire in kernel global address entries. */
2655 for (i = 0; i < NKPML4E; i++) {
2656 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2657 X86_PG_V;
2658 }
2659 for (i = 0; i < ndmpdpphys; i++) {
2660 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2661 X86_PG_V;
2662 }
2663
2664 /* install self-referential address mapping entry(s) */
2665 pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2666 X86_PG_A | X86_PG_M;
2667 }
2668
2669 static void
2670 pmap_pinit_pml4_pti(vm_page_t pml4pg)
2671 {
2672 pml4_entry_t *pm_pml4;
2673 int i;
2674
2675 pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2676 for (i = 0; i < NPML4EPG; i++)
2677 pm_pml4[i] = pti_pml4[i];
2678 }
2679
2680 /*
2681 * Initialize a preallocated and zeroed pmap structure,
2682 * such as one in a vmspace structure.
2683 */
2684 int
2685 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2686 {
2687 vm_page_t pml4pg, pml4pgu;
2688 vm_paddr_t pml4phys;
2689 int i;
2690
2691 /*
2692 * allocate the page directory page
2693 */
2694 pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
2695 VM_ALLOC_WIRED | VM_ALLOC_ZERO | VM_ALLOC_WAITOK);
2696
2697 pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2698 pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2699 CPU_FOREACH(i) {
2700 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2701 pmap->pm_pcids[i].pm_gen = 0;
2702 }
2703 pmap->pm_cr3 = PMAP_NO_CR3; /* initialize to an invalid value */
2704 pmap->pm_ucr3 = PMAP_NO_CR3;
2705 pmap->pm_pml4u = NULL;
2706
2707 pmap->pm_type = pm_type;
2708 if ((pml4pg->flags & PG_ZERO) == 0)
2709 pagezero(pmap->pm_pml4);
2710
2711 /*
2712 * Do not install the host kernel mappings in the nested page
2713 * tables. These mappings are meaningless in the guest physical
2714 * address space.
2715 * Install minimal kernel mappings in PTI case.
2716 */
2717 if (pm_type == PT_X86) {
2718 pmap->pm_cr3 = pml4phys;
2719 pmap_pinit_pml4(pml4pg);
2720 if (pti) {
2721 pml4pgu = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2722 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2723 pmap->pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(
2724 VM_PAGE_TO_PHYS(pml4pgu));
2725 pmap_pinit_pml4_pti(pml4pgu);
2726 pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pml4pgu);
2727 }
2728 }
2729
2730 pmap->pm_root.rt_root = 0;
2731 CPU_ZERO(&pmap->pm_active);
2732 TAILQ_INIT(&pmap->pm_pvchunk);
2733 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2734 pmap->pm_flags = flags;
2735 pmap->pm_eptgen = 0;
2736
2737 return (1);
2738 }
2739
2740 int
2741 pmap_pinit(pmap_t pmap)
2742 {
2743
2744 return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2745 }
2746
2747 /*
2748 * This routine is called if the desired page table page does not exist.
2749 *
2750 * If page table page allocation fails, this routine may sleep before
2751 * returning NULL. It sleeps only if a lock pointer was given.
2752 *
2753 * Note: If a page allocation fails at page table level two or three,
2754 * one or two pages may be held during the wait, only to be released
2755 * afterwards. This conservative approach is easily argued to avoid
2756 * race conditions.
2757 *
2758 * The ptepindexes, i.e. page indices, of the page table pages encountered
2759 * while translating virtual address va are defined as follows:
2760 * - for the page table page (last level),
2761 * ptepindex = pmap_pde_pindex(va) = va >> PDRSHIFT,
2762 * in other words, it is just the index of the PDE that maps the page
2763 * table page.
2764 * - for the page directory page,
2765 * ptepindex = NUPDE (number of userland PD entries) +
2766 * (pmap_pde_index(va) >> NPDEPGSHIFT)
2767 * i.e. index of PDPE is put after the last index of PDE,
2768 * - for the page directory pointer page,
2769 * ptepindex = NUPDE + NUPDPE + (pmap_pde_index(va) >> (NPDEPGSHIFT +
2770 * NPML4EPGSHIFT),
2771 * i.e. index of pml4e is put after the last index of PDPE.
2772 *
2773 * Define an order on the paging entries, where all entries of the
2774 * same height are put together, then heights are put from deepest to
2775 * root. Then ptexpindex is the sequential number of the
2776 * corresponding paging entry in this order.
2777 *
2778 * The root page at PML4 does not participate in this indexing scheme, since
2779 * it is statically allocated by pmap_pinit() and not by _pmap_allocpte().
2780 */
2781 static vm_page_t
2782 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2783 {
2784 vm_page_t m, pdppg, pdpg;
2785 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2786
2787 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2788
2789 PG_A = pmap_accessed_bit(pmap);
2790 PG_M = pmap_modified_bit(pmap);
2791 PG_V = pmap_valid_bit(pmap);
2792 PG_RW = pmap_rw_bit(pmap);
2793
2794 /*
2795 * Allocate a page table page.
2796 */
2797 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2798 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2799 if (lockp != NULL) {
2800 RELEASE_PV_LIST_LOCK(lockp);
2801 PMAP_UNLOCK(pmap);
2802 PMAP_ASSERT_NOT_IN_DI();
2803 VM_WAIT;
2804 PMAP_LOCK(pmap);
2805 }
2806
2807 /*
2808 * Indicate the need to retry. While waiting, the page table
2809 * page may have been allocated.
2810 */
2811 return (NULL);
2812 }
2813 if ((m->flags & PG_ZERO) == 0)
2814 pmap_zero_page(m);
2815
2816 /*
2817 * Map the pagetable page into the process address space, if
2818 * it isn't already there.
2819 */
2820
2821 if (ptepindex >= (NUPDE + NUPDPE)) {
2822 pml4_entry_t *pml4, *pml4u;
2823 vm_pindex_t pml4index;
2824
2825 /* Wire up a new PDPE page */
2826 pml4index = ptepindex - (NUPDE + NUPDPE);
2827 pml4 = &pmap->pm_pml4[pml4index];
2828 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2829 if (pmap->pm_pml4u != NULL && pml4index < NUPML4E) {
2830 /*
2831 * PTI: Make all user-space mappings in the
2832 * kernel-mode page table no-execute so that
2833 * we detect any programming errors that leave
2834 * the kernel-mode page table active on return
2835 * to user space.
2836 */
2837 if (pmap->pm_ucr3 != PMAP_NO_CR3)
2838 *pml4 |= pg_nx;
2839
2840 pml4u = &pmap->pm_pml4u[pml4index];
2841 *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
2842 PG_A | PG_M;
2843 }
2844
2845 } else if (ptepindex >= NUPDE) {
2846 vm_pindex_t pml4index;
2847 vm_pindex_t pdpindex;
2848 pml4_entry_t *pml4;
2849 pdp_entry_t *pdp;
2850
2851 /* Wire up a new PDE page */
2852 pdpindex = ptepindex - NUPDE;
2853 pml4index = pdpindex >> NPML4EPGSHIFT;
2854
2855 pml4 = &pmap->pm_pml4[pml4index];
2856 if ((*pml4 & PG_V) == 0) {
2857 /* Have to allocate a new pdp, recurse */
2858 if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2859 lockp) == NULL) {
2860 --m->wire_count;
2861 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2862 vm_page_free_zero(m);
2863 return (NULL);
2864 }
2865 } else {
2866 /* Add reference to pdp page */
2867 pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2868 pdppg->wire_count++;
2869 }
2870 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2871
2872 /* Now find the pdp page */
2873 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2874 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2875
2876 } else {
2877 vm_pindex_t pml4index;
2878 vm_pindex_t pdpindex;
2879 pml4_entry_t *pml4;
2880 pdp_entry_t *pdp;
2881 pd_entry_t *pd;
2882
2883 /* Wire up a new PTE page */
2884 pdpindex = ptepindex >> NPDPEPGSHIFT;
2885 pml4index = pdpindex >> NPML4EPGSHIFT;
2886
2887 /* First, find the pdp and check that its valid. */
2888 pml4 = &pmap->pm_pml4[pml4index];
2889 if ((*pml4 & PG_V) == 0) {
2890 /* Have to allocate a new pd, recurse */
2891 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2892 lockp) == NULL) {
2893 --m->wire_count;
2894 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2895 vm_page_free_zero(m);
2896 return (NULL);
2897 }
2898 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2899 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2900 } else {
2901 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2902 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2903 if ((*pdp & PG_V) == 0) {
2904 /* Have to allocate a new pd, recurse */
2905 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2906 lockp) == NULL) {
2907 --m->wire_count;
2908 atomic_subtract_int(&vm_cnt.v_wire_count,
2909 1);
2910 vm_page_free_zero(m);
2911 return (NULL);
2912 }
2913 } else {
2914 /* Add reference to the pd page */
2915 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2916 pdpg->wire_count++;
2917 }
2918 }
2919 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2920
2921 /* Now we know where the page directory page is */
2922 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2923 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2924 }
2925
2926 pmap_resident_count_inc(pmap, 1);
2927
2928 return (m);
2929 }
2930
2931 static vm_page_t
2932 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2933 {
2934 vm_pindex_t pdpindex, ptepindex;
2935 pdp_entry_t *pdpe, PG_V;
2936 vm_page_t pdpg;
2937
2938 PG_V = pmap_valid_bit(pmap);
2939
2940 retry:
2941 pdpe = pmap_pdpe(pmap, va);
2942 if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2943 /* Add a reference to the pd page. */
2944 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2945 pdpg->wire_count++;
2946 } else {
2947 /* Allocate a pd page. */
2948 ptepindex = pmap_pde_pindex(va);
2949 pdpindex = ptepindex >> NPDPEPGSHIFT;
2950 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2951 if (pdpg == NULL && lockp != NULL)
2952 goto retry;
2953 }
2954 return (pdpg);
2955 }
2956
2957 static vm_page_t
2958 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2959 {
2960 vm_pindex_t ptepindex;
2961 pd_entry_t *pd, PG_V;
2962 vm_page_t m;
2963
2964 PG_V = pmap_valid_bit(pmap);
2965
2966 /*
2967 * Calculate pagetable page index
2968 */
2969 ptepindex = pmap_pde_pindex(va);
2970 retry:
2971 /*
2972 * Get the page directory entry
2973 */
2974 pd = pmap_pde(pmap, va);
2975
2976 /*
2977 * This supports switching from a 2MB page to a
2978 * normal 4K page.
2979 */
2980 if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2981 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2982 /*
2983 * Invalidation of the 2MB page mapping may have caused
2984 * the deallocation of the underlying PD page.
2985 */
2986 pd = NULL;
2987 }
2988 }
2989
2990 /*
2991 * If the page table page is mapped, we just increment the
2992 * hold count, and activate it.
2993 */
2994 if (pd != NULL && (*pd & PG_V) != 0) {
2995 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2996 m->wire_count++;
2997 } else {
2998 /*
2999 * Here if the pte page isn't mapped, or if it has been
3000 * deallocated.
3001 */
3002 m = _pmap_allocpte(pmap, ptepindex, lockp);
3003 if (m == NULL && lockp != NULL)
3004 goto retry;
3005 }
3006 return (m);
3007 }
3008
3009
3010 /***************************************************
3011 * Pmap allocation/deallocation routines.
3012 ***************************************************/
3013
3014 /*
3015 * Release any resources held by the given physical map.
3016 * Called when a pmap initialized by pmap_pinit is being released.
3017 * Should only be called if the map contains no valid mappings.
3018 */
3019 void
3020 pmap_release(pmap_t pmap)
3021 {
3022 vm_page_t m;
3023 int i;
3024
3025 KASSERT(pmap->pm_stats.resident_count == 0,
3026 ("pmap_release: pmap resident count %ld != 0",
3027 pmap->pm_stats.resident_count));
3028 KASSERT(vm_radix_is_empty(&pmap->pm_root),
3029 ("pmap_release: pmap has reserved page table page(s)"));
3030 KASSERT(CPU_EMPTY(&pmap->pm_active),
3031 ("releasing active pmap %p", pmap));
3032
3033 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
3034
3035 for (i = 0; i < NKPML4E; i++) /* KVA */
3036 pmap->pm_pml4[KPML4BASE + i] = 0;
3037 for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
3038 pmap->pm_pml4[DMPML4I + i] = 0;
3039 pmap->pm_pml4[PML4PML4I] = 0; /* Recursive Mapping */
3040
3041 m->wire_count--;
3042 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3043 vm_page_free_zero(m);
3044
3045 if (pmap->pm_pml4u != NULL) {
3046 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4u));
3047 m->wire_count--;
3048 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
3049 vm_page_free(m);
3050 }
3051 }
3052
3053 static int
3054 kvm_size(SYSCTL_HANDLER_ARGS)
3055 {
3056 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
3057
3058 return sysctl_handle_long(oidp, &ksize, 0, req);
3059 }
3060 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
3061 0, 0, kvm_size, "LU", "Size of KVM");
3062
3063 static int
3064 kvm_free(SYSCTL_HANDLER_ARGS)
3065 {
3066 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
3067
3068 return sysctl_handle_long(oidp, &kfree, 0, req);
3069 }
3070 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
3071 0, 0, kvm_free, "LU", "Amount of KVM free");
3072
3073 /*
3074 * grow the number of kernel page table entries, if needed
3075 */
3076 void
3077 pmap_growkernel(vm_offset_t addr)
3078 {
3079 vm_paddr_t paddr;
3080 vm_page_t nkpg;
3081 pd_entry_t *pde, newpdir;
3082 pdp_entry_t *pdpe;
3083
3084 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
3085
3086 /*
3087 * Return if "addr" is within the range of kernel page table pages
3088 * that were preallocated during pmap bootstrap. Moreover, leave
3089 * "kernel_vm_end" and the kernel page table as they were.
3090 *
3091 * The correctness of this action is based on the following
3092 * argument: vm_map_insert() allocates contiguous ranges of the
3093 * kernel virtual address space. It calls this function if a range
3094 * ends after "kernel_vm_end". If the kernel is mapped between
3095 * "kernel_vm_end" and "addr", then the range cannot begin at
3096 * "kernel_vm_end". In fact, its beginning address cannot be less
3097 * than the kernel. Thus, there is no immediate need to allocate
3098 * any new kernel page table pages between "kernel_vm_end" and
3099 * "KERNBASE".
3100 */
3101 if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
3102 return;
3103
3104 addr = roundup2(addr, NBPDR);
3105 if (addr - 1 >= vm_map_max(kernel_map))
3106 addr = vm_map_max(kernel_map);
3107 while (kernel_vm_end < addr) {
3108 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
3109 if ((*pdpe & X86_PG_V) == 0) {
3110 /* We need a new PDP entry */
3111 nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
3112 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
3113 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
3114 if (nkpg == NULL)
3115 panic("pmap_growkernel: no memory to grow kernel");
3116 if ((nkpg->flags & PG_ZERO) == 0)
3117 pmap_zero_page(nkpg);
3118 paddr = VM_PAGE_TO_PHYS(nkpg);
3119 *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
3120 X86_PG_A | X86_PG_M);
3121 continue; /* try again */
3122 }
3123 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
3124 if ((*pde & X86_PG_V) != 0) {
3125 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3126 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
3127 kernel_vm_end = vm_map_max(kernel_map);
3128 break;
3129 }
3130 continue;
3131 }
3132
3133 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
3134 VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
3135 VM_ALLOC_ZERO);
3136 if (nkpg == NULL)
3137 panic("pmap_growkernel: no memory to grow kernel");
3138 if ((nkpg->flags & PG_ZERO) == 0)
3139 pmap_zero_page(nkpg);
3140 paddr = VM_PAGE_TO_PHYS(nkpg);
3141 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
3142 pde_store(pde, newpdir);
3143
3144 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3145 if (kernel_vm_end - 1 >= vm_map_max(kernel_map)) {
3146 kernel_vm_end = vm_map_max(kernel_map);
3147 break;
3148 }
3149 }
3150 }
3151
3152
3153 /***************************************************
3154 * page management routines.
3155 ***************************************************/
3156
3157 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
3158 CTASSERT(_NPCM == 3);
3159 CTASSERT(_NPCPV == 168);
3160
3161 static __inline struct pv_chunk *
3162 pv_to_chunk(pv_entry_t pv)
3163 {
3164
3165 return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
3166 }
3167
3168 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
3169
3170 #define PC_FREE0 0xfffffffffffffffful
3171 #define PC_FREE1 0xfffffffffffffffful
3172 #define PC_FREE2 0x000000fffffffffful
3173
3174 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
3175
3176 #ifdef PV_STATS
3177 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
3178
3179 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
3180 "Current number of pv entry chunks");
3181 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
3182 "Current number of pv entry chunks allocated");
3183 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
3184 "Current number of pv entry chunks frees");
3185 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
3186 "Number of times tried to get a chunk page but failed.");
3187
3188 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
3189 static int pv_entry_spare;
3190
3191 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
3192 "Current number of pv entry frees");
3193 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
3194 "Current number of pv entry allocs");
3195 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
3196 "Current number of pv entries");
3197 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
3198 "Current number of spare pv entries");
3199 #endif
3200
3201 static void
3202 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
3203 {
3204
3205 if (pmap == NULL)
3206 return;
3207 pmap_invalidate_all(pmap);
3208 if (pmap != locked_pmap)
3209 PMAP_UNLOCK(pmap);
3210 if (start_di)
3211 pmap_delayed_invl_finished();
3212 }
3213
3214 /*
3215 * We are in a serious low memory condition. Resort to
3216 * drastic measures to free some pages so we can allocate
3217 * another pv entry chunk.
3218 *
3219 * Returns NULL if PV entries were reclaimed from the specified pmap.
3220 *
3221 * We do not, however, unmap 2mpages because subsequent accesses will
3222 * allocate per-page pv entries until repromotion occurs, thereby
3223 * exacerbating the shortage of free pv entries.
3224 */
3225 static vm_page_t
3226 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
3227 {
3228 struct pv_chunk *pc, *pc_marker, *pc_marker_end;
3229 struct pv_chunk_header pc_marker_b, pc_marker_end_b;
3230 struct md_page *pvh;
3231 pd_entry_t *pde;
3232 pmap_t next_pmap, pmap;
3233 pt_entry_t *pte, tpte;
3234 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3235 pv_entry_t pv;
3236 vm_offset_t va;
3237 vm_page_t m, m_pc;
3238 struct spglist free;
3239 uint64_t inuse;
3240 int bit, field, freed;
3241 bool start_di;
3242 static int active_reclaims = 0;
3243
3244 PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
3245 KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
3246 pmap = NULL;
3247 m_pc = NULL;
3248 PG_G = PG_A = PG_M = PG_RW = 0;
3249 SLIST_INIT(&free);
3250 bzero(&pc_marker_b, sizeof(pc_marker_b));
3251 bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
3252 pc_marker = (struct pv_chunk *)&pc_marker_b;
3253 pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
3254
3255 /*
3256 * A delayed invalidation block should already be active if
3257 * pmap_advise() or pmap_remove() called this function by way
3258 * of pmap_demote_pde_locked().
3259 */
3260 start_di = pmap_not_in_di();
3261
3262 mtx_lock(&pv_chunks_mutex);
3263 active_reclaims++;
3264 TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
3265 TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
3266 while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
3267 SLIST_EMPTY(&free)) {
3268 next_pmap = pc->pc_pmap;
3269 if (next_pmap == NULL) {
3270 /*
3271 * The next chunk is a marker. However, it is
3272 * not our marker, so active_reclaims must be
3273 * > 1. Consequently, the next_chunk code
3274 * will not rotate the pv_chunks list.
3275 */
3276 goto next_chunk;
3277 }
3278 mtx_unlock(&pv_chunks_mutex);
3279
3280 /*
3281 * A pv_chunk can only be removed from the pc_lru list
3282 * when both pc_chunks_mutex is owned and the
3283 * corresponding pmap is locked.
3284 */
3285 if (pmap != next_pmap) {
3286 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
3287 start_di);
3288 pmap = next_pmap;
3289 /* Avoid deadlock and lock recursion. */
3290 if (pmap > locked_pmap) {
3291 RELEASE_PV_LIST_LOCK(lockp);
3292 PMAP_LOCK(pmap);
3293 if (start_di)
3294 pmap_delayed_invl_started();
3295 mtx_lock(&pv_chunks_mutex);
3296 continue;
3297 } else if (pmap != locked_pmap) {
3298 if (PMAP_TRYLOCK(pmap)) {
3299 if (start_di)
3300 pmap_delayed_invl_started();
3301 mtx_lock(&pv_chunks_mutex);
3302 continue;
3303 } else {
3304 pmap = NULL; /* pmap is not locked */
3305 mtx_lock(&pv_chunks_mutex);
3306 pc = TAILQ_NEXT(pc_marker, pc_lru);
3307 if (pc == NULL ||
3308 pc->pc_pmap != next_pmap)
3309 continue;
3310 goto next_chunk;
3311 }
3312 } else if (start_di)
3313 pmap_delayed_invl_started();
3314 PG_G = pmap_global_bit(pmap);
3315 PG_A = pmap_accessed_bit(pmap);
3316 PG_M = pmap_modified_bit(pmap);
3317 PG_RW = pmap_rw_bit(pmap);
3318 }
3319
3320 /*
3321 * Destroy every non-wired, 4 KB page mapping in the chunk.
3322 */
3323 freed = 0;
3324 for (field = 0; field < _NPCM; field++) {
3325 for (inuse = ~pc->pc_map[field] & pc_freemask[field];
3326 inuse != 0; inuse &= ~(1UL << bit)) {
3327 bit = bsfq(inuse);
3328 pv = &pc->pc_pventry[field * 64 + bit];
3329 va = pv->pv_va;
3330 pde = pmap_pde(pmap, va);
3331 if ((*pde & PG_PS) != 0)
3332 continue;
3333 pte = pmap_pde_to_pte(pde, va);
3334 if ((*pte & PG_W) != 0)
3335 continue;
3336 tpte = pte_load_clear(pte);
3337 if ((tpte & PG_G) != 0)
3338 pmap_invalidate_page(pmap, va);
3339 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3340 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3341 vm_page_dirty(m);
3342 if ((tpte & PG_A) != 0)
3343 vm_page_aflag_set(m, PGA_REFERENCED);
3344 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3345 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3346 m->md.pv_gen++;
3347 if (TAILQ_EMPTY(&m->md.pv_list) &&
3348 (m->flags & PG_FICTITIOUS) == 0) {
3349 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3350 if (TAILQ_EMPTY(&pvh->pv_list)) {
3351 vm_page_aflag_clear(m,
3352 PGA_WRITEABLE);
3353 }
3354 }
3355 pmap_delayed_invl_page(m);
3356 pc->pc_map[field] |= 1UL << bit;
3357 pmap_unuse_pt(pmap, va, *pde, &free);
3358 freed++;
3359 }
3360 }
3361 if (freed == 0) {
3362 mtx_lock(&pv_chunks_mutex);
3363 goto next_chunk;
3364 }
3365 /* Every freed mapping is for a 4 KB page. */
3366 pmap_resident_count_dec(pmap, freed);
3367 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
3368 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
3369 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
3370 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3371 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
3372 pc->pc_map[2] == PC_FREE2) {
3373 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3374 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3375 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3376 /* Entire chunk is free; return it. */
3377 m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3378 dump_drop_page(m_pc->phys_addr);
3379 mtx_lock(&pv_chunks_mutex);
3380 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3381 break;
3382 }
3383 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3384 mtx_lock(&pv_chunks_mutex);
3385 /* One freed pv entry in locked_pmap is sufficient. */
3386 if (pmap == locked_pmap)
3387 break;
3388 next_chunk:
3389 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3390 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
3391 if (active_reclaims == 1 && pmap != NULL) {
3392 /*
3393 * Rotate the pv chunks list so that we do not
3394 * scan the same pv chunks that could not be
3395 * freed (because they contained a wired
3396 * and/or superpage mapping) on every
3397 * invocation of reclaim_pv_chunk().
3398 */
3399 while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
3400 MPASS(pc->pc_pmap != NULL);
3401 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3402 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3403 }
3404 }
3405 }
3406 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3407 TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
3408 active_reclaims--;
3409 mtx_unlock(&pv_chunks_mutex);
3410 reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
3411 if (m_pc == NULL && !SLIST_EMPTY(&free)) {
3412 m_pc = SLIST_FIRST(&free);
3413 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3414 /* Recycle a freed page table page. */
3415 m_pc->wire_count = 1;
3416 }
3417 pmap_free_zero_pages(&free);
3418 return (m_pc);
3419 }
3420
3421 /*
3422 * free the pv_entry back to the free list
3423 */
3424 static void
3425 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3426 {
3427 struct pv_chunk *pc;
3428 int idx, field, bit;
3429
3430 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3431 PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3432 PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3433 PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3434 pc = pv_to_chunk(pv);
3435 idx = pv - &pc->pc_pventry[0];
3436 field = idx / 64;
3437 bit = idx % 64;
3438 pc->pc_map[field] |= 1ul << bit;
3439 if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3440 pc->pc_map[2] != PC_FREE2) {
3441 /* 98% of the time, pc is already at the head of the list. */
3442 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3443 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3444 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3445 }
3446 return;
3447 }
3448 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3449 free_pv_chunk(pc);
3450 }
3451
3452 static void
3453 free_pv_chunk(struct pv_chunk *pc)
3454 {
3455 vm_page_t m;
3456
3457 mtx_lock(&pv_chunks_mutex);
3458 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3459 mtx_unlock(&pv_chunks_mutex);
3460 PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3461 PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3462 PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3463 /* entire chunk is free, return it */
3464 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3465 dump_drop_page(m->phys_addr);
3466 vm_page_unwire(m, PQ_NONE);
3467 vm_page_free(m);
3468 }
3469
3470 /*
3471 * Returns a new PV entry, allocating a new PV chunk from the system when
3472 * needed. If this PV chunk allocation fails and a PV list lock pointer was
3473 * given, a PV chunk is reclaimed from an arbitrary pmap. Otherwise, NULL is
3474 * returned.
3475 *
3476 * The given PV list lock may be released.
3477 */
3478 static pv_entry_t
3479 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3480 {
3481 int bit, field;
3482 pv_entry_t pv;
3483 struct pv_chunk *pc;
3484 vm_page_t m;
3485
3486 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3487 PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3488 retry:
3489 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3490 if (pc != NULL) {
3491 for (field = 0; field < _NPCM; field++) {
3492 if (pc->pc_map[field]) {
3493 bit = bsfq(pc->pc_map[field]);
3494 break;
3495 }
3496 }
3497 if (field < _NPCM) {
3498 pv = &pc->pc_pventry[field * 64 + bit];
3499 pc->pc_map[field] &= ~(1ul << bit);
3500 /* If this was the last item, move it to tail */
3501 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3502 pc->pc_map[2] == 0) {
3503 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3504 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3505 pc_list);
3506 }
3507 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3508 PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3509 return (pv);
3510 }
3511 }
3512 /* No free items, allocate another chunk */
3513 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3514 VM_ALLOC_WIRED);
3515 if (m == NULL) {
3516 if (lockp == NULL) {
3517 PV_STAT(pc_chunk_tryfail++);
3518 return (NULL);
3519 }
3520 m = reclaim_pv_chunk(pmap, lockp);
3521 if (m == NULL)
3522 goto retry;
3523 }
3524 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3525 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3526 dump_add_page(m->phys_addr);
3527 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3528 pc->pc_pmap = pmap;
3529 pc->pc_map[0] = PC_FREE0 & ~1ul; /* preallocated bit 0 */
3530 pc->pc_map[1] = PC_FREE1;
3531 pc->pc_map[2] = PC_FREE2;
3532 mtx_lock(&pv_chunks_mutex);
3533 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3534 mtx_unlock(&pv_chunks_mutex);
3535 pv = &pc->pc_pventry[0];
3536 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3537 PV_STAT(atomic_add_long(&pv_entry_count, 1));
3538 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3539 return (pv);
3540 }
3541
3542 /*
3543 * Returns the number of one bits within the given PV chunk map.
3544 *
3545 * The erratas for Intel processors state that "POPCNT Instruction May
3546 * Take Longer to Execute Than Expected". It is believed that the
3547 * issue is the spurious dependency on the destination register.
3548 * Provide a hint to the register rename logic that the destination
3549 * value is overwritten, by clearing it, as suggested in the
3550 * optimization manual. It should be cheap for unaffected processors
3551 * as well.
3552 *
3553 * Reference numbers for erratas are
3554 * 4th Gen Core: HSD146
3555 * 5th Gen Core: BDM85
3556 * 6th Gen Core: SKL029
3557 */
3558 static int
3559 popcnt_pc_map_pq(uint64_t *map)
3560 {
3561 u_long result, tmp;
3562
3563 __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3564 "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3565 "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3566 : "=&r" (result), "=&r" (tmp)
3567 : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3568 return (result);
3569 }
3570
3571 /*
3572 * Ensure that the number of spare PV entries in the specified pmap meets or
3573 * exceeds the given count, "needed".
3574 *
3575 * The given PV list lock may be released.
3576 */
3577 static void
3578 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3579 {
3580 struct pch new_tail;
3581 struct pv_chunk *pc;
3582 vm_page_t m;
3583 int avail, free;
3584 bool reclaimed;
3585
3586 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3587 KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3588
3589 /*
3590 * Newly allocated PV chunks must be stored in a private list until
3591 * the required number of PV chunks have been allocated. Otherwise,
3592 * reclaim_pv_chunk() could recycle one of these chunks. In
3593 * contrast, these chunks must be added to the pmap upon allocation.
3594 */
3595 TAILQ_INIT(&new_tail);
3596 retry:
3597 avail = 0;
3598 TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3599 #ifndef __POPCNT__
3600 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3601 bit_count((bitstr_t *)pc->pc_map, 0,
3602 sizeof(pc->pc_map) * NBBY, &free);
3603 else
3604 #endif
3605 free = popcnt_pc_map_pq(pc->pc_map);
3606 if (free == 0)
3607 break;
3608 avail += free;
3609 if (avail >= needed)
3610 break;
3611 }
3612 for (reclaimed = false; avail < needed; avail += _NPCPV) {
3613 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3614 VM_ALLOC_WIRED);
3615 if (m == NULL) {
3616 m = reclaim_pv_chunk(pmap, lockp);
3617 if (m == NULL)
3618 goto retry;
3619 reclaimed = true;
3620 }
3621 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3622 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3623 dump_add_page(m->phys_addr);
3624 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3625 pc->pc_pmap = pmap;
3626 pc->pc_map[0] = PC_FREE0;
3627 pc->pc_map[1] = PC_FREE1;
3628 pc->pc_map[2] = PC_FREE2;
3629 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3630 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3631 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3632
3633 /*
3634 * The reclaim might have freed a chunk from the current pmap.
3635 * If that chunk contained available entries, we need to
3636 * re-count the number of available entries.
3637 */
3638 if (reclaimed)
3639 goto retry;
3640 }
3641 if (!TAILQ_EMPTY(&new_tail)) {
3642 mtx_lock(&pv_chunks_mutex);
3643 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3644 mtx_unlock(&pv_chunks_mutex);
3645 }
3646 }
3647
3648 /*
3649 * First find and then remove the pv entry for the specified pmap and virtual
3650 * address from the specified pv list. Returns the pv entry if found and NULL
3651 * otherwise. This operation can be performed on pv lists for either 4KB or
3652 * 2MB page mappings.
3653 */
3654 static __inline pv_entry_t
3655 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3656 {
3657 pv_entry_t pv;
3658
3659 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3660 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3661 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3662 pvh->pv_gen++;
3663 break;
3664 }
3665 }
3666 return (pv);
3667 }
3668
3669 /*
3670 * After demotion from a 2MB page mapping to 512 4KB page mappings,
3671 * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3672 * entries for each of the 4KB page mappings.
3673 */
3674 static void
3675 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3676 struct rwlock **lockp)
3677 {
3678 struct md_page *pvh;
3679 struct pv_chunk *pc;
3680 pv_entry_t pv;
3681 vm_offset_t va_last;
3682 vm_page_t m;
3683 int bit, field;
3684
3685 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3686 KASSERT((pa & PDRMASK) == 0,
3687 ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3688 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3689
3690 /*
3691 * Transfer the 2mpage's pv entry for this mapping to the first
3692 * page's pv list. Once this transfer begins, the pv list lock
3693 * must not be released until the last pv entry is reinstantiated.
3694 */
3695 pvh = pa_to_pvh(pa);
3696 va = trunc_2mpage(va);
3697 pv = pmap_pvh_remove(pvh, pmap, va);
3698 KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3699 m = PHYS_TO_VM_PAGE(pa);
3700 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3701 m->md.pv_gen++;
3702 /* Instantiate the remaining NPTEPG - 1 pv entries. */
3703 PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3704 va_last = va + NBPDR - PAGE_SIZE;
3705 for (;;) {
3706 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3707 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3708 pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3709 for (field = 0; field < _NPCM; field++) {
3710 while (pc->pc_map[field]) {
3711 bit = bsfq(pc->pc_map[field]);
3712 pc->pc_map[field] &= ~(1ul << bit);
3713 pv = &pc->pc_pventry[field * 64 + bit];
3714 va += PAGE_SIZE;
3715 pv->pv_va = va;
3716 m++;
3717 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3718 ("pmap_pv_demote_pde: page %p is not managed", m));
3719 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3720 m->md.pv_gen++;
3721 if (va == va_last)
3722 goto out;
3723 }
3724 }
3725 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3726 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3727 }
3728 out:
3729 if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3730 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3731 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3732 }
3733 PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3734 PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3735 }
3736
3737 #if VM_NRESERVLEVEL > 0
3738 /*
3739 * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3740 * replace the many pv entries for the 4KB page mappings by a single pv entry
3741 * for the 2MB page mapping.
3742 */
3743 static void
3744 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3745 struct rwlock **lockp)
3746 {
3747 struct md_page *pvh;
3748 pv_entry_t pv;
3749 vm_offset_t va_last;
3750 vm_page_t m;
3751
3752 KASSERT((pa & PDRMASK) == 0,
3753 ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3754 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3755
3756 /*
3757 * Transfer the first page's pv entry for this mapping to the 2mpage's
3758 * pv list. Aside from avoiding the cost of a call to get_pv_entry(),
3759 * a transfer avoids the possibility that get_pv_entry() calls
3760 * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3761 * mappings that is being promoted.
3762 */
3763 m = PHYS_TO_VM_PAGE(pa);
3764 va = trunc_2mpage(va);
3765 pv = pmap_pvh_remove(&m->md, pmap, va);
3766 KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3767 pvh = pa_to_pvh(pa);
3768 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3769 pvh->pv_gen++;
3770 /* Free the remaining NPTEPG - 1 pv entries. */
3771 va_last = va + NBPDR - PAGE_SIZE;
3772 do {
3773 m++;
3774 va += PAGE_SIZE;
3775 pmap_pvh_free(&m->md, pmap, va);
3776 } while (va < va_last);
3777 }
3778 #endif /* VM_NRESERVLEVEL > 0 */
3779
3780 /*
3781 * First find and then destroy the pv entry for the specified pmap and virtual
3782 * address. This operation can be performed on pv lists for either 4KB or 2MB
3783 * page mappings.
3784 */
3785 static void
3786 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3787 {
3788 pv_entry_t pv;
3789
3790 pv = pmap_pvh_remove(pvh, pmap, va);
3791 KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3792 free_pv_entry(pmap, pv);
3793 }
3794
3795 /*
3796 * Conditionally create the PV entry for a 4KB page mapping if the required
3797 * memory can be allocated without resorting to reclamation.
3798 */
3799 static boolean_t
3800 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3801 struct rwlock **lockp)
3802 {
3803 pv_entry_t pv;
3804
3805 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3806 /* Pass NULL instead of the lock pointer to disable reclamation. */
3807 if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3808 pv->pv_va = va;
3809 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3810 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3811 m->md.pv_gen++;
3812 return (TRUE);
3813 } else
3814 return (FALSE);
3815 }
3816
3817 /*
3818 * Create the PV entry for a 2MB page mapping. Always returns true unless the
3819 * flag PMAP_ENTER_NORECLAIM is specified. If that flag is specified, returns
3820 * false if the PV entry cannot be allocated without resorting to reclamation.
3821 */
3822 static bool
3823 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
3824 struct rwlock **lockp)
3825 {
3826 struct md_page *pvh;
3827 pv_entry_t pv;
3828 vm_paddr_t pa;
3829
3830 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3831 /* Pass NULL instead of the lock pointer to disable reclamation. */
3832 if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3833 NULL : lockp)) == NULL)
3834 return (false);
3835 pv->pv_va = va;
3836 pa = pde & PG_PS_FRAME;
3837 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3838 pvh = pa_to_pvh(pa);
3839 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3840 pvh->pv_gen++;
3841 return (true);
3842 }
3843
3844 /*
3845 * Fills a page table page with mappings to consecutive physical pages.
3846 */
3847 static void
3848 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3849 {
3850 pt_entry_t *pte;
3851
3852 for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3853 *pte = newpte;
3854 newpte += PAGE_SIZE;
3855 }
3856 }
3857
3858 /*
3859 * Tries to demote a 2MB page mapping. If demotion fails, the 2MB page
3860 * mapping is invalidated.
3861 */
3862 static boolean_t
3863 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3864 {
3865 struct rwlock *lock;
3866 boolean_t rv;
3867
3868 lock = NULL;
3869 rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3870 if (lock != NULL)
3871 rw_wunlock(lock);
3872 return (rv);
3873 }
3874
3875 static boolean_t
3876 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3877 struct rwlock **lockp)
3878 {
3879 pd_entry_t newpde, oldpde;
3880 pt_entry_t *firstpte, newpte;
3881 pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3882 vm_paddr_t mptepa;
3883 vm_page_t mpte;
3884 struct spglist free;
3885 vm_offset_t sva;
3886 int PG_PTE_CACHE;
3887
3888 PG_G = pmap_global_bit(pmap);
3889 PG_A = pmap_accessed_bit(pmap);
3890 PG_M = pmap_modified_bit(pmap);
3891 PG_RW = pmap_rw_bit(pmap);
3892 PG_V = pmap_valid_bit(pmap);
3893 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3894
3895 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3896 oldpde = *pde;
3897 KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3898 ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3899 if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
3900 NULL) {
3901 KASSERT((oldpde & PG_W) == 0,
3902 ("pmap_demote_pde: page table page for a wired mapping"
3903 " is missing"));
3904
3905 /*
3906 * Invalidate the 2MB page mapping and return "failure" if the
3907 * mapping was never accessed or the allocation of the new
3908 * page table page fails. If the 2MB page mapping belongs to
3909 * the direct map region of the kernel's address space, then
3910 * the page allocation request specifies the highest possible
3911 * priority (VM_ALLOC_INTERRUPT). Otherwise, the priority is
3912 * normal. Page table pages are preallocated for every other
3913 * part of the kernel address space, so the direct map region
3914 * is the only part of the kernel address space that must be
3915 * handled here.
3916 */
3917 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3918 pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3919 DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3920 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3921 SLIST_INIT(&free);
3922 sva = trunc_2mpage(va);
3923 pmap_remove_pde(pmap, pde, sva, &free, lockp);
3924 if ((oldpde & PG_G) == 0)
3925 pmap_invalidate_pde_page(pmap, sva, oldpde);
3926 pmap_free_zero_pages(&free);
3927 CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3928 " in pmap %p", va, pmap);
3929 return (FALSE);
3930 }
3931 if (va < VM_MAXUSER_ADDRESS)
3932 pmap_resident_count_inc(pmap, 1);
3933 }
3934 mptepa = VM_PAGE_TO_PHYS(mpte);
3935 firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3936 newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3937 KASSERT((oldpde & PG_A) != 0,
3938 ("pmap_demote_pde: oldpde is missing PG_A"));
3939 KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3940 ("pmap_demote_pde: oldpde is missing PG_M"));
3941 newpte = oldpde & ~PG_PS;
3942 newpte = pmap_swap_pat(pmap, newpte);
3943
3944 /*
3945 * If the page table page is new, initialize it.
3946 */
3947 if (mpte->wire_count == 1) {
3948 mpte->wire_count = NPTEPG;
3949 pmap_fill_ptp(firstpte, newpte);
3950 }
3951 KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3952 ("pmap_demote_pde: firstpte and newpte map different physical"
3953 " addresses"));
3954
3955 /*
3956 * If the mapping has changed attributes, update the page table
3957 * entries.
3958 */
3959 if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3960 pmap_fill_ptp(firstpte, newpte);
3961
3962 /*
3963 * The spare PV entries must be reserved prior to demoting the
3964 * mapping, that is, prior to changing the PDE. Otherwise, the state
3965 * of the PDE and the PV lists will be inconsistent, which can result
3966 * in reclaim_pv_chunk() attempting to remove a PV entry from the
3967 * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3968 * PV entry for the 2MB page mapping that is being demoted.
3969 */
3970 if ((oldpde & PG_MANAGED) != 0)
3971 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3972
3973 /*
3974 * Demote the mapping. This pmap is locked. The old PDE has
3975 * PG_A set. If the old PDE has PG_RW set, it also has PG_M
3976 * set. Thus, there is no danger of a race with another
3977 * processor changing the setting of PG_A and/or PG_M between
3978 * the read above and the store below.
3979 */
3980 if (workaround_erratum383)
3981 pmap_update_pde(pmap, va, pde, newpde);
3982 else
3983 pde_store(pde, newpde);
3984
3985 /*
3986 * Invalidate a stale recursive mapping of the page table page.
3987 */
3988 if (va >= VM_MAXUSER_ADDRESS)
3989 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3990
3991 /*
3992 * Demote the PV entry.
3993 */
3994 if ((oldpde & PG_MANAGED) != 0)
3995 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3996
3997 atomic_add_long(&pmap_pde_demotions, 1);
3998 CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3999 " in pmap %p", va, pmap);
4000 return (TRUE);
4001 }
4002
4003 /*
4004 * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
4005 */
4006 static void
4007 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
4008 {
4009 pd_entry_t newpde;
4010 vm_paddr_t mptepa;
4011 vm_page_t mpte;
4012
4013 KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
4014 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4015 mpte = pmap_remove_pt_page(pmap, va);
4016 if (mpte == NULL)
4017 panic("pmap_remove_kernel_pde: Missing pt page.");
4018
4019 mptepa = VM_PAGE_TO_PHYS(mpte);
4020 newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
4021
4022 /*
4023 * Initialize the page table page.
4024 */
4025 pagezero((void *)PHYS_TO_DMAP(mptepa));
4026
4027 /*
4028 * Demote the mapping.
4029 */
4030 if (workaround_erratum383)
4031 pmap_update_pde(pmap, va, pde, newpde);
4032 else
4033 pde_store(pde, newpde);
4034
4035 /*
4036 * Invalidate a stale recursive mapping of the page table page.
4037 */
4038 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
4039 }
4040
4041 /*
4042 * pmap_remove_pde: do the things to unmap a superpage in a process
4043 */
4044 static int
4045 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
4046 struct spglist *free, struct rwlock **lockp)
4047 {
4048 struct md_page *pvh;
4049 pd_entry_t oldpde;
4050 vm_offset_t eva, va;
4051 vm_page_t m, mpte;
4052 pt_entry_t PG_G, PG_A, PG_M, PG_RW;
4053
4054 PG_G = pmap_global_bit(pmap);
4055 PG_A = pmap_accessed_bit(pmap);
4056 PG_M = pmap_modified_bit(pmap);
4057 PG_RW = pmap_rw_bit(pmap);
4058
4059 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4060 KASSERT((sva & PDRMASK) == 0,
4061 ("pmap_remove_pde: sva is not 2mpage aligned"));
4062 oldpde = pte_load_clear(pdq);
4063 if (oldpde & PG_W)
4064 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
4065 if ((oldpde & PG_G) != 0)
4066 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4067 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
4068 if (oldpde & PG_MANAGED) {
4069 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
4070 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
4071 pmap_pvh_free(pvh, pmap, sva);
4072 eva = sva + NBPDR;
4073 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4074 va < eva; va += PAGE_SIZE, m++) {
4075 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
4076 vm_page_dirty(m);
4077 if (oldpde & PG_A)
4078 vm_page_aflag_set(m, PGA_REFERENCED);
4079 if (TAILQ_EMPTY(&m->md.pv_list) &&
4080 TAILQ_EMPTY(&pvh->pv_list))
4081 vm_page_aflag_clear(m, PGA_WRITEABLE);
4082 pmap_delayed_invl_page(m);
4083 }
4084 }
4085 if (pmap == kernel_pmap) {
4086 pmap_remove_kernel_pde(pmap, pdq, sva);
4087 } else {
4088 mpte = pmap_remove_pt_page(pmap, sva);
4089 if (mpte != NULL) {
4090 pmap_resident_count_dec(pmap, 1);
4091 KASSERT(mpte->wire_count == NPTEPG,
4092 ("pmap_remove_pde: pte page wire count error"));
4093 mpte->wire_count = 0;
4094 pmap_add_delayed_free_list(mpte, free, FALSE);
4095 }
4096 }
4097 return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
4098 }
4099
4100 /*
4101 * pmap_remove_pte: do the things to unmap a page in a process
4102 */
4103 static int
4104 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
4105 pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
4106 {
4107 struct md_page *pvh;
4108 pt_entry_t oldpte, PG_A, PG_M, PG_RW;
4109 vm_page_t m;
4110
4111 PG_A = pmap_accessed_bit(pmap);
4112 PG_M = pmap_modified_bit(pmap);
4113 PG_RW = pmap_rw_bit(pmap);
4114
4115 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4116 oldpte = pte_load_clear(ptq);
4117 if (oldpte & PG_W)
4118 pmap->pm_stats.wired_count -= 1;
4119 pmap_resident_count_dec(pmap, 1);
4120 if (oldpte & PG_MANAGED) {
4121 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
4122 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4123 vm_page_dirty(m);
4124 if (oldpte & PG_A)
4125 vm_page_aflag_set(m, PGA_REFERENCED);
4126 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
4127 pmap_pvh_free(&m->md, pmap, va);
4128 if (TAILQ_EMPTY(&m->md.pv_list) &&
4129 (m->flags & PG_FICTITIOUS) == 0) {
4130 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4131 if (TAILQ_EMPTY(&pvh->pv_list))
4132 vm_page_aflag_clear(m, PGA_WRITEABLE);
4133 }
4134 pmap_delayed_invl_page(m);
4135 }
4136 return (pmap_unuse_pt(pmap, va, ptepde, free));
4137 }
4138
4139 /*
4140 * Remove a single page from a process address space
4141 */
4142 static void
4143 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
4144 struct spglist *free)
4145 {
4146 struct rwlock *lock;
4147 pt_entry_t *pte, PG_V;
4148
4149 PG_V = pmap_valid_bit(pmap);
4150 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4151 if ((*pde & PG_V) == 0)
4152 return;
4153 pte = pmap_pde_to_pte(pde, va);
4154 if ((*pte & PG_V) == 0)
4155 return;
4156 lock = NULL;
4157 pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
4158 if (lock != NULL)
4159 rw_wunlock(lock);
4160 pmap_invalidate_page(pmap, va);
4161 }
4162
4163 /*
4164 * Removes the specified range of addresses from the page table page.
4165 */
4166 static bool
4167 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
4168 pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
4169 {
4170 pt_entry_t PG_G, *pte;
4171 vm_offset_t va;
4172 bool anyvalid;
4173
4174 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4175 PG_G = pmap_global_bit(pmap);
4176 anyvalid = false;
4177 va = eva;
4178 for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
4179 sva += PAGE_SIZE) {
4180 if (*pte == 0) {
4181 if (va != eva) {
4182 pmap_invalidate_range(pmap, va, sva);
4183 va = eva;
4184 }
4185 continue;
4186 }
4187 if ((*pte & PG_G) == 0)
4188 anyvalid = true;
4189 else if (va == eva)
4190 va = sva;
4191 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
4192 sva += PAGE_SIZE;
4193 break;
4194 }
4195 }
4196 if (va != eva)
4197 pmap_invalidate_range(pmap, va, sva);
4198 return (anyvalid);
4199 }
4200
4201 /*
4202 * Remove the given range of addresses from the specified map.
4203 *
4204 * It is assumed that the start and end are properly
4205 * rounded to the page size.
4206 */
4207 void
4208 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4209 {
4210 struct rwlock *lock;
4211 vm_offset_t va_next;
4212 pml4_entry_t *pml4e;
4213 pdp_entry_t *pdpe;
4214 pd_entry_t ptpaddr, *pde;
4215 pt_entry_t PG_G, PG_V;
4216 struct spglist free;
4217 int anyvalid;
4218
4219 PG_G = pmap_global_bit(pmap);
4220 PG_V = pmap_valid_bit(pmap);
4221
4222 /*
4223 * Perform an unsynchronized read. This is, however, safe.
4224 */
4225 if (pmap->pm_stats.resident_count == 0)
4226 return;
4227
4228 anyvalid = 0;
4229 SLIST_INIT(&free);
4230
4231 pmap_delayed_invl_started();
4232 PMAP_LOCK(pmap);
4233
4234 /*
4235 * special handling of removing one page. a very
4236 * common operation and easy to short circuit some
4237 * code.
4238 */
4239 if (sva + PAGE_SIZE == eva) {
4240 pde = pmap_pde(pmap, sva);
4241 if (pde && (*pde & PG_PS) == 0) {
4242 pmap_remove_page(pmap, sva, pde, &free);
4243 goto out;
4244 }
4245 }
4246
4247 lock = NULL;
4248 for (; sva < eva; sva = va_next) {
4249
4250 if (pmap->pm_stats.resident_count == 0)
4251 break;
4252
4253 pml4e = pmap_pml4e(pmap, sva);
4254 if ((*pml4e & PG_V) == 0) {
4255 va_next = (sva + NBPML4) & ~PML4MASK;
4256 if (va_next < sva)
4257 va_next = eva;
4258 continue;
4259 }
4260
4261 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4262 if ((*pdpe & PG_V) == 0) {
4263 va_next = (sva + NBPDP) & ~PDPMASK;
4264 if (va_next < sva)
4265 va_next = eva;
4266 continue;
4267 }
4268
4269 /*
4270 * Calculate index for next page table.
4271 */
4272 va_next = (sva + NBPDR) & ~PDRMASK;
4273 if (va_next < sva)
4274 va_next = eva;
4275
4276 pde = pmap_pdpe_to_pde(pdpe, sva);
4277 ptpaddr = *pde;
4278
4279 /*
4280 * Weed out invalid mappings.
4281 */
4282 if (ptpaddr == 0)
4283 continue;
4284
4285 /*
4286 * Check for large page.
4287 */
4288 if ((ptpaddr & PG_PS) != 0) {
4289 /*
4290 * Are we removing the entire large page? If not,
4291 * demote the mapping and fall through.
4292 */
4293 if (sva + NBPDR == va_next && eva >= va_next) {
4294 /*
4295 * The TLB entry for a PG_G mapping is
4296 * invalidated by pmap_remove_pde().
4297 */
4298 if ((ptpaddr & PG_G) == 0)
4299 anyvalid = 1;
4300 pmap_remove_pde(pmap, pde, sva, &free, &lock);
4301 continue;
4302 } else if (!pmap_demote_pde_locked(pmap, pde, sva,
4303 &lock)) {
4304 /* The large page mapping was destroyed. */
4305 continue;
4306 } else
4307 ptpaddr = *pde;
4308 }
4309
4310 /*
4311 * Limit our scan to either the end of the va represented
4312 * by the current page table page, or to the end of the
4313 * range being removed.
4314 */
4315 if (va_next > eva)
4316 va_next = eva;
4317
4318 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
4319 anyvalid = 1;
4320 }
4321 if (lock != NULL)
4322 rw_wunlock(lock);
4323 out:
4324 if (anyvalid)
4325 pmap_invalidate_all(pmap);
4326 PMAP_UNLOCK(pmap);
4327 pmap_delayed_invl_finished();
4328 pmap_free_zero_pages(&free);
4329 }
4330
4331 /*
4332 * Routine: pmap_remove_all
4333 * Function:
4334 * Removes this physical page from
4335 * all physical maps in which it resides.
4336 * Reflects back modify bits to the pager.
4337 *
4338 * Notes:
4339 * Original versions of this routine were very
4340 * inefficient because they iteratively called
4341 * pmap_remove (slow...)
4342 */
4343
4344 void
4345 pmap_remove_all(vm_page_t m)
4346 {
4347 struct md_page *pvh;
4348 pv_entry_t pv;
4349 pmap_t pmap;
4350 struct rwlock *lock;
4351 pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
4352 pd_entry_t *pde;
4353 vm_offset_t va;
4354 struct spglist free;
4355 int pvh_gen, md_gen;
4356
4357 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4358 ("pmap_remove_all: page %p is not managed", m));
4359 SLIST_INIT(&free);
4360 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4361 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
4362 pa_to_pvh(VM_PAGE_TO_PHYS(m));
4363 retry:
4364 rw_wlock(lock);
4365 while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
4366 pmap = PV_PMAP(pv);
4367 if (!PMAP_TRYLOCK(pmap)) {
4368 pvh_gen = pvh->pv_gen;
4369 rw_wunlock(lock);
4370 PMAP_LOCK(pmap);
4371 rw_wlock(lock);
4372 if (pvh_gen != pvh->pv_gen) {
4373 rw_wunlock(lock);
4374 PMAP_UNLOCK(pmap);
4375 goto retry;
4376 }
4377 }
4378 va = pv->pv_va;
4379 pde = pmap_pde(pmap, va);
4380 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
4381 PMAP_UNLOCK(pmap);
4382 }
4383 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4384 pmap = PV_PMAP(pv);
4385 if (!PMAP_TRYLOCK(pmap)) {
4386 pvh_gen = pvh->pv_gen;
4387 md_gen = m->md.pv_gen;
4388 rw_wunlock(lock);
4389 PMAP_LOCK(pmap);
4390 rw_wlock(lock);
4391 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
4392 rw_wunlock(lock);
4393 PMAP_UNLOCK(pmap);
4394 goto retry;
4395 }
4396 }
4397 PG_A = pmap_accessed_bit(pmap);
4398 PG_M = pmap_modified_bit(pmap);
4399 PG_RW = pmap_rw_bit(pmap);
4400 pmap_resident_count_dec(pmap, 1);
4401 pde = pmap_pde(pmap, pv->pv_va);
4402 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
4403 " a 2mpage in page %p's pv list", m));
4404 pte = pmap_pde_to_pte(pde, pv->pv_va);
4405 tpte = pte_load_clear(pte);
4406 if (tpte & PG_W)
4407 pmap->pm_stats.wired_count--;
4408 if (tpte & PG_A)
4409 vm_page_aflag_set(m, PGA_REFERENCED);
4410
4411 /*
4412 * Update the vm_page_t clean and reference bits.
4413 */
4414 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4415 vm_page_dirty(m);
4416 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
4417 pmap_invalidate_page(pmap, pv->pv_va);
4418 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4419 m->md.pv_gen++;
4420 free_pv_entry(pmap, pv);
4421 PMAP_UNLOCK(pmap);
4422 }
4423 vm_page_aflag_clear(m, PGA_WRITEABLE);
4424 rw_wunlock(lock);
4425 pmap_delayed_invl_wait(m);
4426 pmap_free_zero_pages(&free);
4427 }
4428
4429 /*
4430 * pmap_protect_pde: do the things to protect a 2mpage in a process
4431 */
4432 static boolean_t
4433 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
4434 {
4435 pd_entry_t newpde, oldpde;
4436 vm_offset_t eva, va;
4437 vm_page_t m;
4438 boolean_t anychanged;
4439 pt_entry_t PG_G, PG_M, PG_RW;
4440
4441 PG_G = pmap_global_bit(pmap);
4442 PG_M = pmap_modified_bit(pmap);
4443 PG_RW = pmap_rw_bit(pmap);
4444
4445 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4446 KASSERT((sva & PDRMASK) == 0,
4447 ("pmap_protect_pde: sva is not 2mpage aligned"));
4448 anychanged = FALSE;
4449 retry:
4450 oldpde = newpde = *pde;
4451 if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4452 (PG_MANAGED | PG_M | PG_RW)) {
4453 eva = sva + NBPDR;
4454 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4455 va < eva; va += PAGE_SIZE, m++)
4456 vm_page_dirty(m);
4457 }
4458 if ((prot & VM_PROT_WRITE) == 0)
4459 newpde &= ~(PG_RW | PG_M);
4460 if ((prot & VM_PROT_EXECUTE) == 0)
4461 newpde |= pg_nx;
4462 if (newpde != oldpde) {
4463 /*
4464 * As an optimization to future operations on this PDE, clear
4465 * PG_PROMOTED. The impending invalidation will remove any
4466 * lingering 4KB page mappings from the TLB.
4467 */
4468 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
4469 goto retry;
4470 if ((oldpde & PG_G) != 0)
4471 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4472 else
4473 anychanged = TRUE;
4474 }
4475 return (anychanged);
4476 }
4477
4478 /*
4479 * Set the physical protection on the
4480 * specified range of this map as requested.
4481 */
4482 void
4483 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4484 {
4485 vm_offset_t va_next;
4486 pml4_entry_t *pml4e;
4487 pdp_entry_t *pdpe;
4488 pd_entry_t ptpaddr, *pde;
4489 pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4490 boolean_t anychanged;
4491
4492 KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4493 if (prot == VM_PROT_NONE) {
4494 pmap_remove(pmap, sva, eva);
4495 return;
4496 }
4497
4498 if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4499 (VM_PROT_WRITE|VM_PROT_EXECUTE))
4500 return;
4501
4502 PG_G = pmap_global_bit(pmap);
4503 PG_M = pmap_modified_bit(pmap);
4504 PG_V = pmap_valid_bit(pmap);
4505 PG_RW = pmap_rw_bit(pmap);
4506 anychanged = FALSE;
4507
4508 /*
4509 * Although this function delays and batches the invalidation
4510 * of stale TLB entries, it does not need to call
4511 * pmap_delayed_invl_started() and
4512 * pmap_delayed_invl_finished(), because it does not
4513 * ordinarily destroy mappings. Stale TLB entries from
4514 * protection-only changes need only be invalidated before the
4515 * pmap lock is released, because protection-only changes do
4516 * not destroy PV entries. Even operations that iterate over
4517 * a physical page's PV list of mappings, like
4518 * pmap_remove_write(), acquire the pmap lock for each
4519 * mapping. Consequently, for protection-only changes, the
4520 * pmap lock suffices to synchronize both page table and TLB
4521 * updates.
4522 *
4523 * This function only destroys a mapping if pmap_demote_pde()
4524 * fails. In that case, stale TLB entries are immediately
4525 * invalidated.
4526 */
4527
4528 PMAP_LOCK(pmap);
4529 for (; sva < eva; sva = va_next) {
4530
4531 pml4e = pmap_pml4e(pmap, sva);
4532 if ((*pml4e & PG_V) == 0) {
4533 va_next = (sva + NBPML4) & ~PML4MASK;
4534 if (va_next < sva)
4535 va_next = eva;
4536 continue;
4537 }
4538
4539 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4540 if ((*pdpe & PG_V) == 0) {
4541 va_next = (sva + NBPDP) & ~PDPMASK;
4542 if (va_next < sva)
4543 va_next = eva;
4544 continue;
4545 }
4546
4547 va_next = (sva + NBPDR) & ~PDRMASK;
4548 if (va_next < sva)
4549 va_next = eva;
4550
4551 pde = pmap_pdpe_to_pde(pdpe, sva);
4552 ptpaddr = *pde;
4553
4554 /*
4555 * Weed out invalid mappings.
4556 */
4557 if (ptpaddr == 0)
4558 continue;
4559
4560 /*
4561 * Check for large page.
4562 */
4563 if ((ptpaddr & PG_PS) != 0) {
4564 /*
4565 * Are we protecting the entire large page? If not,
4566 * demote the mapping and fall through.
4567 */
4568 if (sva + NBPDR == va_next && eva >= va_next) {
4569 /*
4570 * The TLB entry for a PG_G mapping is
4571 * invalidated by pmap_protect_pde().
4572 */
4573 if (pmap_protect_pde(pmap, pde, sva, prot))
4574 anychanged = TRUE;
4575 continue;
4576 } else if (!pmap_demote_pde(pmap, pde, sva)) {
4577 /*
4578 * The large page mapping was destroyed.
4579 */
4580 continue;
4581 }
4582 }
4583
4584 if (va_next > eva)
4585 va_next = eva;
4586
4587 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4588 sva += PAGE_SIZE) {
4589 pt_entry_t obits, pbits;
4590 vm_page_t m;
4591
4592 retry:
4593 obits = pbits = *pte;
4594 if ((pbits & PG_V) == 0)
4595 continue;
4596
4597 if ((prot & VM_PROT_WRITE) == 0) {
4598 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4599 (PG_MANAGED | PG_M | PG_RW)) {
4600 m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4601 vm_page_dirty(m);
4602 }
4603 pbits &= ~(PG_RW | PG_M);
4604 }
4605 if ((prot & VM_PROT_EXECUTE) == 0)
4606 pbits |= pg_nx;
4607
4608 if (pbits != obits) {
4609 if (!atomic_cmpset_long(pte, obits, pbits))
4610 goto retry;
4611 if (obits & PG_G)
4612 pmap_invalidate_page(pmap, sva);
4613 else
4614 anychanged = TRUE;
4615 }
4616 }
4617 }
4618 if (anychanged)
4619 pmap_invalidate_all(pmap);
4620 PMAP_UNLOCK(pmap);
4621 }
4622
4623 #if VM_NRESERVLEVEL > 0
4624 static bool
4625 pmap_pde_ept_executable(pmap_t pmap, pd_entry_t pde)
4626 {
4627
4628 if (pmap->pm_type != PT_EPT)
4629 return (false);
4630 return ((pde & EPT_PG_EXECUTE) != 0);
4631 }
4632
4633 /*
4634 * Tries to promote the 512, contiguous 4KB page mappings that are within a
4635 * single page table page (PTP) to a single 2MB page mapping. For promotion
4636 * to occur, two conditions must be met: (1) the 4KB page mappings must map
4637 * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4638 * identical characteristics.
4639 */
4640 static void
4641 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4642 struct rwlock **lockp)
4643 {
4644 pd_entry_t newpde;
4645 pt_entry_t *firstpte, oldpte, pa, *pte;
4646 pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4647 vm_page_t mpte;
4648 int PG_PTE_CACHE;
4649
4650 PG_A = pmap_accessed_bit(pmap);
4651 PG_G = pmap_global_bit(pmap);
4652 PG_M = pmap_modified_bit(pmap);
4653 PG_V = pmap_valid_bit(pmap);
4654 PG_RW = pmap_rw_bit(pmap);
4655 PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4656
4657 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4658
4659 /*
4660 * Examine the first PTE in the specified PTP. Abort if this PTE is
4661 * either invalid, unused, or does not map the first 4KB physical page
4662 * within a 2MB page.
4663 */
4664 firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4665 setpde:
4666 newpde = *firstpte;
4667 if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V) ||
4668 !pmap_allow_2m_x_page(pmap, pmap_pde_ept_executable(pmap,
4669 newpde))) {
4670 atomic_add_long(&pmap_pde_p_failures, 1);
4671 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4672 " in pmap %p", va, pmap);
4673 return;
4674 }
4675 if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4676 /*
4677 * When PG_M is already clear, PG_RW can be cleared without
4678 * a TLB invalidation.
4679 */
4680 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4681 goto setpde;
4682 newpde &= ~PG_RW;
4683 }
4684
4685 /*
4686 * Examine each of the other PTEs in the specified PTP. Abort if this
4687 * PTE maps an unexpected 4KB physical page or does not have identical
4688 * characteristics to the first PTE.
4689 */
4690 pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4691 for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4692 setpte:
4693 oldpte = *pte;
4694 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4695 atomic_add_long(&pmap_pde_p_failures, 1);
4696 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4697 " in pmap %p", va, pmap);
4698 return;
4699 }
4700 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4701 /*
4702 * When PG_M is already clear, PG_RW can be cleared
4703 * without a TLB invalidation.
4704 */
4705 if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4706 goto setpte;
4707 oldpte &= ~PG_RW;
4708 CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4709 " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4710 (va & ~PDRMASK), pmap);
4711 }
4712 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4713 atomic_add_long(&pmap_pde_p_failures, 1);
4714 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4715 " in pmap %p", va, pmap);
4716 return;
4717 }
4718 pa -= PAGE_SIZE;
4719 }
4720
4721 /*
4722 * Save the page table page in its current state until the PDE
4723 * mapping the superpage is demoted by pmap_demote_pde() or
4724 * destroyed by pmap_remove_pde().
4725 */
4726 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4727 KASSERT(mpte >= vm_page_array &&
4728 mpte < &vm_page_array[vm_page_array_size],
4729 ("pmap_promote_pde: page table page is out of range"));
4730 KASSERT(mpte->pindex == pmap_pde_pindex(va),
4731 ("pmap_promote_pde: page table page's pindex is wrong"));
4732 if (pmap_insert_pt_page(pmap, mpte)) {
4733 atomic_add_long(&pmap_pde_p_failures, 1);
4734 CTR2(KTR_PMAP,
4735 "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4736 pmap);
4737 return;
4738 }
4739
4740 /*
4741 * Promote the pv entries.
4742 */
4743 if ((newpde & PG_MANAGED) != 0)
4744 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4745
4746 /*
4747 * Propagate the PAT index to its proper position.
4748 */
4749 newpde = pmap_swap_pat(pmap, newpde);
4750
4751 /*
4752 * Map the superpage.
4753 */
4754 if (workaround_erratum383)
4755 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4756 else
4757 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
4758
4759 atomic_add_long(&pmap_pde_promotions, 1);
4760 CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4761 " in pmap %p", va, pmap);
4762 }
4763 #endif /* VM_NRESERVLEVEL > 0 */
4764
4765 /*
4766 * Insert the given physical page (p) at
4767 * the specified virtual address (v) in the
4768 * target physical map with the protection requested.
4769 *
4770 * If specified, the page will be wired down, meaning
4771 * that the related pte can not be reclaimed.
4772 *
4773 * NB: This is the only routine which MAY NOT lazy-evaluate
4774 * or lose information. That is, this routine must actually
4775 * insert this page into the given map NOW.
4776 *
4777 * When destroying both a page table and PV entry, this function
4778 * performs the TLB invalidation before releasing the PV list
4779 * lock, so we do not need pmap_delayed_invl_page() calls here.
4780 */
4781 int
4782 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4783 u_int flags, int8_t psind)
4784 {
4785 struct rwlock *lock;
4786 pd_entry_t *pde;
4787 pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4788 pt_entry_t newpte, origpte;
4789 pv_entry_t pv;
4790 vm_paddr_t opa, pa;
4791 vm_page_t mpte, om;
4792 int rv;
4793 boolean_t nosleep;
4794
4795 PG_A = pmap_accessed_bit(pmap);
4796 PG_G = pmap_global_bit(pmap);
4797 PG_M = pmap_modified_bit(pmap);
4798 PG_V = pmap_valid_bit(pmap);
4799 PG_RW = pmap_rw_bit(pmap);
4800
4801 va = trunc_page(va);
4802 KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4803 KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4804 ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4805 va));
4806 KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4807 va >= kmi.clean_eva,
4808 ("pmap_enter: managed mapping within the clean submap"));
4809 if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4810 VM_OBJECT_ASSERT_LOCKED(m->object);
4811 KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
4812 ("pmap_enter: flags %u has reserved bits set", flags));
4813 pa = VM_PAGE_TO_PHYS(m);
4814 newpte = (pt_entry_t)(pa | PG_A | PG_V);
4815 if ((flags & VM_PROT_WRITE) != 0)
4816 newpte |= PG_M;
4817 if ((prot & VM_PROT_WRITE) != 0)
4818 newpte |= PG_RW;
4819 KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4820 ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4821 if ((prot & VM_PROT_EXECUTE) == 0)
4822 newpte |= pg_nx;
4823 if ((flags & PMAP_ENTER_WIRED) != 0)
4824 newpte |= PG_W;
4825 if (va < VM_MAXUSER_ADDRESS)
4826 newpte |= PG_U;
4827 if (pmap == kernel_pmap)
4828 newpte |= PG_G;
4829 newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
4830
4831 /*
4832 * Set modified bit gratuitously for writeable mappings if
4833 * the page is unmanaged. We do not want to take a fault
4834 * to do the dirty bit accounting for these mappings.
4835 */
4836 if ((m->oflags & VPO_UNMANAGED) != 0) {
4837 if ((newpte & PG_RW) != 0)
4838 newpte |= PG_M;
4839 } else
4840 newpte |= PG_MANAGED;
4841
4842 lock = NULL;
4843 PMAP_LOCK(pmap);
4844 if (psind == 1) {
4845 /* Assert the required virtual and physical alignment. */
4846 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
4847 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4848 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
4849 goto out;
4850 }
4851 mpte = NULL;
4852
4853 /*
4854 * In the case that a page table page is not
4855 * resident, we are creating it here.
4856 */
4857 retry:
4858 pde = pmap_pde(pmap, va);
4859 if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4860 pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4861 pte = pmap_pde_to_pte(pde, va);
4862 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4863 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4864 mpte->wire_count++;
4865 }
4866 } else if (va < VM_MAXUSER_ADDRESS) {
4867 /*
4868 * Here if the pte page isn't mapped, or if it has been
4869 * deallocated.
4870 */
4871 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4872 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4873 nosleep ? NULL : &lock);
4874 if (mpte == NULL && nosleep) {
4875 rv = KERN_RESOURCE_SHORTAGE;
4876 goto out;
4877 }
4878 goto retry;
4879 } else
4880 panic("pmap_enter: invalid page directory va=%#lx", va);
4881
4882 origpte = *pte;
4883 pv = NULL;
4884
4885 /*
4886 * Is the specified virtual address already mapped?
4887 */
4888 if ((origpte & PG_V) != 0) {
4889 /*
4890 * Wiring change, just update stats. We don't worry about
4891 * wiring PT pages as they remain resident as long as there
4892 * are valid mappings in them. Hence, if a user page is wired,
4893 * the PT page will be also.
4894 */
4895 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4896 pmap->pm_stats.wired_count++;
4897 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4898 pmap->pm_stats.wired_count--;
4899
4900 /*
4901 * Remove the extra PT page reference.
4902 */
4903 if (mpte != NULL) {
4904 mpte->wire_count--;
4905 KASSERT(mpte->wire_count > 0,
4906 ("pmap_enter: missing reference to page table page,"
4907 " va: 0x%lx", va));
4908 }
4909
4910 /*
4911 * Has the physical page changed?
4912 */
4913 opa = origpte & PG_FRAME;
4914 if (opa == pa) {
4915 /*
4916 * No, might be a protection or wiring change.
4917 */
4918 if ((origpte & PG_MANAGED) != 0 &&
4919 (newpte & PG_RW) != 0)
4920 vm_page_aflag_set(m, PGA_WRITEABLE);
4921 if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4922 goto unchanged;
4923 goto validate;
4924 }
4925
4926 /*
4927 * The physical page has changed. Temporarily invalidate
4928 * the mapping. This ensures that all threads sharing the
4929 * pmap keep a consistent view of the mapping, which is
4930 * necessary for the correct handling of COW faults. It
4931 * also permits reuse of the old mapping's PV entry,
4932 * avoiding an allocation.
4933 *
4934 * For consistency, handle unmanaged mappings the same way.
4935 */
4936 origpte = pte_load_clear(pte);
4937 KASSERT((origpte & PG_FRAME) == opa,
4938 ("pmap_enter: unexpected pa update for %#lx", va));
4939 if ((origpte & PG_MANAGED) != 0) {
4940 om = PHYS_TO_VM_PAGE(opa);
4941
4942 /*
4943 * The pmap lock is sufficient to synchronize with
4944 * concurrent calls to pmap_page_test_mappings() and
4945 * pmap_ts_referenced().
4946 */
4947 if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4948 vm_page_dirty(om);
4949 if ((origpte & PG_A) != 0)
4950 vm_page_aflag_set(om, PGA_REFERENCED);
4951 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4952 pv = pmap_pvh_remove(&om->md, pmap, va);
4953 if ((newpte & PG_MANAGED) == 0)
4954 free_pv_entry(pmap, pv);
4955 if ((om->aflags & PGA_WRITEABLE) != 0 &&
4956 TAILQ_EMPTY(&om->md.pv_list) &&
4957 ((om->flags & PG_FICTITIOUS) != 0 ||
4958 TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4959 vm_page_aflag_clear(om, PGA_WRITEABLE);
4960 }
4961 if ((origpte & PG_A) != 0)
4962 pmap_invalidate_page(pmap, va);
4963 origpte = 0;
4964 } else {
4965 /*
4966 * Increment the counters.
4967 */
4968 if ((newpte & PG_W) != 0)
4969 pmap->pm_stats.wired_count++;
4970 pmap_resident_count_inc(pmap, 1);
4971 }
4972
4973 /*
4974 * Enter on the PV list if part of our managed memory.
4975 */
4976 if ((newpte & PG_MANAGED) != 0) {
4977 if (pv == NULL) {
4978 pv = get_pv_entry(pmap, &lock);
4979 pv->pv_va = va;
4980 }
4981 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4982 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4983 m->md.pv_gen++;
4984 if ((newpte & PG_RW) != 0)
4985 vm_page_aflag_set(m, PGA_WRITEABLE);
4986 }
4987
4988 /*
4989 * Update the PTE.
4990 */
4991 if ((origpte & PG_V) != 0) {
4992 validate:
4993 origpte = pte_load_store(pte, newpte);
4994 KASSERT((origpte & PG_FRAME) == pa,
4995 ("pmap_enter: unexpected pa update for %#lx", va));
4996 if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
4997 (PG_M | PG_RW)) {
4998 if ((origpte & PG_MANAGED) != 0)
4999 vm_page_dirty(m);
5000
5001 /*
5002 * Although the PTE may still have PG_RW set, TLB
5003 * invalidation may nonetheless be required because
5004 * the PTE no longer has PG_M set.
5005 */
5006 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
5007 /*
5008 * This PTE change does not require TLB invalidation.
5009 */
5010 goto unchanged;
5011 }
5012 if ((origpte & PG_A) != 0)
5013 pmap_invalidate_page(pmap, va);
5014 } else
5015 pte_store(pte, newpte);
5016
5017 unchanged:
5018
5019 #if VM_NRESERVLEVEL > 0
5020 /*
5021 * If both the page table page and the reservation are fully
5022 * populated, then attempt promotion.
5023 */
5024 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
5025 pmap_ps_enabled(pmap) &&
5026 (m->flags & PG_FICTITIOUS) == 0 &&
5027 vm_reserv_level_iffullpop(m) == 0)
5028 pmap_promote_pde(pmap, pde, va, &lock);
5029 #endif
5030
5031 rv = KERN_SUCCESS;
5032 out:
5033 if (lock != NULL)
5034 rw_wunlock(lock);
5035 PMAP_UNLOCK(pmap);
5036 return (rv);
5037 }
5038
5039 /*
5040 * Tries to create a read- and/or execute-only 2MB page mapping. Returns true
5041 * if successful. Returns false if (1) a page table page cannot be allocated
5042 * without sleeping, (2) a mapping already exists at the specified virtual
5043 * address, or (3) a PV entry cannot be allocated without reclaiming another
5044 * PV entry.
5045 */
5046 static bool
5047 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
5048 struct rwlock **lockp)
5049 {
5050 pd_entry_t newpde;
5051 pt_entry_t PG_V;
5052
5053 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5054 PG_V = pmap_valid_bit(pmap);
5055 newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
5056 PG_PS | PG_V;
5057 if ((m->oflags & VPO_UNMANAGED) == 0)
5058 newpde |= PG_MANAGED;
5059 if ((prot & VM_PROT_EXECUTE) == 0)
5060 newpde |= pg_nx;
5061 if (va < VM_MAXUSER_ADDRESS)
5062 newpde |= PG_U;
5063 return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
5064 PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
5065 KERN_SUCCESS);
5066 }
5067
5068 /*
5069 * Tries to create the specified 2MB page mapping. Returns KERN_SUCCESS if
5070 * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
5071 * otherwise. Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
5072 * a mapping already exists at the specified virtual address. Returns
5073 * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
5074 * page allocation failed. Returns KERN_RESOURCE_SHORTAGE if
5075 * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
5076 *
5077 * The parameter "m" is only used when creating a managed, writeable mapping.
5078 */
5079 static int
5080 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
5081 vm_page_t m, struct rwlock **lockp)
5082 {
5083 struct spglist free;
5084 pd_entry_t oldpde, *pde;
5085 pt_entry_t PG_G, PG_RW, PG_V;
5086 vm_page_t mt, pdpg;
5087
5088 PG_G = pmap_global_bit(pmap);
5089 PG_RW = pmap_rw_bit(pmap);
5090 KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
5091 ("pmap_enter_pde: newpde is missing PG_M"));
5092 PG_V = pmap_valid_bit(pmap);
5093 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5094
5095 if (!pmap_allow_2m_x_page(pmap, pmap_pde_ept_executable(pmap,
5096 newpde))) {
5097 CTR2(KTR_PMAP, "pmap_enter_pde: 2m x blocked for va %#lx"
5098 " in pmap %p", va, pmap);
5099 return (KERN_FAILURE);
5100 }
5101 if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
5102 NULL : lockp)) == NULL) {
5103 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5104 " in pmap %p", va, pmap);
5105 return (KERN_RESOURCE_SHORTAGE);
5106 }
5107 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5108 pde = &pde[pmap_pde_index(va)];
5109 oldpde = *pde;
5110 if ((oldpde & PG_V) != 0) {
5111 KASSERT(pdpg->wire_count > 1,
5112 ("pmap_enter_pde: pdpg's wire count is too low"));
5113 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
5114 pdpg->wire_count--;
5115 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5116 " in pmap %p", va, pmap);
5117 return (KERN_FAILURE);
5118 }
5119 /* Break the existing mapping(s). */
5120 SLIST_INIT(&free);
5121 if ((oldpde & PG_PS) != 0) {
5122 /*
5123 * The reference to the PD page that was acquired by
5124 * pmap_allocpde() ensures that it won't be freed.
5125 * However, if the PDE resulted from a promotion, then
5126 * a reserved PT page could be freed.
5127 */
5128 (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
5129 if ((oldpde & PG_G) == 0)
5130 pmap_invalidate_pde_page(pmap, va, oldpde);
5131 } else {
5132 pmap_delayed_invl_started();
5133 if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
5134 lockp))
5135 pmap_invalidate_all(pmap);
5136 pmap_delayed_invl_finished();
5137 }
5138 pmap_free_zero_pages(&free);
5139 if (va >= VM_MAXUSER_ADDRESS) {
5140 mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
5141 if (pmap_insert_pt_page(pmap, mt)) {
5142 /*
5143 * XXX Currently, this can't happen because
5144 * we do not perform pmap_enter(psind == 1)
5145 * on the kernel pmap.
5146 */
5147 panic("pmap_enter_pde: trie insert failed");
5148 }
5149 } else
5150 KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
5151 pde));
5152 }
5153 if ((newpde & PG_MANAGED) != 0) {
5154 /*
5155 * Abort this mapping if its PV entry could not be created.
5156 */
5157 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
5158 SLIST_INIT(&free);
5159 if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
5160 /*
5161 * Although "va" is not mapped, paging-
5162 * structure caches could nonetheless have
5163 * entries that refer to the freed page table
5164 * pages. Invalidate those entries.
5165 */
5166 pmap_invalidate_page(pmap, va);
5167 pmap_free_zero_pages(&free);
5168 }
5169 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5170 " in pmap %p", va, pmap);
5171 return (KERN_RESOURCE_SHORTAGE);
5172 }
5173 if ((newpde & PG_RW) != 0) {
5174 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5175 vm_page_aflag_set(mt, PGA_WRITEABLE);
5176 }
5177 }
5178
5179 /*
5180 * Increment counters.
5181 */
5182 if ((newpde & PG_W) != 0)
5183 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
5184 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5185
5186 /*
5187 * Map the superpage. (This is not a promoted mapping; there will not
5188 * be any lingering 4KB page mappings in the TLB.)
5189 */
5190 pde_store(pde, newpde);
5191
5192 atomic_add_long(&pmap_pde_mappings, 1);
5193 CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
5194 " in pmap %p", va, pmap);
5195 return (KERN_SUCCESS);
5196 }
5197
5198 /*
5199 * Maps a sequence of resident pages belonging to the same object.
5200 * The sequence begins with the given page m_start. This page is
5201 * mapped at the given virtual address start. Each subsequent page is
5202 * mapped at a virtual address that is offset from start by the same
5203 * amount as the page is offset from m_start within the object. The
5204 * last page in the sequence is the page with the largest offset from
5205 * m_start that can be mapped at a virtual address less than the given
5206 * virtual address end. Not every virtual page between start and end
5207 * is mapped; only those for which a resident page exists with the
5208 * corresponding offset from m_start are mapped.
5209 */
5210 void
5211 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
5212 vm_page_t m_start, vm_prot_t prot)
5213 {
5214 struct rwlock *lock;
5215 vm_offset_t va;
5216 vm_page_t m, mpte;
5217 vm_pindex_t diff, psize;
5218
5219 VM_OBJECT_ASSERT_LOCKED(m_start->object);
5220
5221 psize = atop(end - start);
5222 mpte = NULL;
5223 m = m_start;
5224 lock = NULL;
5225 PMAP_LOCK(pmap);
5226 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
5227 va = start + ptoa(diff);
5228 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
5229 m->psind == 1 && pmap_ps_enabled(pmap) &&
5230 pmap_allow_2m_x_page(pmap, (prot & VM_PROT_EXECUTE) != 0) &&
5231 pmap_enter_2mpage(pmap, va, m, prot, &lock))
5232 m = &m[NBPDR / PAGE_SIZE - 1];
5233 else
5234 mpte = pmap_enter_quick_locked(pmap, va, m, prot,
5235 mpte, &lock);
5236 m = TAILQ_NEXT(m, listq);
5237 }
5238 if (lock != NULL)
5239 rw_wunlock(lock);
5240 PMAP_UNLOCK(pmap);
5241 }
5242
5243 /*
5244 * this code makes some *MAJOR* assumptions:
5245 * 1. Current pmap & pmap exists.
5246 * 2. Not wired.
5247 * 3. Read access.
5248 * 4. No page table pages.
5249 * but is *MUCH* faster than pmap_enter...
5250 */
5251
5252 void
5253 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
5254 {
5255 struct rwlock *lock;
5256
5257 lock = NULL;
5258 PMAP_LOCK(pmap);
5259 (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
5260 if (lock != NULL)
5261 rw_wunlock(lock);
5262 PMAP_UNLOCK(pmap);
5263 }
5264
5265 static vm_page_t
5266 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
5267 vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
5268 {
5269 struct spglist free;
5270 pt_entry_t newpte, *pte, PG_V;
5271
5272 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
5273 (m->oflags & VPO_UNMANAGED) != 0,
5274 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
5275 PG_V = pmap_valid_bit(pmap);
5276 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5277
5278 /*
5279 * In the case that a page table page is not
5280 * resident, we are creating it here.
5281 */
5282 if (va < VM_MAXUSER_ADDRESS) {
5283 vm_pindex_t ptepindex;
5284 pd_entry_t *ptepa;
5285
5286 /*
5287 * Calculate pagetable page index
5288 */
5289 ptepindex = pmap_pde_pindex(va);
5290 if (mpte && (mpte->pindex == ptepindex)) {
5291 mpte->wire_count++;
5292 } else {
5293 /*
5294 * Get the page directory entry
5295 */
5296 ptepa = pmap_pde(pmap, va);
5297
5298 /*
5299 * If the page table page is mapped, we just increment
5300 * the hold count, and activate it. Otherwise, we
5301 * attempt to allocate a page table page. If this
5302 * attempt fails, we don't retry. Instead, we give up.
5303 */
5304 if (ptepa && (*ptepa & PG_V) != 0) {
5305 if (*ptepa & PG_PS)
5306 return (NULL);
5307 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
5308 mpte->wire_count++;
5309 } else {
5310 /*
5311 * Pass NULL instead of the PV list lock
5312 * pointer, because we don't intend to sleep.
5313 */
5314 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
5315 if (mpte == NULL)
5316 return (mpte);
5317 }
5318 }
5319 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
5320 pte = &pte[pmap_pte_index(va)];
5321 } else {
5322 mpte = NULL;
5323 pte = vtopte(va);
5324 }
5325 if (*pte) {
5326 if (mpte != NULL) {
5327 mpte->wire_count--;
5328 mpte = NULL;
5329 }
5330 return (mpte);
5331 }
5332
5333 /*
5334 * Enter on the PV list if part of our managed memory.
5335 */
5336 if ((m->oflags & VPO_UNMANAGED) == 0 &&
5337 !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
5338 if (mpte != NULL) {
5339 SLIST_INIT(&free);
5340 if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
5341 /*
5342 * Although "va" is not mapped, paging-
5343 * structure caches could nonetheless have
5344 * entries that refer to the freed page table
5345 * pages. Invalidate those entries.
5346 */
5347 pmap_invalidate_page(pmap, va);
5348 pmap_free_zero_pages(&free);
5349 }
5350 mpte = NULL;
5351 }
5352 return (mpte);
5353 }
5354
5355 /*
5356 * Increment counters
5357 */
5358 pmap_resident_count_inc(pmap, 1);
5359
5360 newpte = VM_PAGE_TO_PHYS(m) | PG_V |
5361 pmap_cache_bits(pmap, m->md.pat_mode, 0);
5362 if ((m->oflags & VPO_UNMANAGED) == 0)
5363 newpte |= PG_MANAGED;
5364 if ((prot & VM_PROT_EXECUTE) == 0)
5365 newpte |= pg_nx;
5366 if (va < VM_MAXUSER_ADDRESS)
5367 newpte |= PG_U;
5368 pte_store(pte, newpte);
5369 return (mpte);
5370 }
5371
5372 /*
5373 * Make a temporary mapping for a physical address. This is only intended
5374 * to be used for panic dumps.
5375 */
5376 void *
5377 pmap_kenter_temporary(vm_paddr_t pa, int i)
5378 {
5379 vm_offset_t va;
5380
5381 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
5382 pmap_kenter(va, pa);
5383 invlpg(va);
5384 return ((void *)crashdumpmap);
5385 }
5386
5387 /*
5388 * This code maps large physical mmap regions into the
5389 * processor address space. Note that some shortcuts
5390 * are taken, but the code works.
5391 */
5392 void
5393 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
5394 vm_pindex_t pindex, vm_size_t size)
5395 {
5396 pd_entry_t *pde;
5397 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5398 vm_paddr_t pa, ptepa;
5399 vm_page_t p, pdpg;
5400 int pat_mode;
5401
5402 PG_A = pmap_accessed_bit(pmap);
5403 PG_M = pmap_modified_bit(pmap);
5404 PG_V = pmap_valid_bit(pmap);
5405 PG_RW = pmap_rw_bit(pmap);
5406
5407 VM_OBJECT_ASSERT_WLOCKED(object);
5408 KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
5409 ("pmap_object_init_pt: non-device object"));
5410 if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
5411 if (!pmap_ps_enabled(pmap))
5412 return;
5413 if (!vm_object_populate(object, pindex, pindex + atop(size)))
5414 return;
5415 p = vm_page_lookup(object, pindex);
5416 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5417 ("pmap_object_init_pt: invalid page %p", p));
5418 pat_mode = p->md.pat_mode;
5419
5420 /*
5421 * Abort the mapping if the first page is not physically
5422 * aligned to a 2MB page boundary.
5423 */
5424 ptepa = VM_PAGE_TO_PHYS(p);
5425 if (ptepa & (NBPDR - 1))
5426 return;
5427
5428 /*
5429 * Skip the first page. Abort the mapping if the rest of
5430 * the pages are not physically contiguous or have differing
5431 * memory attributes.
5432 */
5433 p = TAILQ_NEXT(p, listq);
5434 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
5435 pa += PAGE_SIZE) {
5436 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5437 ("pmap_object_init_pt: invalid page %p", p));
5438 if (pa != VM_PAGE_TO_PHYS(p) ||
5439 pat_mode != p->md.pat_mode)
5440 return;
5441 p = TAILQ_NEXT(p, listq);
5442 }
5443
5444 /*
5445 * Map using 2MB pages. Since "ptepa" is 2M aligned and
5446 * "size" is a multiple of 2M, adding the PAT setting to "pa"
5447 * will not affect the termination of this loop.
5448 */
5449 PMAP_LOCK(pmap);
5450 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
5451 pa < ptepa + size; pa += NBPDR) {
5452 pdpg = pmap_allocpde(pmap, addr, NULL);
5453 if (pdpg == NULL) {
5454 /*
5455 * The creation of mappings below is only an
5456 * optimization. If a page directory page
5457 * cannot be allocated without blocking,
5458 * continue on to the next mapping rather than
5459 * blocking.
5460 */
5461 addr += NBPDR;
5462 continue;
5463 }
5464 pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5465 pde = &pde[pmap_pde_index(addr)];
5466 if ((*pde & PG_V) == 0) {
5467 pde_store(pde, pa | PG_PS | PG_M | PG_A |
5468 PG_U | PG_RW | PG_V);
5469 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5470 atomic_add_long(&pmap_pde_mappings, 1);
5471 } else {
5472 /* Continue on if the PDE is already valid. */
5473 pdpg->wire_count--;
5474 KASSERT(pdpg->wire_count > 0,
5475 ("pmap_object_init_pt: missing reference "
5476 "to page directory page, va: 0x%lx", addr));
5477 }
5478 addr += NBPDR;
5479 }
5480 PMAP_UNLOCK(pmap);
5481 }
5482 }
5483
5484 /*
5485 * Clear the wired attribute from the mappings for the specified range of
5486 * addresses in the given pmap. Every valid mapping within that range
5487 * must have the wired attribute set. In contrast, invalid mappings
5488 * cannot have the wired attribute set, so they are ignored.
5489 *
5490 * The wired attribute of the page table entry is not a hardware
5491 * feature, so there is no need to invalidate any TLB entries.
5492 * Since pmap_demote_pde() for the wired entry must never fail,
5493 * pmap_delayed_invl_started()/finished() calls around the
5494 * function are not needed.
5495 */
5496 void
5497 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5498 {
5499 vm_offset_t va_next;
5500 pml4_entry_t *pml4e;
5501 pdp_entry_t *pdpe;
5502 pd_entry_t *pde;
5503 pt_entry_t *pte, PG_V;
5504
5505 PG_V = pmap_valid_bit(pmap);
5506 PMAP_LOCK(pmap);
5507 for (; sva < eva; sva = va_next) {
5508 pml4e = pmap_pml4e(pmap, sva);
5509 if ((*pml4e & PG_V) == 0) {
5510 va_next = (sva + NBPML4) & ~PML4MASK;
5511 if (va_next < sva)
5512 va_next = eva;
5513 continue;
5514 }
5515 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5516 if ((*pdpe & PG_V) == 0) {
5517 va_next = (sva + NBPDP) & ~PDPMASK;
5518 if (va_next < sva)
5519 va_next = eva;
5520 continue;
5521 }
5522 va_next = (sva + NBPDR) & ~PDRMASK;
5523 if (va_next < sva)
5524 va_next = eva;
5525 pde = pmap_pdpe_to_pde(pdpe, sva);
5526 if ((*pde & PG_V) == 0)
5527 continue;
5528 if ((*pde & PG_PS) != 0) {
5529 if ((*pde & PG_W) == 0)
5530 panic("pmap_unwire: pde %#jx is missing PG_W",
5531 (uintmax_t)*pde);
5532
5533 /*
5534 * Are we unwiring the entire large page? If not,
5535 * demote the mapping and fall through.
5536 */
5537 if (sva + NBPDR == va_next && eva >= va_next) {
5538 atomic_clear_long(pde, PG_W);
5539 pmap->pm_stats.wired_count -= NBPDR /
5540 PAGE_SIZE;
5541 continue;
5542 } else if (!pmap_demote_pde(pmap, pde, sva))
5543 panic("pmap_unwire: demotion failed");
5544 }
5545 if (va_next > eva)
5546 va_next = eva;
5547 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
5548 sva += PAGE_SIZE) {
5549 if ((*pte & PG_V) == 0)
5550 continue;
5551 if ((*pte & PG_W) == 0)
5552 panic("pmap_unwire: pte %#jx is missing PG_W",
5553 (uintmax_t)*pte);
5554
5555 /*
5556 * PG_W must be cleared atomically. Although the pmap
5557 * lock synchronizes access to PG_W, another processor
5558 * could be setting PG_M and/or PG_A concurrently.
5559 */
5560 atomic_clear_long(pte, PG_W);
5561 pmap->pm_stats.wired_count--;
5562 }
5563 }
5564 PMAP_UNLOCK(pmap);
5565 }
5566
5567 /*
5568 * Copy the range specified by src_addr/len
5569 * from the source map to the range dst_addr/len
5570 * in the destination map.
5571 *
5572 * This routine is only advisory and need not do anything.
5573 */
5574
5575 void
5576 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5577 vm_offset_t src_addr)
5578 {
5579 struct rwlock *lock;
5580 struct spglist free;
5581 vm_offset_t addr;
5582 vm_offset_t end_addr = src_addr + len;
5583 vm_offset_t va_next;
5584 vm_page_t dst_pdpg, dstmpte, srcmpte;
5585 pt_entry_t PG_A, PG_M, PG_V;
5586
5587 if (dst_addr != src_addr)
5588 return;
5589
5590 if (dst_pmap->pm_type != src_pmap->pm_type)
5591 return;
5592
5593 /*
5594 * EPT page table entries that require emulation of A/D bits are
5595 * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5596 * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5597 * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5598 * implementations flag an EPT misconfiguration for exec-only
5599 * mappings we skip this function entirely for emulated pmaps.
5600 */
5601 if (pmap_emulate_ad_bits(dst_pmap))
5602 return;
5603
5604 lock = NULL;
5605 if (dst_pmap < src_pmap) {
5606 PMAP_LOCK(dst_pmap);
5607 PMAP_LOCK(src_pmap);
5608 } else {
5609 PMAP_LOCK(src_pmap);
5610 PMAP_LOCK(dst_pmap);
5611 }
5612
5613 PG_A = pmap_accessed_bit(dst_pmap);
5614 PG_M = pmap_modified_bit(dst_pmap);
5615 PG_V = pmap_valid_bit(dst_pmap);
5616
5617 for (addr = src_addr; addr < end_addr; addr = va_next) {
5618 pt_entry_t *src_pte, *dst_pte;
5619 pml4_entry_t *pml4e;
5620 pdp_entry_t *pdpe;
5621 pd_entry_t srcptepaddr, *pde;
5622
5623 KASSERT(addr < UPT_MIN_ADDRESS,
5624 ("pmap_copy: invalid to pmap_copy page tables"));
5625
5626 pml4e = pmap_pml4e(src_pmap, addr);
5627 if ((*pml4e & PG_V) == 0) {
5628 va_next = (addr + NBPML4) & ~PML4MASK;
5629 if (va_next < addr)
5630 va_next = end_addr;
5631 continue;
5632 }
5633
5634 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5635 if ((*pdpe & PG_V) == 0) {
5636 va_next = (addr + NBPDP) & ~PDPMASK;
5637 if (va_next < addr)
5638 va_next = end_addr;
5639 continue;
5640 }
5641
5642 va_next = (addr + NBPDR) & ~PDRMASK;
5643 if (va_next < addr)
5644 va_next = end_addr;
5645
5646 pde = pmap_pdpe_to_pde(pdpe, addr);
5647 srcptepaddr = *pde;
5648 if (srcptepaddr == 0)
5649 continue;
5650
5651 if (srcptepaddr & PG_PS) {
5652 if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5653 continue;
5654 dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
5655 if (dst_pdpg == NULL)
5656 break;
5657 pde = (pd_entry_t *)
5658 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
5659 pde = &pde[pmap_pde_index(addr)];
5660 if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5661 pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
5662 PMAP_ENTER_NORECLAIM, &lock))) {
5663 *pde = srcptepaddr & ~PG_W;
5664 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5665 atomic_add_long(&pmap_pde_mappings, 1);
5666 } else
5667 dst_pdpg->wire_count--;
5668 continue;
5669 }
5670
5671 srcptepaddr &= PG_FRAME;
5672 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5673 KASSERT(srcmpte->wire_count > 0,
5674 ("pmap_copy: source page table page is unused"));
5675
5676 if (va_next > end_addr)
5677 va_next = end_addr;
5678
5679 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5680 src_pte = &src_pte[pmap_pte_index(addr)];
5681 dstmpte = NULL;
5682 while (addr < va_next) {
5683 pt_entry_t ptetemp;
5684 ptetemp = *src_pte;
5685 /*
5686 * we only virtual copy managed pages
5687 */
5688 if ((ptetemp & PG_MANAGED) != 0) {
5689 if (dstmpte != NULL &&
5690 dstmpte->pindex == pmap_pde_pindex(addr))
5691 dstmpte->wire_count++;
5692 else if ((dstmpte = pmap_allocpte(dst_pmap,
5693 addr, NULL)) == NULL)
5694 goto out;
5695 dst_pte = (pt_entry_t *)
5696 PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5697 dst_pte = &dst_pte[pmap_pte_index(addr)];
5698 if (*dst_pte == 0 &&
5699 pmap_try_insert_pv_entry(dst_pmap, addr,
5700 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5701 &lock)) {
5702 /*
5703 * Clear the wired, modified, and
5704 * accessed (referenced) bits
5705 * during the copy.
5706 */
5707 *dst_pte = ptetemp & ~(PG_W | PG_M |
5708 PG_A);
5709 pmap_resident_count_inc(dst_pmap, 1);
5710 } else {
5711 SLIST_INIT(&free);
5712 if (pmap_unwire_ptp(dst_pmap, addr,
5713 dstmpte, &free)) {
5714 /*
5715 * Although "addr" is not
5716 * mapped, paging-structure
5717 * caches could nonetheless
5718 * have entries that refer to
5719 * the freed page table pages.
5720 * Invalidate those entries.
5721 */
5722 pmap_invalidate_page(dst_pmap,
5723 addr);
5724 pmap_free_zero_pages(&free);
5725 }
5726 goto out;
5727 }
5728 if (dstmpte->wire_count >= srcmpte->wire_count)
5729 break;
5730 }
5731 addr += PAGE_SIZE;
5732 src_pte++;
5733 }
5734 }
5735 out:
5736 if (lock != NULL)
5737 rw_wunlock(lock);
5738 PMAP_UNLOCK(src_pmap);
5739 PMAP_UNLOCK(dst_pmap);
5740 }
5741
5742 /*
5743 * pmap_zero_page zeros the specified hardware page by mapping
5744 * the page into KVM and using bzero to clear its contents.
5745 */
5746 void
5747 pmap_zero_page(vm_page_t m)
5748 {
5749 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5750
5751 pagezero((void *)va);
5752 }
5753
5754 /*
5755 * pmap_zero_page_area zeros the specified hardware page by mapping
5756 * the page into KVM and using bzero to clear its contents.
5757 *
5758 * off and size may not cover an area beyond a single hardware page.
5759 */
5760 void
5761 pmap_zero_page_area(vm_page_t m, int off, int size)
5762 {
5763 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5764
5765 if (off == 0 && size == PAGE_SIZE)
5766 pagezero((void *)va);
5767 else
5768 bzero((char *)va + off, size);
5769 }
5770
5771 /*
5772 * pmap_zero_page_idle zeros the specified hardware page by mapping
5773 * the page into KVM and using bzero to clear its contents. This
5774 * is intended to be called from the vm_pagezero process only and
5775 * outside of Giant.
5776 */
5777 void
5778 pmap_zero_page_idle(vm_page_t m)
5779 {
5780 vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5781
5782 pagezero((void *)va);
5783 }
5784
5785 /*
5786 * pmap_copy_page copies the specified (machine independent)
5787 * page by mapping the page into virtual memory and using
5788 * bcopy to copy the page, one machine dependent page at a
5789 * time.
5790 */
5791 void
5792 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5793 {
5794 vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5795 vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5796
5797 pagecopy((void *)src, (void *)dst);
5798 }
5799
5800 int unmapped_buf_allowed = 1;
5801
5802 void
5803 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5804 vm_offset_t b_offset, int xfersize)
5805 {
5806 void *a_cp, *b_cp;
5807 vm_page_t pages[2];
5808 vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5809 int cnt;
5810 boolean_t mapped;
5811
5812 while (xfersize > 0) {
5813 a_pg_offset = a_offset & PAGE_MASK;
5814 pages[0] = ma[a_offset >> PAGE_SHIFT];
5815 b_pg_offset = b_offset & PAGE_MASK;
5816 pages[1] = mb[b_offset >> PAGE_SHIFT];
5817 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5818 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5819 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5820 a_cp = (char *)vaddr[0] + a_pg_offset;
5821 b_cp = (char *)vaddr[1] + b_pg_offset;
5822 bcopy(a_cp, b_cp, cnt);
5823 if (__predict_false(mapped))
5824 pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5825 a_offset += cnt;
5826 b_offset += cnt;
5827 xfersize -= cnt;
5828 }
5829 }
5830
5831 /*
5832 * Returns true if the pmap's pv is one of the first
5833 * 16 pvs linked to from this page. This count may
5834 * be changed upwards or downwards in the future; it
5835 * is only necessary that true be returned for a small
5836 * subset of pmaps for proper page aging.
5837 */
5838 boolean_t
5839 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5840 {
5841 struct md_page *pvh;
5842 struct rwlock *lock;
5843 pv_entry_t pv;
5844 int loops = 0;
5845 boolean_t rv;
5846
5847 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5848 ("pmap_page_exists_quick: page %p is not managed", m));
5849 rv = FALSE;
5850 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5851 rw_rlock(lock);
5852 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5853 if (PV_PMAP(pv) == pmap) {
5854 rv = TRUE;
5855 break;
5856 }
5857 loops++;
5858 if (loops >= 16)
5859 break;
5860 }
5861 if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5862 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5863 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5864 if (PV_PMAP(pv) == pmap) {
5865 rv = TRUE;
5866 break;
5867 }
5868 loops++;
5869 if (loops >= 16)
5870 break;
5871 }
5872 }
5873 rw_runlock(lock);
5874 return (rv);
5875 }
5876
5877 /*
5878 * pmap_page_wired_mappings:
5879 *
5880 * Return the number of managed mappings to the given physical page
5881 * that are wired.
5882 */
5883 int
5884 pmap_page_wired_mappings(vm_page_t m)
5885 {
5886 struct rwlock *lock;
5887 struct md_page *pvh;
5888 pmap_t pmap;
5889 pt_entry_t *pte;
5890 pv_entry_t pv;
5891 int count, md_gen, pvh_gen;
5892
5893 if ((m->oflags & VPO_UNMANAGED) != 0)
5894 return (0);
5895 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5896 rw_rlock(lock);
5897 restart:
5898 count = 0;
5899 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5900 pmap = PV_PMAP(pv);
5901 if (!PMAP_TRYLOCK(pmap)) {
5902 md_gen = m->md.pv_gen;
5903 rw_runlock(lock);
5904 PMAP_LOCK(pmap);
5905 rw_rlock(lock);
5906 if (md_gen != m->md.pv_gen) {
5907 PMAP_UNLOCK(pmap);
5908 goto restart;
5909 }
5910 }
5911 pte = pmap_pte(pmap, pv->pv_va);
5912 if ((*pte & PG_W) != 0)
5913 count++;
5914 PMAP_UNLOCK(pmap);
5915 }
5916 if ((m->flags & PG_FICTITIOUS) == 0) {
5917 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5918 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5919 pmap = PV_PMAP(pv);
5920 if (!PMAP_TRYLOCK(pmap)) {
5921 md_gen = m->md.pv_gen;
5922 pvh_gen = pvh->pv_gen;
5923 rw_runlock(lock);
5924 PMAP_LOCK(pmap);
5925 rw_rlock(lock);
5926 if (md_gen != m->md.pv_gen ||
5927 pvh_gen != pvh->pv_gen) {
5928 PMAP_UNLOCK(pmap);
5929 goto restart;
5930 }
5931 }
5932 pte = pmap_pde(pmap, pv->pv_va);
5933 if ((*pte & PG_W) != 0)
5934 count++;
5935 PMAP_UNLOCK(pmap);
5936 }
5937 }
5938 rw_runlock(lock);
5939 return (count);
5940 }
5941
5942 /*
5943 * Returns TRUE if the given page is mapped individually or as part of
5944 * a 2mpage. Otherwise, returns FALSE.
5945 */
5946 boolean_t
5947 pmap_page_is_mapped(vm_page_t m)
5948 {
5949 struct rwlock *lock;
5950 boolean_t rv;
5951
5952 if ((m->oflags & VPO_UNMANAGED) != 0)
5953 return (FALSE);
5954 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5955 rw_rlock(lock);
5956 rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5957 ((m->flags & PG_FICTITIOUS) == 0 &&
5958 !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5959 rw_runlock(lock);
5960 return (rv);
5961 }
5962
5963 /*
5964 * Destroy all managed, non-wired mappings in the given user-space
5965 * pmap. This pmap cannot be active on any processor besides the
5966 * caller.
5967 *
5968 * This function cannot be applied to the kernel pmap. Moreover, it
5969 * is not intended for general use. It is only to be used during
5970 * process termination. Consequently, it can be implemented in ways
5971 * that make it faster than pmap_remove(). First, it can more quickly
5972 * destroy mappings by iterating over the pmap's collection of PV
5973 * entries, rather than searching the page table. Second, it doesn't
5974 * have to test and clear the page table entries atomically, because
5975 * no processor is currently accessing the user address space. In
5976 * particular, a page table entry's dirty bit won't change state once
5977 * this function starts.
5978 *
5979 * Although this function destroys all of the pmap's managed,
5980 * non-wired mappings, it can delay and batch the invalidation of TLB
5981 * entries without calling pmap_delayed_invl_started() and
5982 * pmap_delayed_invl_finished(). Because the pmap is not active on
5983 * any other processor, none of these TLB entries will ever be used
5984 * before their eventual invalidation. Consequently, there is no need
5985 * for either pmap_remove_all() or pmap_remove_write() to wait for
5986 * that eventual TLB invalidation.
5987 */
5988 void
5989 pmap_remove_pages(pmap_t pmap)
5990 {
5991 pd_entry_t ptepde;
5992 pt_entry_t *pte, tpte;
5993 pt_entry_t PG_M, PG_RW, PG_V;
5994 struct spglist free;
5995 vm_page_t m, mpte, mt;
5996 pv_entry_t pv;
5997 struct md_page *pvh;
5998 struct pv_chunk *pc, *npc;
5999 struct rwlock *lock;
6000 int64_t bit;
6001 uint64_t inuse, bitmask;
6002 int allfree, field, freed, idx;
6003 boolean_t superpage;
6004 vm_paddr_t pa;
6005
6006 /*
6007 * Assert that the given pmap is only active on the current
6008 * CPU. Unfortunately, we cannot block another CPU from
6009 * activating the pmap while this function is executing.
6010 */
6011 KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
6012 #ifdef INVARIANTS
6013 {
6014 cpuset_t other_cpus;
6015
6016 other_cpus = all_cpus;
6017 critical_enter();
6018 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
6019 CPU_AND(&other_cpus, &pmap->pm_active);
6020 critical_exit();
6021 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
6022 }
6023 #endif
6024
6025 lock = NULL;
6026 PG_M = pmap_modified_bit(pmap);
6027 PG_V = pmap_valid_bit(pmap);
6028 PG_RW = pmap_rw_bit(pmap);
6029
6030 SLIST_INIT(&free);
6031 PMAP_LOCK(pmap);
6032 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
6033 allfree = 1;
6034 freed = 0;
6035 for (field = 0; field < _NPCM; field++) {
6036 inuse = ~pc->pc_map[field] & pc_freemask[field];
6037 while (inuse != 0) {
6038 bit = bsfq(inuse);
6039 bitmask = 1UL << bit;
6040 idx = field * 64 + bit;
6041 pv = &pc->pc_pventry[idx];
6042 inuse &= ~bitmask;
6043
6044 pte = pmap_pdpe(pmap, pv->pv_va);
6045 ptepde = *pte;
6046 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
6047 tpte = *pte;
6048 if ((tpte & (PG_PS | PG_V)) == PG_V) {
6049 superpage = FALSE;
6050 ptepde = tpte;
6051 pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
6052 PG_FRAME);
6053 pte = &pte[pmap_pte_index(pv->pv_va)];
6054 tpte = *pte;
6055 } else {
6056 /*
6057 * Keep track whether 'tpte' is a
6058 * superpage explicitly instead of
6059 * relying on PG_PS being set.
6060 *
6061 * This is because PG_PS is numerically
6062 * identical to PG_PTE_PAT and thus a
6063 * regular page could be mistaken for
6064 * a superpage.
6065 */
6066 superpage = TRUE;
6067 }
6068
6069 if ((tpte & PG_V) == 0) {
6070 panic("bad pte va %lx pte %lx",
6071 pv->pv_va, tpte);
6072 }
6073
6074 /*
6075 * We cannot remove wired pages from a process' mapping at this time
6076 */
6077 if (tpte & PG_W) {
6078 allfree = 0;
6079 continue;
6080 }
6081
6082 if (superpage)
6083 pa = tpte & PG_PS_FRAME;
6084 else
6085 pa = tpte & PG_FRAME;
6086
6087 m = PHYS_TO_VM_PAGE(pa);
6088 KASSERT(m->phys_addr == pa,
6089 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
6090 m, (uintmax_t)m->phys_addr,
6091 (uintmax_t)tpte));
6092
6093 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
6094 m < &vm_page_array[vm_page_array_size],
6095 ("pmap_remove_pages: bad tpte %#jx",
6096 (uintmax_t)tpte));
6097
6098 pte_clear(pte);
6099
6100 /*
6101 * Update the vm_page_t clean/reference bits.
6102 */
6103 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6104 if (superpage) {
6105 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6106 vm_page_dirty(mt);
6107 } else
6108 vm_page_dirty(m);
6109 }
6110
6111 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
6112
6113 /* Mark free */
6114 pc->pc_map[field] |= bitmask;
6115 if (superpage) {
6116 pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
6117 pvh = pa_to_pvh(tpte & PG_PS_FRAME);
6118 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6119 pvh->pv_gen++;
6120 if (TAILQ_EMPTY(&pvh->pv_list)) {
6121 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6122 if ((mt->aflags & PGA_WRITEABLE) != 0 &&
6123 TAILQ_EMPTY(&mt->md.pv_list))
6124 vm_page_aflag_clear(mt, PGA_WRITEABLE);
6125 }
6126 mpte = pmap_remove_pt_page(pmap, pv->pv_va);
6127 if (mpte != NULL) {
6128 pmap_resident_count_dec(pmap, 1);
6129 KASSERT(mpte->wire_count == NPTEPG,
6130 ("pmap_remove_pages: pte page wire count error"));
6131 mpte->wire_count = 0;
6132 pmap_add_delayed_free_list(mpte, &free, FALSE);
6133 }
6134 } else {
6135 pmap_resident_count_dec(pmap, 1);
6136 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6137 m->md.pv_gen++;
6138 if ((m->aflags & PGA_WRITEABLE) != 0 &&
6139 TAILQ_EMPTY(&m->md.pv_list) &&
6140 (m->flags & PG_FICTITIOUS) == 0) {
6141 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6142 if (TAILQ_EMPTY(&pvh->pv_list))
6143 vm_page_aflag_clear(m, PGA_WRITEABLE);
6144 }
6145 }
6146 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
6147 freed++;
6148 }
6149 }
6150 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
6151 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
6152 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
6153 if (allfree) {
6154 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
6155 free_pv_chunk(pc);
6156 }
6157 }
6158 if (lock != NULL)
6159 rw_wunlock(lock);
6160 pmap_invalidate_all(pmap);
6161 PMAP_UNLOCK(pmap);
6162 pmap_free_zero_pages(&free);
6163 }
6164
6165 static boolean_t
6166 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
6167 {
6168 struct rwlock *lock;
6169 pv_entry_t pv;
6170 struct md_page *pvh;
6171 pt_entry_t *pte, mask;
6172 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6173 pmap_t pmap;
6174 int md_gen, pvh_gen;
6175 boolean_t rv;
6176
6177 rv = FALSE;
6178 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6179 rw_rlock(lock);
6180 restart:
6181 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6182 pmap = PV_PMAP(pv);
6183 if (!PMAP_TRYLOCK(pmap)) {
6184 md_gen = m->md.pv_gen;
6185 rw_runlock(lock);
6186 PMAP_LOCK(pmap);
6187 rw_rlock(lock);
6188 if (md_gen != m->md.pv_gen) {
6189 PMAP_UNLOCK(pmap);
6190 goto restart;
6191 }
6192 }
6193 pte = pmap_pte(pmap, pv->pv_va);
6194 mask = 0;
6195 if (modified) {
6196 PG_M = pmap_modified_bit(pmap);
6197 PG_RW = pmap_rw_bit(pmap);
6198 mask |= PG_RW | PG_M;
6199 }
6200 if (accessed) {
6201 PG_A = pmap_accessed_bit(pmap);
6202 PG_V = pmap_valid_bit(pmap);
6203 mask |= PG_V | PG_A;
6204 }
6205 rv = (*pte & mask) == mask;
6206 PMAP_UNLOCK(pmap);
6207 if (rv)
6208 goto out;
6209 }
6210 if ((m->flags & PG_FICTITIOUS) == 0) {
6211 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6212 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
6213 pmap = PV_PMAP(pv);
6214 if (!PMAP_TRYLOCK(pmap)) {
6215 md_gen = m->md.pv_gen;
6216 pvh_gen = pvh->pv_gen;
6217 rw_runlock(lock);
6218 PMAP_LOCK(pmap);
6219 rw_rlock(lock);
6220 if (md_gen != m->md.pv_gen ||
6221 pvh_gen != pvh->pv_gen) {
6222 PMAP_UNLOCK(pmap);
6223 goto restart;
6224 }
6225 }
6226 pte = pmap_pde(pmap, pv->pv_va);
6227 mask = 0;
6228 if (modified) {
6229 PG_M = pmap_modified_bit(pmap);
6230 PG_RW = pmap_rw_bit(pmap);
6231 mask |= PG_RW | PG_M;
6232 }
6233 if (accessed) {
6234 PG_A = pmap_accessed_bit(pmap);
6235 PG_V = pmap_valid_bit(pmap);
6236 mask |= PG_V | PG_A;
6237 }
6238 rv = (*pte & mask) == mask;
6239 PMAP_UNLOCK(pmap);
6240 if (rv)
6241 goto out;
6242 }
6243 }
6244 out:
6245 rw_runlock(lock);
6246 return (rv);
6247 }
6248
6249 /*
6250 * pmap_is_modified:
6251 *
6252 * Return whether or not the specified physical page was modified
6253 * in any physical maps.
6254 */
6255 boolean_t
6256 pmap_is_modified(vm_page_t m)
6257 {
6258
6259 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6260 ("pmap_is_modified: page %p is not managed", m));
6261
6262 /*
6263 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6264 * concurrently set while the object is locked. Thus, if PGA_WRITEABLE
6265 * is clear, no PTEs can have PG_M set.
6266 */
6267 VM_OBJECT_ASSERT_WLOCKED(m->object);
6268 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6269 return (FALSE);
6270 return (pmap_page_test_mappings(m, FALSE, TRUE));
6271 }
6272
6273 /*
6274 * pmap_is_prefaultable:
6275 *
6276 * Return whether or not the specified virtual address is eligible
6277 * for prefault.
6278 */
6279 boolean_t
6280 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
6281 {
6282 pd_entry_t *pde;
6283 pt_entry_t *pte, PG_V;
6284 boolean_t rv;
6285
6286 PG_V = pmap_valid_bit(pmap);
6287 rv = FALSE;
6288 PMAP_LOCK(pmap);
6289 pde = pmap_pde(pmap, addr);
6290 if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
6291 pte = pmap_pde_to_pte(pde, addr);
6292 rv = (*pte & PG_V) == 0;
6293 }
6294 PMAP_UNLOCK(pmap);
6295 return (rv);
6296 }
6297
6298 /*
6299 * pmap_is_referenced:
6300 *
6301 * Return whether or not the specified physical page was referenced
6302 * in any physical maps.
6303 */
6304 boolean_t
6305 pmap_is_referenced(vm_page_t m)
6306 {
6307
6308 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6309 ("pmap_is_referenced: page %p is not managed", m));
6310 return (pmap_page_test_mappings(m, TRUE, FALSE));
6311 }
6312
6313 /*
6314 * Clear the write and modified bits in each of the given page's mappings.
6315 */
6316 void
6317 pmap_remove_write(vm_page_t m)
6318 {
6319 struct md_page *pvh;
6320 pmap_t pmap;
6321 struct rwlock *lock;
6322 pv_entry_t next_pv, pv;
6323 pd_entry_t *pde;
6324 pt_entry_t oldpte, *pte, PG_M, PG_RW;
6325 vm_offset_t va;
6326 int pvh_gen, md_gen;
6327
6328 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6329 ("pmap_remove_write: page %p is not managed", m));
6330
6331 /*
6332 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6333 * set by another thread while the object is locked. Thus,
6334 * if PGA_WRITEABLE is clear, no page table entries need updating.
6335 */
6336 VM_OBJECT_ASSERT_WLOCKED(m->object);
6337 if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6338 return;
6339 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6340 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6341 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6342 retry_pv_loop:
6343 rw_wlock(lock);
6344 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6345 pmap = PV_PMAP(pv);
6346 if (!PMAP_TRYLOCK(pmap)) {
6347 pvh_gen = pvh->pv_gen;
6348 rw_wunlock(lock);
6349 PMAP_LOCK(pmap);
6350 rw_wlock(lock);
6351 if (pvh_gen != pvh->pv_gen) {
6352 PMAP_UNLOCK(pmap);
6353 rw_wunlock(lock);
6354 goto retry_pv_loop;
6355 }
6356 }
6357 PG_RW = pmap_rw_bit(pmap);
6358 va = pv->pv_va;
6359 pde = pmap_pde(pmap, va);
6360 if ((*pde & PG_RW) != 0)
6361 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6362 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6363 ("inconsistent pv lock %p %p for page %p",
6364 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6365 PMAP_UNLOCK(pmap);
6366 }
6367 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6368 pmap = PV_PMAP(pv);
6369 if (!PMAP_TRYLOCK(pmap)) {
6370 pvh_gen = pvh->pv_gen;
6371 md_gen = m->md.pv_gen;
6372 rw_wunlock(lock);
6373 PMAP_LOCK(pmap);
6374 rw_wlock(lock);
6375 if (pvh_gen != pvh->pv_gen ||
6376 md_gen != m->md.pv_gen) {
6377 PMAP_UNLOCK(pmap);
6378 rw_wunlock(lock);
6379 goto retry_pv_loop;
6380 }
6381 }
6382 PG_M = pmap_modified_bit(pmap);
6383 PG_RW = pmap_rw_bit(pmap);
6384 pde = pmap_pde(pmap, pv->pv_va);
6385 KASSERT((*pde & PG_PS) == 0,
6386 ("pmap_remove_write: found a 2mpage in page %p's pv list",
6387 m));
6388 pte = pmap_pde_to_pte(pde, pv->pv_va);
6389 retry:
6390 oldpte = *pte;
6391 if (oldpte & PG_RW) {
6392 if (!atomic_cmpset_long(pte, oldpte, oldpte &
6393 ~(PG_RW | PG_M)))
6394 goto retry;
6395 if ((oldpte & PG_M) != 0)
6396 vm_page_dirty(m);
6397 pmap_invalidate_page(pmap, pv->pv_va);
6398 }
6399 PMAP_UNLOCK(pmap);
6400 }
6401 rw_wunlock(lock);
6402 vm_page_aflag_clear(m, PGA_WRITEABLE);
6403 pmap_delayed_invl_wait(m);
6404 }
6405
6406 static __inline boolean_t
6407 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
6408 {
6409
6410 if (!pmap_emulate_ad_bits(pmap))
6411 return (TRUE);
6412
6413 KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
6414
6415 /*
6416 * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
6417 * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
6418 * if the EPT_PG_WRITE bit is set.
6419 */
6420 if ((pte & EPT_PG_WRITE) != 0)
6421 return (FALSE);
6422
6423 /*
6424 * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
6425 */
6426 if ((pte & EPT_PG_EXECUTE) == 0 ||
6427 ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
6428 return (TRUE);
6429 else
6430 return (FALSE);
6431 }
6432
6433 /*
6434 * pmap_ts_referenced:
6435 *
6436 * Return a count of reference bits for a page, clearing those bits.
6437 * It is not necessary for every reference bit to be cleared, but it
6438 * is necessary that 0 only be returned when there are truly no
6439 * reference bits set.
6440 *
6441 * As an optimization, update the page's dirty field if a modified bit is
6442 * found while counting reference bits. This opportunistic update can be
6443 * performed at low cost and can eliminate the need for some future calls
6444 * to pmap_is_modified(). However, since this function stops after
6445 * finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
6446 * dirty pages. Those dirty pages will only be detected by a future call
6447 * to pmap_is_modified().
6448 *
6449 * A DI block is not needed within this function, because
6450 * invalidations are performed before the PV list lock is
6451 * released.
6452 */
6453 int
6454 pmap_ts_referenced(vm_page_t m)
6455 {
6456 struct md_page *pvh;
6457 pv_entry_t pv, pvf;
6458 pmap_t pmap;
6459 struct rwlock *lock;
6460 pd_entry_t oldpde, *pde;
6461 pt_entry_t *pte, PG_A, PG_M, PG_RW;
6462 vm_offset_t va;
6463 vm_paddr_t pa;
6464 int cleared, md_gen, not_cleared, pvh_gen;
6465 struct spglist free;
6466 boolean_t demoted;
6467
6468 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6469 ("pmap_ts_referenced: page %p is not managed", m));
6470 SLIST_INIT(&free);
6471 cleared = 0;
6472 pa = VM_PAGE_TO_PHYS(m);
6473 lock = PHYS_TO_PV_LIST_LOCK(pa);
6474 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
6475 rw_wlock(lock);
6476 retry:
6477 not_cleared = 0;
6478 if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6479 goto small_mappings;
6480 pv = pvf;
6481 do {
6482 if (pvf == NULL)
6483 pvf = pv;
6484 pmap = PV_PMAP(pv);
6485 if (!PMAP_TRYLOCK(pmap)) {
6486 pvh_gen = pvh->pv_gen;
6487 rw_wunlock(lock);
6488 PMAP_LOCK(pmap);
6489 rw_wlock(lock);
6490 if (pvh_gen != pvh->pv_gen) {
6491 PMAP_UNLOCK(pmap);
6492 goto retry;
6493 }
6494 }
6495 PG_A = pmap_accessed_bit(pmap);
6496 PG_M = pmap_modified_bit(pmap);
6497 PG_RW = pmap_rw_bit(pmap);
6498 va = pv->pv_va;
6499 pde = pmap_pde(pmap, pv->pv_va);
6500 oldpde = *pde;
6501 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6502 /*
6503 * Although "oldpde" is mapping a 2MB page, because
6504 * this function is called at a 4KB page granularity,
6505 * we only update the 4KB page under test.
6506 */
6507 vm_page_dirty(m);
6508 }
6509 if ((oldpde & PG_A) != 0) {
6510 /*
6511 * Since this reference bit is shared by 512 4KB
6512 * pages, it should not be cleared every time it is
6513 * tested. Apply a simple "hash" function on the
6514 * physical page number, the virtual superpage number,
6515 * and the pmap address to select one 4KB page out of
6516 * the 512 on which testing the reference bit will
6517 * result in clearing that reference bit. This
6518 * function is designed to avoid the selection of the
6519 * same 4KB page for every 2MB page mapping.
6520 *
6521 * On demotion, a mapping that hasn't been referenced
6522 * is simply destroyed. To avoid the possibility of a
6523 * subsequent page fault on a demoted wired mapping,
6524 * always leave its reference bit set. Moreover,
6525 * since the superpage is wired, the current state of
6526 * its reference bit won't affect page replacement.
6527 */
6528 if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
6529 (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
6530 (oldpde & PG_W) == 0) {
6531 if (safe_to_clear_referenced(pmap, oldpde)) {
6532 atomic_clear_long(pde, PG_A);
6533 pmap_invalidate_page(pmap, pv->pv_va);
6534 demoted = FALSE;
6535 } else if (pmap_demote_pde_locked(pmap, pde,
6536 pv->pv_va, &lock)) {
6537 /*
6538 * Remove the mapping to a single page
6539 * so that a subsequent access may
6540 * repromote. Since the underlying
6541 * page table page is fully populated,
6542 * this removal never frees a page
6543 * table page.
6544 */
6545 demoted = TRUE;
6546 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6547 PG_PS_FRAME);
6548 pte = pmap_pde_to_pte(pde, va);
6549 pmap_remove_pte(pmap, pte, va, *pde,
6550 NULL, &lock);
6551 pmap_invalidate_page(pmap, va);
6552 } else
6553 demoted = TRUE;
6554
6555 if (demoted) {
6556 /*
6557 * The superpage mapping was removed
6558 * entirely and therefore 'pv' is no
6559 * longer valid.
6560 */
6561 if (pvf == pv)
6562 pvf = NULL;
6563 pv = NULL;
6564 }
6565 cleared++;
6566 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6567 ("inconsistent pv lock %p %p for page %p",
6568 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6569 } else
6570 not_cleared++;
6571 }
6572 PMAP_UNLOCK(pmap);
6573 /* Rotate the PV list if it has more than one entry. */
6574 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6575 TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6576 TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6577 pvh->pv_gen++;
6578 }
6579 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6580 goto out;
6581 } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6582 small_mappings:
6583 if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6584 goto out;
6585 pv = pvf;
6586 do {
6587 if (pvf == NULL)
6588 pvf = pv;
6589 pmap = PV_PMAP(pv);
6590 if (!PMAP_TRYLOCK(pmap)) {
6591 pvh_gen = pvh->pv_gen;
6592 md_gen = m->md.pv_gen;
6593 rw_wunlock(lock);
6594 PMAP_LOCK(pmap);
6595 rw_wlock(lock);
6596 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6597 PMAP_UNLOCK(pmap);
6598 goto retry;
6599 }
6600 }
6601 PG_A = pmap_accessed_bit(pmap);
6602 PG_M = pmap_modified_bit(pmap);
6603 PG_RW = pmap_rw_bit(pmap);
6604 pde = pmap_pde(pmap, pv->pv_va);
6605 KASSERT((*pde & PG_PS) == 0,
6606 ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6607 m));
6608 pte = pmap_pde_to_pte(pde, pv->pv_va);
6609 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6610 vm_page_dirty(m);
6611 if ((*pte & PG_A) != 0) {
6612 if (safe_to_clear_referenced(pmap, *pte)) {
6613 atomic_clear_long(pte, PG_A);
6614 pmap_invalidate_page(pmap, pv->pv_va);
6615 cleared++;
6616 } else if ((*pte & PG_W) == 0) {
6617 /*
6618 * Wired pages cannot be paged out so
6619 * doing accessed bit emulation for
6620 * them is wasted effort. We do the
6621 * hard work for unwired pages only.
6622 */
6623 pmap_remove_pte(pmap, pte, pv->pv_va,
6624 *pde, &free, &lock);
6625 pmap_invalidate_page(pmap, pv->pv_va);
6626 cleared++;
6627 if (pvf == pv)
6628 pvf = NULL;
6629 pv = NULL;
6630 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6631 ("inconsistent pv lock %p %p for page %p",
6632 lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6633 } else
6634 not_cleared++;
6635 }
6636 PMAP_UNLOCK(pmap);
6637 /* Rotate the PV list if it has more than one entry. */
6638 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6639 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6640 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6641 m->md.pv_gen++;
6642 }
6643 } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6644 not_cleared < PMAP_TS_REFERENCED_MAX);
6645 out:
6646 rw_wunlock(lock);
6647 pmap_free_zero_pages(&free);
6648 return (cleared + not_cleared);
6649 }
6650
6651 /*
6652 * Apply the given advice to the specified range of addresses within the
6653 * given pmap. Depending on the advice, clear the referenced and/or
6654 * modified flags in each mapping and set the mapped page's dirty field.
6655 */
6656 void
6657 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6658 {
6659 struct rwlock *lock;
6660 pml4_entry_t *pml4e;
6661 pdp_entry_t *pdpe;
6662 pd_entry_t oldpde, *pde;
6663 pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6664 vm_offset_t va, va_next;
6665 vm_page_t m;
6666 boolean_t anychanged;
6667
6668 if (advice != MADV_DONTNEED && advice != MADV_FREE)
6669 return;
6670
6671 /*
6672 * A/D bit emulation requires an alternate code path when clearing
6673 * the modified and accessed bits below. Since this function is
6674 * advisory in nature we skip it entirely for pmaps that require
6675 * A/D bit emulation.
6676 */
6677 if (pmap_emulate_ad_bits(pmap))
6678 return;
6679
6680 PG_A = pmap_accessed_bit(pmap);
6681 PG_G = pmap_global_bit(pmap);
6682 PG_M = pmap_modified_bit(pmap);
6683 PG_V = pmap_valid_bit(pmap);
6684 PG_RW = pmap_rw_bit(pmap);
6685 anychanged = FALSE;
6686 pmap_delayed_invl_started();
6687 PMAP_LOCK(pmap);
6688 for (; sva < eva; sva = va_next) {
6689 pml4e = pmap_pml4e(pmap, sva);
6690 if ((*pml4e & PG_V) == 0) {
6691 va_next = (sva + NBPML4) & ~PML4MASK;
6692 if (va_next < sva)
6693 va_next = eva;
6694 continue;
6695 }
6696 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6697 if ((*pdpe & PG_V) == 0) {
6698 va_next = (sva + NBPDP) & ~PDPMASK;
6699 if (va_next < sva)
6700 va_next = eva;
6701 continue;
6702 }
6703 va_next = (sva + NBPDR) & ~PDRMASK;
6704 if (va_next < sva)
6705 va_next = eva;
6706 pde = pmap_pdpe_to_pde(pdpe, sva);
6707 oldpde = *pde;
6708 if ((oldpde & PG_V) == 0)
6709 continue;
6710 else if ((oldpde & PG_PS) != 0) {
6711 if ((oldpde & PG_MANAGED) == 0)
6712 continue;
6713 lock = NULL;
6714 if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6715 if (lock != NULL)
6716 rw_wunlock(lock);
6717
6718 /*
6719 * The large page mapping was destroyed.
6720 */
6721 continue;
6722 }
6723
6724 /*
6725 * Unless the page mappings are wired, remove the
6726 * mapping to a single page so that a subsequent
6727 * access may repromote. Since the underlying page
6728 * table page is fully populated, this removal never
6729 * frees a page table page.
6730 */
6731 if ((oldpde & PG_W) == 0) {
6732 pte = pmap_pde_to_pte(pde, sva);
6733 KASSERT((*pte & PG_V) != 0,
6734 ("pmap_advise: invalid PTE"));
6735 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6736 &lock);
6737 anychanged = TRUE;
6738 }
6739 if (lock != NULL)
6740 rw_wunlock(lock);
6741 }
6742 if (va_next > eva)
6743 va_next = eva;
6744 va = va_next;
6745 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6746 sva += PAGE_SIZE) {
6747 if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6748 goto maybe_invlrng;
6749 else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6750 if (advice == MADV_DONTNEED) {
6751 /*
6752 * Future calls to pmap_is_modified()
6753 * can be avoided by making the page
6754 * dirty now.
6755 */
6756 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6757 vm_page_dirty(m);
6758 }
6759 atomic_clear_long(pte, PG_M | PG_A);
6760 } else if ((*pte & PG_A) != 0)
6761 atomic_clear_long(pte, PG_A);
6762 else
6763 goto maybe_invlrng;
6764
6765 if ((*pte & PG_G) != 0) {
6766 if (va == va_next)
6767 va = sva;
6768 } else
6769 anychanged = TRUE;
6770 continue;
6771 maybe_invlrng:
6772 if (va != va_next) {
6773 pmap_invalidate_range(pmap, va, sva);
6774 va = va_next;
6775 }
6776 }
6777 if (va != va_next)
6778 pmap_invalidate_range(pmap, va, sva);
6779 }
6780 if (anychanged)
6781 pmap_invalidate_all(pmap);
6782 PMAP_UNLOCK(pmap);
6783 pmap_delayed_invl_finished();
6784 }
6785
6786 /*
6787 * Clear the modify bits on the specified physical page.
6788 */
6789 void
6790 pmap_clear_modify(vm_page_t m)
6791 {
6792 struct md_page *pvh;
6793 pmap_t pmap;
6794 pv_entry_t next_pv, pv;
6795 pd_entry_t oldpde, *pde;
6796 pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6797 struct rwlock *lock;
6798 vm_offset_t va;
6799 int md_gen, pvh_gen;
6800
6801 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6802 ("pmap_clear_modify: page %p is not managed", m));
6803 VM_OBJECT_ASSERT_WLOCKED(m->object);
6804 KASSERT(!vm_page_xbusied(m),
6805 ("pmap_clear_modify: page %p is exclusive busied", m));
6806
6807 /*
6808 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6809 * If the object containing the page is locked and the page is not
6810 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6811 */
6812 if ((m->aflags & PGA_WRITEABLE) == 0)
6813 return;
6814 pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6815 pa_to_pvh(VM_PAGE_TO_PHYS(m));
6816 lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6817 rw_wlock(lock);
6818 restart:
6819 TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6820 pmap = PV_PMAP(pv);
6821 if (!PMAP_TRYLOCK(pmap)) {
6822 pvh_gen = pvh->pv_gen;
6823 rw_wunlock(lock);
6824 PMAP_LOCK(pmap);
6825 rw_wlock(lock);
6826 if (pvh_gen != pvh->pv_gen) {
6827 PMAP_UNLOCK(pmap);
6828 goto restart;
6829 }
6830 }
6831 PG_M = pmap_modified_bit(pmap);
6832 PG_V = pmap_valid_bit(pmap);
6833 PG_RW = pmap_rw_bit(pmap);
6834 va = pv->pv_va;
6835 pde = pmap_pde(pmap, va);
6836 oldpde = *pde;
6837 if ((oldpde & PG_RW) != 0) {
6838 if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6839 if ((oldpde & PG_W) == 0) {
6840 /*
6841 * Write protect the mapping to a
6842 * single page so that a subsequent
6843 * write access may repromote.
6844 */
6845 va += VM_PAGE_TO_PHYS(m) - (oldpde &
6846 PG_PS_FRAME);
6847 pte = pmap_pde_to_pte(pde, va);
6848 oldpte = *pte;
6849 if ((oldpte & PG_V) != 0) {
6850 while (!atomic_cmpset_long(pte,
6851 oldpte,
6852 oldpte & ~(PG_M | PG_RW)))
6853 oldpte = *pte;
6854 vm_page_dirty(m);
6855 pmap_invalidate_page(pmap, va);
6856 }
6857 }
6858 }
6859 }
6860 PMAP_UNLOCK(pmap);
6861 }
6862 TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6863 pmap = PV_PMAP(pv);
6864 if (!PMAP_TRYLOCK(pmap)) {
6865 md_gen = m->md.pv_gen;
6866 pvh_gen = pvh->pv_gen;
6867 rw_wunlock(lock);
6868 PMAP_LOCK(pmap);
6869 rw_wlock(lock);
6870 if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6871 PMAP_UNLOCK(pmap);
6872 goto restart;
6873 }
6874 }
6875 PG_M = pmap_modified_bit(pmap);
6876 PG_RW = pmap_rw_bit(pmap);
6877 pde = pmap_pde(pmap, pv->pv_va);
6878 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6879 " a 2mpage in page %p's pv list", m));
6880 pte = pmap_pde_to_pte(pde, pv->pv_va);
6881 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6882 atomic_clear_long(pte, PG_M);
6883 pmap_invalidate_page(pmap, pv->pv_va);
6884 }
6885 PMAP_UNLOCK(pmap);
6886 }
6887 rw_wunlock(lock);
6888 }
6889
6890 /*
6891 * Miscellaneous support routines follow
6892 */
6893
6894 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6895 static __inline void
6896 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6897 {
6898 u_int opte, npte;
6899
6900 /*
6901 * The cache mode bits are all in the low 32-bits of the
6902 * PTE, so we can just spin on updating the low 32-bits.
6903 */
6904 do {
6905 opte = *(u_int *)pte;
6906 npte = opte & ~mask;
6907 npte |= cache_bits;
6908 } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6909 }
6910
6911 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6912 static __inline void
6913 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6914 {
6915 u_int opde, npde;
6916
6917 /*
6918 * The cache mode bits are all in the low 32-bits of the
6919 * PDE, so we can just spin on updating the low 32-bits.
6920 */
6921 do {
6922 opde = *(u_int *)pde;
6923 npde = opde & ~mask;
6924 npde |= cache_bits;
6925 } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6926 }
6927
6928 /*
6929 * Map a set of physical memory pages into the kernel virtual
6930 * address space. Return a pointer to where it is mapped. This
6931 * routine is intended to be used for mapping device memory,
6932 * NOT real memory.
6933 */
6934 static void *
6935 pmap_mapdev_internal(vm_paddr_t pa, vm_size_t size, int mode, int flags)
6936 {
6937 struct pmap_preinit_mapping *ppim;
6938 vm_offset_t va, offset;
6939 vm_size_t tmpsize;
6940 int i;
6941
6942 offset = pa & PAGE_MASK;
6943 size = round_page(offset + size);
6944 pa = trunc_page(pa);
6945
6946 if (!pmap_initialized) {
6947 va = 0;
6948 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6949 ppim = pmap_preinit_mapping + i;
6950 if (ppim->va == 0) {
6951 ppim->pa = pa;
6952 ppim->sz = size;
6953 ppim->mode = mode;
6954 ppim->va = virtual_avail;
6955 virtual_avail += size;
6956 va = ppim->va;
6957 break;
6958 }
6959 }
6960 if (va == 0)
6961 panic("%s: too many preinit mappings", __func__);
6962 } else {
6963 /*
6964 * If we have a preinit mapping, re-use it.
6965 */
6966 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6967 ppim = pmap_preinit_mapping + i;
6968 if (ppim->pa == pa && ppim->sz == size &&
6969 (ppim->mode == mode ||
6970 (flags & MAPDEV_SETATTR) == 0))
6971 return ((void *)(ppim->va + offset));
6972 }
6973 /*
6974 * If the specified range of physical addresses fits within
6975 * the direct map window, use the direct map.
6976 */
6977 if (pa < dmaplimit && pa + size <= dmaplimit) {
6978 va = PHYS_TO_DMAP(pa);
6979 if ((flags & MAPDEV_SETATTR) != 0) {
6980 PMAP_LOCK(kernel_pmap);
6981 i = pmap_change_attr_locked(va, size, mode, flags);
6982 PMAP_UNLOCK(kernel_pmap);
6983 } else
6984 i = 0;
6985 if (!i)
6986 return ((void *)(va + offset));
6987 }
6988 va = kva_alloc(size);
6989 if (va == 0)
6990 panic("%s: Couldn't allocate KVA", __func__);
6991 }
6992 for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6993 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6994 pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6995 if ((flags & MAPDEV_FLUSHCACHE) != 0)
6996 pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6997 return ((void *)(va + offset));
6998 }
6999
7000 void *
7001 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
7002 {
7003
7004 return (pmap_mapdev_internal(pa, size, mode, MAPDEV_FLUSHCACHE |
7005 MAPDEV_SETATTR));
7006 }
7007
7008 void *
7009 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
7010 {
7011
7012 return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
7013 }
7014
7015 void *
7016 pmap_mapdev_pciecfg(vm_paddr_t pa, vm_size_t size)
7017 {
7018
7019 return (pmap_mapdev_internal(pa, size, PAT_UNCACHEABLE,
7020 MAPDEV_SETATTR));
7021 }
7022
7023 void *
7024 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
7025 {
7026
7027 return (pmap_mapdev_internal(pa, size, PAT_WRITE_BACK,
7028 MAPDEV_FLUSHCACHE));
7029 }
7030
7031 void
7032 pmap_unmapdev(vm_offset_t va, vm_size_t size)
7033 {
7034 struct pmap_preinit_mapping *ppim;
7035 vm_offset_t offset;
7036 int i;
7037
7038 /* If we gave a direct map region in pmap_mapdev, do nothing */
7039 if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
7040 return;
7041 offset = va & PAGE_MASK;
7042 size = round_page(offset + size);
7043 va = trunc_page(va);
7044 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
7045 ppim = pmap_preinit_mapping + i;
7046 if (ppim->va == va && ppim->sz == size) {
7047 if (pmap_initialized)
7048 return;
7049 ppim->pa = 0;
7050 ppim->va = 0;
7051 ppim->sz = 0;
7052 ppim->mode = 0;
7053 if (va + size == virtual_avail)
7054 virtual_avail = va;
7055 return;
7056 }
7057 }
7058 if (pmap_initialized)
7059 kva_free(va, size);
7060 }
7061
7062 /*
7063 * Tries to demote a 1GB page mapping.
7064 */
7065 static boolean_t
7066 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
7067 {
7068 pdp_entry_t newpdpe, oldpdpe;
7069 pd_entry_t *firstpde, newpde, *pde;
7070 pt_entry_t PG_A, PG_M, PG_RW, PG_V;
7071 vm_paddr_t pdpgpa;
7072 vm_page_t pdpg;
7073
7074 PG_A = pmap_accessed_bit(pmap);
7075 PG_M = pmap_modified_bit(pmap);
7076 PG_V = pmap_valid_bit(pmap);
7077 PG_RW = pmap_rw_bit(pmap);
7078
7079 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
7080 oldpdpe = *pdpe;
7081 KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
7082 ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
7083 if ((pdpg = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
7084 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
7085 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
7086 " in pmap %p", va, pmap);
7087 return (FALSE);
7088 }
7089 pdpgpa = VM_PAGE_TO_PHYS(pdpg);
7090 firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
7091 newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
7092 KASSERT((oldpdpe & PG_A) != 0,
7093 ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
7094 KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
7095 ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
7096 newpde = oldpdpe;
7097
7098 /*
7099 * Initialize the page directory page.
7100 */
7101 for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
7102 *pde = newpde;
7103 newpde += NBPDR;
7104 }
7105
7106 /*
7107 * Demote the mapping.
7108 */
7109 *pdpe = newpdpe;
7110
7111 /*
7112 * Invalidate a stale recursive mapping of the page directory page.
7113 */
7114 pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
7115
7116 pmap_pdpe_demotions++;
7117 CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
7118 " in pmap %p", va, pmap);
7119 return (TRUE);
7120 }
7121
7122 /*
7123 * Sets the memory attribute for the specified page.
7124 */
7125 void
7126 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
7127 {
7128
7129 m->md.pat_mode = ma;
7130
7131 /*
7132 * If "m" is a normal page, update its direct mapping. This update
7133 * can be relied upon to perform any cache operations that are
7134 * required for data coherence.
7135 */
7136 if ((m->flags & PG_FICTITIOUS) == 0 &&
7137 pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
7138 m->md.pat_mode))
7139 panic("memory attribute change on the direct map failed");
7140 }
7141
7142 /*
7143 * Changes the specified virtual address range's memory type to that given by
7144 * the parameter "mode". The specified virtual address range must be
7145 * completely contained within either the direct map or the kernel map. If
7146 * the virtual address range is contained within the kernel map, then the
7147 * memory type for each of the corresponding ranges of the direct map is also
7148 * changed. (The corresponding ranges of the direct map are those ranges that
7149 * map the same physical pages as the specified virtual address range.) These
7150 * changes to the direct map are necessary because Intel describes the
7151 * behavior of their processors as "undefined" if two or more mappings to the
7152 * same physical page have different memory types.
7153 *
7154 * Returns zero if the change completed successfully, and either EINVAL or
7155 * ENOMEM if the change failed. Specifically, EINVAL is returned if some part
7156 * of the virtual address range was not mapped, and ENOMEM is returned if
7157 * there was insufficient memory available to complete the change. In the
7158 * latter case, the memory type may have been changed on some part of the
7159 * virtual address range or the direct map.
7160 */
7161 int
7162 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
7163 {
7164 int error;
7165
7166 PMAP_LOCK(kernel_pmap);
7167 error = pmap_change_attr_locked(va, size, mode, MAPDEV_FLUSHCACHE);
7168 PMAP_UNLOCK(kernel_pmap);
7169 return (error);
7170 }
7171
7172 static int
7173 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode, int flags)
7174 {
7175 vm_offset_t base, offset, tmpva;
7176 vm_paddr_t pa_start, pa_end, pa_end1;
7177 pdp_entry_t *pdpe;
7178 pd_entry_t *pde;
7179 pt_entry_t *pte;
7180 int cache_bits_pte, cache_bits_pde, error;
7181 boolean_t changed;
7182
7183 PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
7184 base = trunc_page(va);
7185 offset = va & PAGE_MASK;
7186 size = round_page(offset + size);
7187
7188 /*
7189 * Only supported on kernel virtual addresses, including the direct
7190 * map but excluding the recursive map.
7191 */
7192 if (base < DMAP_MIN_ADDRESS)
7193 return (EINVAL);
7194
7195 cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
7196 cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
7197 changed = FALSE;
7198
7199 /*
7200 * Pages that aren't mapped aren't supported. Also break down 2MB pages
7201 * into 4KB pages if required.
7202 */
7203 for (tmpva = base; tmpva < base + size; ) {
7204 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7205 if (pdpe == NULL || *pdpe == 0)
7206 return (EINVAL);
7207 if (*pdpe & PG_PS) {
7208 /*
7209 * If the current 1GB page already has the required
7210 * memory type, then we need not demote this page. Just
7211 * increment tmpva to the next 1GB page frame.
7212 */
7213 if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
7214 tmpva = trunc_1gpage(tmpva) + NBPDP;
7215 continue;
7216 }
7217
7218 /*
7219 * If the current offset aligns with a 1GB page frame
7220 * and there is at least 1GB left within the range, then
7221 * we need not break down this page into 2MB pages.
7222 */
7223 if ((tmpva & PDPMASK) == 0 &&
7224 tmpva + PDPMASK < base + size) {
7225 tmpva += NBPDP;
7226 continue;
7227 }
7228 if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
7229 return (ENOMEM);
7230 }
7231 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7232 if (*pde == 0)
7233 return (EINVAL);
7234 if (*pde & PG_PS) {
7235 /*
7236 * If the current 2MB page already has the required
7237 * memory type, then we need not demote this page. Just
7238 * increment tmpva to the next 2MB page frame.
7239 */
7240 if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
7241 tmpva = trunc_2mpage(tmpva) + NBPDR;
7242 continue;
7243 }
7244
7245 /*
7246 * If the current offset aligns with a 2MB page frame
7247 * and there is at least 2MB left within the range, then
7248 * we need not break down this page into 4KB pages.
7249 */
7250 if ((tmpva & PDRMASK) == 0 &&
7251 tmpva + PDRMASK < base + size) {
7252 tmpva += NBPDR;
7253 continue;
7254 }
7255 if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
7256 return (ENOMEM);
7257 }
7258 pte = pmap_pde_to_pte(pde, tmpva);
7259 if (*pte == 0)
7260 return (EINVAL);
7261 tmpva += PAGE_SIZE;
7262 }
7263 error = 0;
7264
7265 /*
7266 * Ok, all the pages exist, so run through them updating their
7267 * cache mode if required.
7268 */
7269 pa_start = pa_end = 0;
7270 for (tmpva = base; tmpva < base + size; ) {
7271 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7272 if (*pdpe & PG_PS) {
7273 if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
7274 pmap_pde_attr(pdpe, cache_bits_pde,
7275 X86_PG_PDE_CACHE);
7276 changed = TRUE;
7277 }
7278 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7279 (*pdpe & PG_PS_FRAME) < dmaplimit) {
7280 if (pa_start == pa_end) {
7281 /* Start physical address run. */
7282 pa_start = *pdpe & PG_PS_FRAME;
7283 pa_end = pa_start + NBPDP;
7284 } else if (pa_end == (*pdpe & PG_PS_FRAME))
7285 pa_end += NBPDP;
7286 else {
7287 /* Run ended, update direct map. */
7288 error = pmap_change_attr_locked(
7289 PHYS_TO_DMAP(pa_start),
7290 pa_end - pa_start, mode, flags);
7291 if (error != 0)
7292 break;
7293 /* Start physical address run. */
7294 pa_start = *pdpe & PG_PS_FRAME;
7295 pa_end = pa_start + NBPDP;
7296 }
7297 }
7298 tmpva = trunc_1gpage(tmpva) + NBPDP;
7299 continue;
7300 }
7301 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7302 if (*pde & PG_PS) {
7303 if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
7304 pmap_pde_attr(pde, cache_bits_pde,
7305 X86_PG_PDE_CACHE);
7306 changed = TRUE;
7307 }
7308 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7309 (*pde & PG_PS_FRAME) < dmaplimit) {
7310 if (pa_start == pa_end) {
7311 /* Start physical address run. */
7312 pa_start = *pde & PG_PS_FRAME;
7313 pa_end = pa_start + NBPDR;
7314 } else if (pa_end == (*pde & PG_PS_FRAME))
7315 pa_end += NBPDR;
7316 else {
7317 /* Run ended, update direct map. */
7318 error = pmap_change_attr_locked(
7319 PHYS_TO_DMAP(pa_start),
7320 pa_end - pa_start, mode, flags);
7321 if (error != 0)
7322 break;
7323 /* Start physical address run. */
7324 pa_start = *pde & PG_PS_FRAME;
7325 pa_end = pa_start + NBPDR;
7326 }
7327 }
7328 tmpva = trunc_2mpage(tmpva) + NBPDR;
7329 } else {
7330 pte = pmap_pde_to_pte(pde, tmpva);
7331 if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
7332 pmap_pte_attr(pte, cache_bits_pte,
7333 X86_PG_PTE_CACHE);
7334 changed = TRUE;
7335 }
7336 if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7337 (*pte & PG_FRAME) < dmaplimit) {
7338 if (pa_start == pa_end) {
7339 /* Start physical address run. */
7340 pa_start = *pte & PG_FRAME;
7341 pa_end = pa_start + PAGE_SIZE;
7342 } else if (pa_end == (*pte & PG_FRAME))
7343 pa_end += PAGE_SIZE;
7344 else {
7345 /* Run ended, update direct map. */
7346 error = pmap_change_attr_locked(
7347 PHYS_TO_DMAP(pa_start),
7348 pa_end - pa_start, mode, flags);
7349 if (error != 0)
7350 break;
7351 /* Start physical address run. */
7352 pa_start = *pte & PG_FRAME;
7353 pa_end = pa_start + PAGE_SIZE;
7354 }
7355 }
7356 tmpva += PAGE_SIZE;
7357 }
7358 }
7359 if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
7360 pa_end1 = MIN(pa_end, dmaplimit);
7361 if (pa_start != pa_end1)
7362 error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
7363 pa_end1 - pa_start, mode, flags);
7364 }
7365
7366 /*
7367 * Flush CPU caches if required to make sure any data isn't cached that
7368 * shouldn't be, etc.
7369 */
7370 if (changed) {
7371 pmap_invalidate_range(kernel_pmap, base, tmpva);
7372 if ((flags & MAPDEV_FLUSHCACHE) != 0)
7373 pmap_invalidate_cache_range(base, tmpva, FALSE);
7374 }
7375 return (error);
7376 }
7377
7378 /*
7379 * Demotes any mapping within the direct map region that covers more than the
7380 * specified range of physical addresses. This range's size must be a power
7381 * of two and its starting address must be a multiple of its size. Since the
7382 * demotion does not change any attributes of the mapping, a TLB invalidation
7383 * is not mandatory. The caller may, however, request a TLB invalidation.
7384 */
7385 void
7386 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
7387 {
7388 pdp_entry_t *pdpe;
7389 pd_entry_t *pde;
7390 vm_offset_t va;
7391 boolean_t changed;
7392
7393 if (len == 0)
7394 return;
7395 KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
7396 KASSERT((base & (len - 1)) == 0,
7397 ("pmap_demote_DMAP: base is not a multiple of len"));
7398 if (len < NBPDP && base < dmaplimit) {
7399 va = PHYS_TO_DMAP(base);
7400 changed = FALSE;
7401 PMAP_LOCK(kernel_pmap);
7402 pdpe = pmap_pdpe(kernel_pmap, va);
7403 if ((*pdpe & X86_PG_V) == 0)
7404 panic("pmap_demote_DMAP: invalid PDPE");
7405 if ((*pdpe & PG_PS) != 0) {
7406 if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
7407 panic("pmap_demote_DMAP: PDPE failed");
7408 changed = TRUE;
7409 }
7410 if (len < NBPDR) {
7411 pde = pmap_pdpe_to_pde(pdpe, va);
7412 if ((*pde & X86_PG_V) == 0)
7413 panic("pmap_demote_DMAP: invalid PDE");
7414 if ((*pde & PG_PS) != 0) {
7415 if (!pmap_demote_pde(kernel_pmap, pde, va))
7416 panic("pmap_demote_DMAP: PDE failed");
7417 changed = TRUE;
7418 }
7419 }
7420 if (changed && invalidate)
7421 pmap_invalidate_page(kernel_pmap, va);
7422 PMAP_UNLOCK(kernel_pmap);
7423 }
7424 }
7425
7426 /*
7427 * perform the pmap work for mincore
7428 */
7429 int
7430 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
7431 {
7432 pd_entry_t *pdep;
7433 pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
7434 vm_paddr_t pa;
7435 int val;
7436
7437 PG_A = pmap_accessed_bit(pmap);
7438 PG_M = pmap_modified_bit(pmap);
7439 PG_V = pmap_valid_bit(pmap);
7440 PG_RW = pmap_rw_bit(pmap);
7441
7442 PMAP_LOCK(pmap);
7443 retry:
7444 pdep = pmap_pde(pmap, addr);
7445 if (pdep != NULL && (*pdep & PG_V)) {
7446 if (*pdep & PG_PS) {
7447 pte = *pdep;
7448 /* Compute the physical address of the 4KB page. */
7449 pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
7450 PG_FRAME;
7451 val = MINCORE_SUPER;
7452 } else {
7453 pte = *pmap_pde_to_pte(pdep, addr);
7454 pa = pte & PG_FRAME;
7455 val = 0;
7456 }
7457 } else {
7458 pte = 0;
7459 pa = 0;
7460 val = 0;
7461 }
7462 if ((pte & PG_V) != 0) {
7463 val |= MINCORE_INCORE;
7464 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7465 val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
7466 if ((pte & PG_A) != 0)
7467 val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
7468 }
7469 if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
7470 (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
7471 (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
7472 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
7473 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
7474 goto retry;
7475 } else
7476 PA_UNLOCK_COND(*locked_pa);
7477 PMAP_UNLOCK(pmap);
7478 return (val);
7479 }
7480
7481 static uint64_t
7482 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
7483 {
7484 uint32_t gen, new_gen, pcid_next;
7485
7486 CRITICAL_ASSERT(curthread);
7487 gen = PCPU_GET(pcid_gen);
7488 if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN)
7489 return (pti ? 0 : CR3_PCID_SAVE);
7490 if (pmap->pm_pcids[cpuid].pm_gen == gen)
7491 return (CR3_PCID_SAVE);
7492 pcid_next = PCPU_GET(pcid_next);
7493 KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
7494 (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
7495 ("cpu %d pcid_next %#x", cpuid, pcid_next));
7496 if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
7497 (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
7498 new_gen = gen + 1;
7499 if (new_gen == 0)
7500 new_gen = 1;
7501 PCPU_SET(pcid_gen, new_gen);
7502 pcid_next = PMAP_PCID_KERN + 1;
7503 } else {
7504 new_gen = gen;
7505 }
7506 pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
7507 pmap->pm_pcids[cpuid].pm_gen = new_gen;
7508 PCPU_SET(pcid_next, pcid_next + 1);
7509 return (0);
7510 }
7511
7512 void
7513 pmap_activate_sw(struct thread *td)
7514 {
7515 pmap_t oldpmap, pmap;
7516 struct invpcid_descr d;
7517 uint64_t cached, cr3, kcr3, kern_pti_cached, rsp0, ucr3;
7518 register_t rflags;
7519 u_int cpuid;
7520 struct amd64tss *tssp;
7521
7522 oldpmap = PCPU_GET(curpmap);
7523 pmap = vmspace_pmap(td->td_proc->p_vmspace);
7524 if (oldpmap == pmap)
7525 return;
7526 cpuid = PCPU_GET(cpuid);
7527 #ifdef SMP
7528 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7529 #else
7530 CPU_SET(cpuid, &pmap->pm_active);
7531 #endif
7532 cr3 = rcr3();
7533 if (pmap_pcid_enabled) {
7534 cached = pmap_pcid_alloc(pmap, cpuid);
7535 KASSERT(pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
7536 ("pmap %p cpu %d pcid %#x", pmap, cpuid,
7537 pmap->pm_pcids[cpuid].pm_pcid));
7538 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
7539 pmap == kernel_pmap,
7540 ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
7541 td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
7542
7543 /*
7544 * If the INVPCID instruction is not available,
7545 * invltlb_pcid_handler() is used for handle
7546 * invalidate_all IPI, which checks for curpmap ==
7547 * smp_tlb_pmap. Below operations sequence has a
7548 * window where %CR3 is loaded with the new pmap's
7549 * PML4 address, but curpmap value is not yet updated.
7550 * This causes invltlb IPI handler, called between the
7551 * updates, to execute as NOP, which leaves stale TLB
7552 * entries.
7553 *
7554 * Note that the most typical use of
7555 * pmap_activate_sw(), from the context switch, is
7556 * immune to this race, because interrupts are
7557 * disabled (while the thread lock is owned), and IPI
7558 * happens after curpmap is updated. Protect other
7559 * callers in a similar way, by disabling interrupts
7560 * around the %cr3 register reload and curpmap
7561 * assignment.
7562 */
7563 if (!invpcid_works)
7564 rflags = intr_disable();
7565
7566 kern_pti_cached = pti ? 0 : cached;
7567 if (!kern_pti_cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
7568 load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
7569 kern_pti_cached);
7570 }
7571 PCPU_SET(curpmap, pmap);
7572 if (pti) {
7573 kcr3 = pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid;
7574 ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[cpuid].pm_pcid |
7575 PMAP_PCID_USER_PT;
7576
7577 if (!cached && pmap->pm_ucr3 != PMAP_NO_CR3) {
7578 /*
7579 * Manually invalidate translations cached
7580 * from the user page table. They are not
7581 * flushed by reload of cr3 with the kernel
7582 * page table pointer above.
7583 */
7584 if (invpcid_works) {
7585 d.pcid = PMAP_PCID_USER_PT |
7586 pmap->pm_pcids[cpuid].pm_pcid;
7587 d.pad = 0;
7588 d.addr = 0;
7589 invpcid(&d, INVPCID_CTX);
7590 } else {
7591 pmap_pti_pcid_invalidate(ucr3, kcr3);
7592 }
7593 }
7594
7595 PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
7596 PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
7597 }
7598 if (!invpcid_works)
7599 intr_restore(rflags);
7600 if (cached)
7601 PCPU_INC(pm_save_cnt);
7602 } else {
7603 load_cr3(pmap->pm_cr3);
7604 PCPU_SET(curpmap, pmap);
7605 if (pti) {
7606 PCPU_SET(kcr3, pmap->pm_cr3);
7607 PCPU_SET(ucr3, pmap->pm_ucr3);
7608 }
7609 }
7610 if (pmap->pm_ucr3 != PMAP_NO_CR3) {
7611 rsp0 = ((vm_offset_t)PCPU_PTR(pti_stack) +
7612 PC_PTI_STACK_SZ * sizeof(uint64_t)) & ~0xful;
7613 tssp = PCPU_GET(tssp);
7614 tssp->tss_rsp0 = rsp0;
7615 }
7616 #ifdef SMP
7617 CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
7618 #else
7619 CPU_CLR(cpuid, &oldpmap->pm_active);
7620 #endif
7621 }
7622
7623 void
7624 pmap_activate(struct thread *td)
7625 {
7626
7627 critical_enter();
7628 pmap_activate_sw(td);
7629 critical_exit();
7630 }
7631
7632 void
7633 pmap_activate_boot(pmap_t pmap)
7634 {
7635 uint64_t kcr3;
7636 u_int cpuid;
7637
7638 /*
7639 * kernel_pmap must be never deactivated, and we ensure that
7640 * by never activating it at all.
7641 */
7642 MPASS(pmap != kernel_pmap);
7643
7644 cpuid = PCPU_GET(cpuid);
7645 #ifdef SMP
7646 CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7647 #else
7648 CPU_SET(cpuid, &pmap->pm_active);
7649 #endif
7650 PCPU_SET(curpmap, pmap);
7651 if (pti) {
7652 kcr3 = pmap->pm_cr3;
7653 if (pmap_pcid_enabled)
7654 kcr3 |= pmap->pm_pcids[cpuid].pm_pcid | CR3_PCID_SAVE;
7655 } else {
7656 kcr3 = PMAP_NO_CR3;
7657 }
7658 PCPU_SET(kcr3, kcr3);
7659 PCPU_SET(ucr3, PMAP_NO_CR3);
7660 }
7661
7662 void
7663 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
7664 {
7665 }
7666
7667 /*
7668 * Increase the starting virtual address of the given mapping if a
7669 * different alignment might result in more superpage mappings.
7670 */
7671 void
7672 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7673 vm_offset_t *addr, vm_size_t size)
7674 {
7675 vm_offset_t superpage_offset;
7676
7677 if (size < NBPDR)
7678 return;
7679 if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7680 offset += ptoa(object->pg_color);
7681 superpage_offset = offset & PDRMASK;
7682 if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
7683 (*addr & PDRMASK) == superpage_offset)
7684 return;
7685 if ((*addr & PDRMASK) < superpage_offset)
7686 *addr = (*addr & ~PDRMASK) + superpage_offset;
7687 else
7688 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
7689 }
7690
7691 #ifdef INVARIANTS
7692 static unsigned long num_dirty_emulations;
7693 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
7694 &num_dirty_emulations, 0, NULL);
7695
7696 static unsigned long num_accessed_emulations;
7697 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
7698 &num_accessed_emulations, 0, NULL);
7699
7700 static unsigned long num_superpage_accessed_emulations;
7701 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7702 &num_superpage_accessed_emulations, 0, NULL);
7703
7704 static unsigned long ad_emulation_superpage_promotions;
7705 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7706 &ad_emulation_superpage_promotions, 0, NULL);
7707 #endif /* INVARIANTS */
7708
7709 int
7710 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7711 {
7712 int rv;
7713 struct rwlock *lock;
7714 #if VM_NRESERVLEVEL > 0
7715 vm_page_t m, mpte;
7716 #endif
7717 pd_entry_t *pde;
7718 pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7719
7720 KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7721 ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7722
7723 if (!pmap_emulate_ad_bits(pmap))
7724 return (-1);
7725
7726 PG_A = pmap_accessed_bit(pmap);
7727 PG_M = pmap_modified_bit(pmap);
7728 PG_V = pmap_valid_bit(pmap);
7729 PG_RW = pmap_rw_bit(pmap);
7730
7731 rv = -1;
7732 lock = NULL;
7733 PMAP_LOCK(pmap);
7734
7735 pde = pmap_pde(pmap, va);
7736 if (pde == NULL || (*pde & PG_V) == 0)
7737 goto done;
7738
7739 if ((*pde & PG_PS) != 0) {
7740 if (ftype == VM_PROT_READ) {
7741 #ifdef INVARIANTS
7742 atomic_add_long(&num_superpage_accessed_emulations, 1);
7743 #endif
7744 *pde |= PG_A;
7745 rv = 0;
7746 }
7747 goto done;
7748 }
7749
7750 pte = pmap_pde_to_pte(pde, va);
7751 if ((*pte & PG_V) == 0)
7752 goto done;
7753
7754 if (ftype == VM_PROT_WRITE) {
7755 if ((*pte & PG_RW) == 0)
7756 goto done;
7757 /*
7758 * Set the modified and accessed bits simultaneously.
7759 *
7760 * Intel EPT PTEs that do software emulation of A/D bits map
7761 * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7762 * An EPT misconfiguration is triggered if the PTE is writable
7763 * but not readable (WR=10). This is avoided by setting PG_A
7764 * and PG_M simultaneously.
7765 */
7766 *pte |= PG_M | PG_A;
7767 } else {
7768 *pte |= PG_A;
7769 }
7770
7771 #if VM_NRESERVLEVEL > 0
7772 /* try to promote the mapping */
7773 if (va < VM_MAXUSER_ADDRESS)
7774 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7775 else
7776 mpte = NULL;
7777
7778 m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7779
7780 if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7781 pmap_ps_enabled(pmap) &&
7782 (m->flags & PG_FICTITIOUS) == 0 &&
7783 vm_reserv_level_iffullpop(m) == 0) {
7784 pmap_promote_pde(pmap, pde, va, &lock);
7785 #ifdef INVARIANTS
7786 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7787 #endif
7788 }
7789 #endif
7790
7791 #ifdef INVARIANTS
7792 if (ftype == VM_PROT_WRITE)
7793 atomic_add_long(&num_dirty_emulations, 1);
7794 else
7795 atomic_add_long(&num_accessed_emulations, 1);
7796 #endif
7797 rv = 0; /* success */
7798 done:
7799 if (lock != NULL)
7800 rw_wunlock(lock);
7801 PMAP_UNLOCK(pmap);
7802 return (rv);
7803 }
7804
7805 void
7806 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7807 {
7808 pml4_entry_t *pml4;
7809 pdp_entry_t *pdp;
7810 pd_entry_t *pde;
7811 pt_entry_t *pte, PG_V;
7812 int idx;
7813
7814 idx = 0;
7815 PG_V = pmap_valid_bit(pmap);
7816 PMAP_LOCK(pmap);
7817
7818 pml4 = pmap_pml4e(pmap, va);
7819 ptr[idx++] = *pml4;
7820 if ((*pml4 & PG_V) == 0)
7821 goto done;
7822
7823 pdp = pmap_pml4e_to_pdpe(pml4, va);
7824 ptr[idx++] = *pdp;
7825 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7826 goto done;
7827
7828 pde = pmap_pdpe_to_pde(pdp, va);
7829 ptr[idx++] = *pde;
7830 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7831 goto done;
7832
7833 pte = pmap_pde_to_pte(pde, va);
7834 ptr[idx++] = *pte;
7835
7836 done:
7837 PMAP_UNLOCK(pmap);
7838 *num = idx;
7839 }
7840
7841 /**
7842 * Get the kernel virtual address of a set of physical pages. If there are
7843 * physical addresses not covered by the DMAP perform a transient mapping
7844 * that will be removed when calling pmap_unmap_io_transient.
7845 *
7846 * \param page The pages the caller wishes to obtain the virtual
7847 * address on the kernel memory map.
7848 * \param vaddr On return contains the kernel virtual memory address
7849 * of the pages passed in the page parameter.
7850 * \param count Number of pages passed in.
7851 * \param can_fault TRUE if the thread using the mapped pages can take
7852 * page faults, FALSE otherwise.
7853 *
7854 * \returns TRUE if the caller must call pmap_unmap_io_transient when
7855 * finished or FALSE otherwise.
7856 *
7857 */
7858 boolean_t
7859 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7860 boolean_t can_fault)
7861 {
7862 vm_paddr_t paddr;
7863 boolean_t needs_mapping;
7864 pt_entry_t *pte;
7865 int cache_bits, error, i;
7866
7867 /*
7868 * Allocate any KVA space that we need, this is done in a separate
7869 * loop to prevent calling vmem_alloc while pinned.
7870 */
7871 needs_mapping = FALSE;
7872 for (i = 0; i < count; i++) {
7873 paddr = VM_PAGE_TO_PHYS(page[i]);
7874 if (__predict_false(paddr >= dmaplimit)) {
7875 error = vmem_alloc(kernel_arena, PAGE_SIZE,
7876 M_BESTFIT | M_WAITOK, &vaddr[i]);
7877 KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7878 needs_mapping = TRUE;
7879 } else {
7880 vaddr[i] = PHYS_TO_DMAP(paddr);
7881 }
7882 }
7883
7884 /* Exit early if everything is covered by the DMAP */
7885 if (!needs_mapping)
7886 return (FALSE);
7887
7888 /*
7889 * NB: The sequence of updating a page table followed by accesses
7890 * to the corresponding pages used in the !DMAP case is subject to
7891 * the situation described in the "AMD64 Architecture Programmer's
7892 * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7893 * Coherency Considerations". Therefore, issuing the INVLPG right
7894 * after modifying the PTE bits is crucial.
7895 */
7896 if (!can_fault)
7897 sched_pin();
7898 for (i = 0; i < count; i++) {
7899 paddr = VM_PAGE_TO_PHYS(page[i]);
7900 if (paddr >= dmaplimit) {
7901 if (can_fault) {
7902 /*
7903 * Slow path, since we can get page faults
7904 * while mappings are active don't pin the
7905 * thread to the CPU and instead add a global
7906 * mapping visible to all CPUs.
7907 */
7908 pmap_qenter(vaddr[i], &page[i], 1);
7909 } else {
7910 pte = vtopte(vaddr[i]);
7911 cache_bits = pmap_cache_bits(kernel_pmap,
7912 page[i]->md.pat_mode, 0);
7913 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7914 cache_bits);
7915 invlpg(vaddr[i]);
7916 }
7917 }
7918 }
7919
7920 return (needs_mapping);
7921 }
7922
7923 void
7924 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7925 boolean_t can_fault)
7926 {
7927 vm_paddr_t paddr;
7928 int i;
7929
7930 if (!can_fault)
7931 sched_unpin();
7932 for (i = 0; i < count; i++) {
7933 paddr = VM_PAGE_TO_PHYS(page[i]);
7934 if (paddr >= dmaplimit) {
7935 if (can_fault)
7936 pmap_qremove(vaddr[i], 1);
7937 vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7938 }
7939 }
7940 }
7941
7942 vm_offset_t
7943 pmap_quick_enter_page(vm_page_t m)
7944 {
7945 vm_paddr_t paddr;
7946
7947 paddr = VM_PAGE_TO_PHYS(m);
7948 if (paddr < dmaplimit)
7949 return (PHYS_TO_DMAP(paddr));
7950 mtx_lock_spin(&qframe_mtx);
7951 KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7952 pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7953 X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7954 return (qframe);
7955 }
7956
7957 void
7958 pmap_quick_remove_page(vm_offset_t addr)
7959 {
7960
7961 if (addr != qframe)
7962 return;
7963 pte_store(vtopte(qframe), 0);
7964 invlpg(qframe);
7965 mtx_unlock_spin(&qframe_mtx);
7966 }
7967
7968 static vm_page_t
7969 pmap_pti_alloc_page(void)
7970 {
7971 vm_page_t m;
7972
7973 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7974 m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_NOBUSY |
7975 VM_ALLOC_WIRED | VM_ALLOC_ZERO);
7976 return (m);
7977 }
7978
7979 static bool
7980 pmap_pti_free_page(vm_page_t m)
7981 {
7982
7983 KASSERT(m->wire_count > 0, ("page %p not wired", m));
7984 m->wire_count--;
7985 if (m->wire_count != 0)
7986 return (false);
7987 atomic_subtract_int(&vm_cnt.v_wire_count, 1);
7988 vm_page_free_zero(m);
7989 return (true);
7990 }
7991
7992 static void
7993 pmap_pti_init(void)
7994 {
7995 vm_page_t pml4_pg;
7996 pdp_entry_t *pdpe;
7997 vm_offset_t va;
7998 int i;
7999
8000 if (!pti)
8001 return;
8002 pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
8003 VM_OBJECT_WLOCK(pti_obj);
8004 pml4_pg = pmap_pti_alloc_page();
8005 pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
8006 for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
8007 va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
8008 pdpe = pmap_pti_pdpe(va);
8009 pmap_pti_wire_pte(pdpe);
8010 }
8011 pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
8012 (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
8013 pmap_pti_add_kva_locked((vm_offset_t)gdt, (vm_offset_t)gdt +
8014 sizeof(struct user_segment_descriptor) * NGDT * MAXCPU, false);
8015 pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
8016 sizeof(struct gate_descriptor) * NIDT, false);
8017 pmap_pti_add_kva_locked((vm_offset_t)common_tss,
8018 (vm_offset_t)common_tss + sizeof(struct amd64tss) * MAXCPU, false);
8019 CPU_FOREACH(i) {
8020 /* Doublefault stack IST 1 */
8021 va = common_tss[i].tss_ist1;
8022 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
8023 /* NMI stack IST 2 */
8024 va = common_tss[i].tss_ist2 + sizeof(struct nmi_pcpu);
8025 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
8026 /* MC# stack IST 3 */
8027 va = common_tss[i].tss_ist3 + sizeof(struct nmi_pcpu);
8028 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
8029 /* DB# stack IST 4 */
8030 va = common_tss[i].tss_ist4 + sizeof(struct nmi_pcpu);
8031 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
8032 }
8033 pmap_pti_add_kva_locked((vm_offset_t)kernphys + KERNBASE,
8034 (vm_offset_t)etext, true);
8035 pti_finalized = true;
8036 VM_OBJECT_WUNLOCK(pti_obj);
8037 }
8038 SYSINIT(pmap_pti, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_pti_init, NULL);
8039
8040 static pdp_entry_t *
8041 pmap_pti_pdpe(vm_offset_t va)
8042 {
8043 pml4_entry_t *pml4e;
8044 pdp_entry_t *pdpe;
8045 vm_page_t m;
8046 vm_pindex_t pml4_idx;
8047 vm_paddr_t mphys;
8048
8049 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8050
8051 pml4_idx = pmap_pml4e_index(va);
8052 pml4e = &pti_pml4[pml4_idx];
8053 m = NULL;
8054 if (*pml4e == 0) {
8055 if (pti_finalized)
8056 panic("pml4 alloc after finalization\n");
8057 m = pmap_pti_alloc_page();
8058 if (*pml4e != 0) {
8059 pmap_pti_free_page(m);
8060 mphys = *pml4e & ~PAGE_MASK;
8061 } else {
8062 mphys = VM_PAGE_TO_PHYS(m);
8063 *pml4e = mphys | X86_PG_RW | X86_PG_V;
8064 }
8065 } else {
8066 mphys = *pml4e & ~PAGE_MASK;
8067 }
8068 pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
8069 return (pdpe);
8070 }
8071
8072 static void
8073 pmap_pti_wire_pte(void *pte)
8074 {
8075 vm_page_t m;
8076
8077 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8078 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
8079 m->wire_count++;
8080 }
8081
8082 static void
8083 pmap_pti_unwire_pde(void *pde, bool only_ref)
8084 {
8085 vm_page_t m;
8086
8087 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8088 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
8089 MPASS(m->wire_count > 0);
8090 MPASS(only_ref || m->wire_count > 1);
8091 pmap_pti_free_page(m);
8092 }
8093
8094 static void
8095 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
8096 {
8097 vm_page_t m;
8098 pd_entry_t *pde;
8099
8100 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8101 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
8102 MPASS(m->wire_count > 0);
8103 if (pmap_pti_free_page(m)) {
8104 pde = pmap_pti_pde(va);
8105 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
8106 *pde = 0;
8107 pmap_pti_unwire_pde(pde, false);
8108 }
8109 }
8110
8111 static pd_entry_t *
8112 pmap_pti_pde(vm_offset_t va)
8113 {
8114 pdp_entry_t *pdpe;
8115 pd_entry_t *pde;
8116 vm_page_t m;
8117 vm_pindex_t pd_idx;
8118 vm_paddr_t mphys;
8119
8120 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8121
8122 pdpe = pmap_pti_pdpe(va);
8123 if (*pdpe == 0) {
8124 m = pmap_pti_alloc_page();
8125 if (*pdpe != 0) {
8126 pmap_pti_free_page(m);
8127 MPASS((*pdpe & X86_PG_PS) == 0);
8128 mphys = *pdpe & ~PAGE_MASK;
8129 } else {
8130 mphys = VM_PAGE_TO_PHYS(m);
8131 *pdpe = mphys | X86_PG_RW | X86_PG_V;
8132 }
8133 } else {
8134 MPASS((*pdpe & X86_PG_PS) == 0);
8135 mphys = *pdpe & ~PAGE_MASK;
8136 }
8137
8138 pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
8139 pd_idx = pmap_pde_index(va);
8140 pde += pd_idx;
8141 return (pde);
8142 }
8143
8144 static pt_entry_t *
8145 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
8146 {
8147 pd_entry_t *pde;
8148 pt_entry_t *pte;
8149 vm_page_t m;
8150 vm_paddr_t mphys;
8151
8152 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8153
8154 pde = pmap_pti_pde(va);
8155 if (unwire_pde != NULL) {
8156 *unwire_pde = true;
8157 pmap_pti_wire_pte(pde);
8158 }
8159 if (*pde == 0) {
8160 m = pmap_pti_alloc_page();
8161 if (*pde != 0) {
8162 pmap_pti_free_page(m);
8163 MPASS((*pde & X86_PG_PS) == 0);
8164 mphys = *pde & ~(PAGE_MASK | pg_nx);
8165 } else {
8166 mphys = VM_PAGE_TO_PHYS(m);
8167 *pde = mphys | X86_PG_RW | X86_PG_V;
8168 if (unwire_pde != NULL)
8169 *unwire_pde = false;
8170 }
8171 } else {
8172 MPASS((*pde & X86_PG_PS) == 0);
8173 mphys = *pde & ~(PAGE_MASK | pg_nx);
8174 }
8175
8176 pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
8177 pte += pmap_pte_index(va);
8178
8179 return (pte);
8180 }
8181
8182 static void
8183 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
8184 {
8185 vm_paddr_t pa;
8186 pd_entry_t *pde;
8187 pt_entry_t *pte, ptev;
8188 bool unwire_pde;
8189
8190 VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8191
8192 sva = trunc_page(sva);
8193 MPASS(sva > VM_MAXUSER_ADDRESS);
8194 eva = round_page(eva);
8195 MPASS(sva < eva);
8196 for (; sva < eva; sva += PAGE_SIZE) {
8197 pte = pmap_pti_pte(sva, &unwire_pde);
8198 pa = pmap_kextract(sva);
8199 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A | X86_PG_G |
8200 (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
8201 VM_MEMATTR_DEFAULT, FALSE);
8202 if (*pte == 0) {
8203 pte_store(pte, ptev);
8204 pmap_pti_wire_pte(pte);
8205 } else {
8206 KASSERT(!pti_finalized,
8207 ("pti overlap after fin %#lx %#lx %#lx",
8208 sva, *pte, ptev));
8209 KASSERT(*pte == ptev,
8210 ("pti non-identical pte after fin %#lx %#lx %#lx",
8211 sva, *pte, ptev));
8212 }
8213 if (unwire_pde) {
8214 pde = pmap_pti_pde(sva);
8215 pmap_pti_unwire_pde(pde, true);
8216 }
8217 }
8218 }
8219
8220 void
8221 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
8222 {
8223
8224 if (!pti)
8225 return;
8226 VM_OBJECT_WLOCK(pti_obj);
8227 pmap_pti_add_kva_locked(sva, eva, exec);
8228 VM_OBJECT_WUNLOCK(pti_obj);
8229 }
8230
8231 void
8232 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
8233 {
8234 pt_entry_t *pte;
8235 vm_offset_t va;
8236
8237 if (!pti)
8238 return;
8239 sva = rounddown2(sva, PAGE_SIZE);
8240 MPASS(sva > VM_MAXUSER_ADDRESS);
8241 eva = roundup2(eva, PAGE_SIZE);
8242 MPASS(sva < eva);
8243 VM_OBJECT_WLOCK(pti_obj);
8244 for (va = sva; va < eva; va += PAGE_SIZE) {
8245 pte = pmap_pti_pte(va, NULL);
8246 KASSERT((*pte & X86_PG_V) != 0,
8247 ("invalid pte va %#lx pte %#lx pt %#lx", va,
8248 (u_long)pte, *pte));
8249 pte_clear(pte);
8250 pmap_pti_unwire_pte(pte, va);
8251 }
8252 pmap_invalidate_range(kernel_pmap, sva, eva);
8253 VM_OBJECT_WUNLOCK(pti_obj);
8254 }
8255
8256 #include "opt_ddb.h"
8257 #ifdef DDB
8258 #include <ddb/ddb.h>
8259
8260 DB_SHOW_COMMAND(pte, pmap_print_pte)
8261 {
8262 pmap_t pmap;
8263 pml4_entry_t *pml4;
8264 pdp_entry_t *pdp;
8265 pd_entry_t *pde;
8266 pt_entry_t *pte, PG_V;
8267 vm_offset_t va;
8268
8269 if (have_addr) {
8270 va = (vm_offset_t)addr;
8271 pmap = PCPU_GET(curpmap); /* XXX */
8272 } else {
8273 db_printf("show pte addr\n");
8274 return;
8275 }
8276 PG_V = pmap_valid_bit(pmap);
8277 pml4 = pmap_pml4e(pmap, va);
8278 db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
8279 if ((*pml4 & PG_V) == 0) {
8280 db_printf("\n");
8281 return;
8282 }
8283 pdp = pmap_pml4e_to_pdpe(pml4, va);
8284 db_printf(" pdpe %#016lx", *pdp);
8285 if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
8286 db_printf("\n");
8287 return;
8288 }
8289 pde = pmap_pdpe_to_pde(pdp, va);
8290 db_printf(" pde %#016lx", *pde);
8291 if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
8292 db_printf("\n");
8293 return;
8294 }
8295 pte = pmap_pde_to_pte(pde, va);
8296 db_printf(" pte %#016lx\n", *pte);
8297 }
8298
8299 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
8300 {
8301 vm_paddr_t a;
8302
8303 if (have_addr) {
8304 a = (vm_paddr_t)addr;
8305 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
8306 } else {
8307 db_printf("show phys2dmap addr\n");
8308 }
8309 }
8310 #endif
Cache object: be329e20066eb8ad63ee586455f29521
|