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