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