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