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