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