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