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