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