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