]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/amd64/pmap.c
Revert r335999 to re-commit with the correct error message.
[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                                 vm_page_hold(m);
2312                         }
2313                 } else {
2314                         pte = *pmap_pde_to_pte(pdep, va);
2315                         if ((pte & PG_V) &&
2316                             ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
2317                                 if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
2318                                     &pa))
2319                                         goto retry;
2320                                 m = PHYS_TO_VM_PAGE(pa);
2321                                 if (m != NULL)
2322                                         vm_page_hold(m);
2323                         }
2324                 }
2325         }
2326         PA_UNLOCK_COND(pa);
2327         PMAP_UNLOCK(pmap);
2328         return (m);
2329 }
2330
2331 vm_paddr_t
2332 pmap_kextract(vm_offset_t va)
2333 {
2334         pd_entry_t pde;
2335         vm_paddr_t pa;
2336
2337         if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS) {
2338                 pa = DMAP_TO_PHYS(va);
2339         } else {
2340                 pde = *vtopde(va);
2341                 if (pde & PG_PS) {
2342                         pa = (pde & PG_PS_FRAME) | (va & PDRMASK);
2343                 } else {
2344                         /*
2345                          * Beware of a concurrent promotion that changes the
2346                          * PDE at this point!  For example, vtopte() must not
2347                          * be used to access the PTE because it would use the
2348                          * new PDE.  It is, however, safe to use the old PDE
2349                          * because the page table page is preserved by the
2350                          * promotion.
2351                          */
2352                         pa = *pmap_pde_to_pte(&pde, va);
2353                         pa = (pa & PG_FRAME) | (va & PAGE_MASK);
2354                 }
2355         }
2356         return (pa);
2357 }
2358
2359 /***************************************************
2360  * Low level mapping routines.....
2361  ***************************************************/
2362
2363 /*
2364  * Add a wired page to the kva.
2365  * Note: not SMP coherent.
2366  */
2367 PMAP_INLINE void 
2368 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
2369 {
2370         pt_entry_t *pte;
2371
2372         pte = vtopte(va);
2373         pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g);
2374 }
2375
2376 static __inline void
2377 pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
2378 {
2379         pt_entry_t *pte;
2380         int cache_bits;
2381
2382         pte = vtopte(va);
2383         cache_bits = pmap_cache_bits(kernel_pmap, mode, 0);
2384         pte_store(pte, pa | X86_PG_RW | X86_PG_V | pg_g | cache_bits);
2385 }
2386
2387 /*
2388  * Remove a page from the kernel pagetables.
2389  * Note: not SMP coherent.
2390  */
2391 PMAP_INLINE void
2392 pmap_kremove(vm_offset_t va)
2393 {
2394         pt_entry_t *pte;
2395
2396         pte = vtopte(va);
2397         pte_clear(pte);
2398 }
2399
2400 /*
2401  *      Used to map a range of physical addresses into kernel
2402  *      virtual address space.
2403  *
2404  *      The value passed in '*virt' is a suggested virtual address for
2405  *      the mapping. Architectures which can support a direct-mapped
2406  *      physical to virtual region can return the appropriate address
2407  *      within that region, leaving '*virt' unchanged. Other
2408  *      architectures should map the pages starting at '*virt' and
2409  *      update '*virt' with the first usable address after the mapped
2410  *      region.
2411  */
2412 vm_offset_t
2413 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
2414 {
2415         return PHYS_TO_DMAP(start);
2416 }
2417
2418
2419 /*
2420  * Add a list of wired pages to the kva
2421  * this routine is only used for temporary
2422  * kernel mappings that do not need to have
2423  * page modification or references recorded.
2424  * Note that old mappings are simply written
2425  * over.  The page *must* be wired.
2426  * Note: SMP coherent.  Uses a ranged shootdown IPI.
2427  */
2428 void
2429 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
2430 {
2431         pt_entry_t *endpte, oldpte, pa, *pte;
2432         vm_page_t m;
2433         int cache_bits;
2434
2435         oldpte = 0;
2436         pte = vtopte(sva);
2437         endpte = pte + count;
2438         while (pte < endpte) {
2439                 m = *ma++;
2440                 cache_bits = pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0);
2441                 pa = VM_PAGE_TO_PHYS(m) | cache_bits;
2442                 if ((*pte & (PG_FRAME | X86_PG_PTE_CACHE)) != pa) {
2443                         oldpte |= *pte;
2444                         pte_store(pte, pa | pg_g | pg_nx | X86_PG_RW | X86_PG_V);
2445                 }
2446                 pte++;
2447         }
2448         if (__predict_false((oldpte & X86_PG_V) != 0))
2449                 pmap_invalidate_range(kernel_pmap, sva, sva + count *
2450                     PAGE_SIZE);
2451 }
2452
2453 /*
2454  * This routine tears out page mappings from the
2455  * kernel -- it is meant only for temporary mappings.
2456  * Note: SMP coherent.  Uses a ranged shootdown IPI.
2457  */
2458 void
2459 pmap_qremove(vm_offset_t sva, int count)
2460 {
2461         vm_offset_t va;
2462
2463         va = sva;
2464         while (count-- > 0) {
2465                 KASSERT(va >= VM_MIN_KERNEL_ADDRESS, ("usermode va %lx", va));
2466                 pmap_kremove(va);
2467                 va += PAGE_SIZE;
2468         }
2469         pmap_invalidate_range(kernel_pmap, sva, va);
2470 }
2471
2472 /***************************************************
2473  * Page table page management routines.....
2474  ***************************************************/
2475 /*
2476  * Schedule the specified unused page table page to be freed.  Specifically,
2477  * add the page to the specified list of pages that will be released to the
2478  * physical memory manager after the TLB has been updated.
2479  */
2480 static __inline void
2481 pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
2482     boolean_t set_PG_ZERO)
2483 {
2484
2485         if (set_PG_ZERO)
2486                 m->flags |= PG_ZERO;
2487         else
2488                 m->flags &= ~PG_ZERO;
2489         SLIST_INSERT_HEAD(free, m, plinks.s.ss);
2490 }
2491         
2492 /*
2493  * Inserts the specified page table page into the specified pmap's collection
2494  * of idle page table pages.  Each of a pmap's page table pages is responsible
2495  * for mapping a distinct range of virtual addresses.  The pmap's collection is
2496  * ordered by this virtual address range.
2497  */
2498 static __inline int
2499 pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
2500 {
2501
2502         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2503         return (vm_radix_insert(&pmap->pm_root, mpte));
2504 }
2505
2506 /*
2507  * Removes the page table page mapping the specified virtual address from the
2508  * specified pmap's collection of idle page table pages, and returns it.
2509  * Otherwise, returns NULL if there is no page table page corresponding to the
2510  * specified virtual address.
2511  */
2512 static __inline vm_page_t
2513 pmap_remove_pt_page(pmap_t pmap, vm_offset_t va)
2514 {
2515
2516         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2517         return (vm_radix_remove(&pmap->pm_root, pmap_pde_pindex(va)));
2518 }
2519
2520 /*
2521  * Decrements a page table page's wire count, which is used to record the
2522  * number of valid page table entries within the page.  If the wire count
2523  * drops to zero, then the page table page is unmapped.  Returns TRUE if the
2524  * page table page was unmapped and FALSE otherwise.
2525  */
2526 static inline boolean_t
2527 pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2528 {
2529
2530         --m->wire_count;
2531         if (m->wire_count == 0) {
2532                 _pmap_unwire_ptp(pmap, va, m, free);
2533                 return (TRUE);
2534         } else
2535                 return (FALSE);
2536 }
2537
2538 static void
2539 _pmap_unwire_ptp(pmap_t pmap, vm_offset_t va, vm_page_t m, struct spglist *free)
2540 {
2541
2542         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2543         /*
2544          * unmap the page table page
2545          */
2546         if (m->pindex >= (NUPDE + NUPDPE)) {
2547                 /* PDP page */
2548                 pml4_entry_t *pml4;
2549                 pml4 = pmap_pml4e(pmap, va);
2550                 *pml4 = 0;
2551                 if (pmap->pm_pml4u != NULL && va <= VM_MAXUSER_ADDRESS) {
2552                         pml4 = &pmap->pm_pml4u[pmap_pml4e_index(va)];
2553                         *pml4 = 0;
2554                 }
2555         } else if (m->pindex >= NUPDE) {
2556                 /* PD page */
2557                 pdp_entry_t *pdp;
2558                 pdp = pmap_pdpe(pmap, va);
2559                 *pdp = 0;
2560         } else {
2561                 /* PTE page */
2562                 pd_entry_t *pd;
2563                 pd = pmap_pde(pmap, va);
2564                 *pd = 0;
2565         }
2566         pmap_resident_count_dec(pmap, 1);
2567         if (m->pindex < NUPDE) {
2568                 /* We just released a PT, unhold the matching PD */
2569                 vm_page_t pdpg;
2570
2571                 pdpg = PHYS_TO_VM_PAGE(*pmap_pdpe(pmap, va) & PG_FRAME);
2572                 pmap_unwire_ptp(pmap, va, pdpg, free);
2573         }
2574         if (m->pindex >= NUPDE && m->pindex < (NUPDE + NUPDPE)) {
2575                 /* We just released a PD, unhold the matching PDP */
2576                 vm_page_t pdppg;
2577
2578                 pdppg = PHYS_TO_VM_PAGE(*pmap_pml4e(pmap, va) & PG_FRAME);
2579                 pmap_unwire_ptp(pmap, va, pdppg, free);
2580         }
2581
2582         /* 
2583          * Put page on a list so that it is released after
2584          * *ALL* TLB shootdown is done
2585          */
2586         pmap_add_delayed_free_list(m, free, TRUE);
2587 }
2588
2589 /*
2590  * After removing a page table entry, this routine is used to
2591  * conditionally free the page, and manage the hold/wire counts.
2592  */
2593 static int
2594 pmap_unuse_pt(pmap_t pmap, vm_offset_t va, pd_entry_t ptepde,
2595     struct spglist *free)
2596 {
2597         vm_page_t mpte;
2598
2599         if (va >= VM_MAXUSER_ADDRESS)
2600                 return (0);
2601         KASSERT(ptepde != 0, ("pmap_unuse_pt: ptepde != 0"));
2602         mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
2603         return (pmap_unwire_ptp(pmap, va, mpte, free));
2604 }
2605
2606 void
2607 pmap_pinit0(pmap_t pmap)
2608 {
2609         int i;
2610
2611         PMAP_LOCK_INIT(pmap);
2612         pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(KPML4phys);
2613         pmap->pm_pml4u = NULL;
2614         pmap->pm_cr3 = KPML4phys;
2615         /* hack to keep pmap_pti_pcid_invalidate() alive */
2616         pmap->pm_ucr3 = PMAP_NO_CR3;
2617         pmap->pm_root.rt_root = 0;
2618         CPU_ZERO(&pmap->pm_active);
2619         TAILQ_INIT(&pmap->pm_pvchunk);
2620         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2621         pmap->pm_flags = pmap_flags;
2622         CPU_FOREACH(i) {
2623                 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2624                 pmap->pm_pcids[i].pm_gen = 0;
2625                 if (!pti) {
2626                         __pcpu[i].pc_kcr3 = PMAP_NO_CR3;
2627                         __pcpu[i].pc_ucr3 = PMAP_NO_CR3;
2628                 }
2629         }
2630         PCPU_SET(curpmap, kernel_pmap);
2631         pmap_activate(curthread);
2632         CPU_FILL(&kernel_pmap->pm_active);
2633 }
2634
2635 void
2636 pmap_pinit_pml4(vm_page_t pml4pg)
2637 {
2638         pml4_entry_t *pm_pml4;
2639         int i;
2640
2641         pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2642
2643         /* Wire in kernel global address entries. */
2644         for (i = 0; i < NKPML4E; i++) {
2645                 pm_pml4[KPML4BASE + i] = (KPDPphys + ptoa(i)) | X86_PG_RW |
2646                     X86_PG_V;
2647         }
2648         for (i = 0; i < ndmpdpphys; i++) {
2649                 pm_pml4[DMPML4I + i] = (DMPDPphys + ptoa(i)) | X86_PG_RW |
2650                     X86_PG_V;
2651         }
2652
2653         /* install self-referential address mapping entry(s) */
2654         pm_pml4[PML4PML4I] = VM_PAGE_TO_PHYS(pml4pg) | X86_PG_V | X86_PG_RW |
2655             X86_PG_A | X86_PG_M;
2656 }
2657
2658 static void
2659 pmap_pinit_pml4_pti(vm_page_t pml4pg)
2660 {
2661         pml4_entry_t *pm_pml4;
2662         int i;
2663
2664         pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4pg));
2665         for (i = 0; i < NPML4EPG; i++)
2666                 pm_pml4[i] = pti_pml4[i];
2667 }
2668
2669 /*
2670  * Initialize a preallocated and zeroed pmap structure,
2671  * such as one in a vmspace structure.
2672  */
2673 int
2674 pmap_pinit_type(pmap_t pmap, enum pmap_type pm_type, int flags)
2675 {
2676         vm_page_t pml4pg, pml4pgu;
2677         vm_paddr_t pml4phys;
2678         int i;
2679
2680         /*
2681          * allocate the page directory page
2682          */
2683         pml4pg = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
2684             VM_ALLOC_WIRED | VM_ALLOC_ZERO | VM_ALLOC_WAITOK);
2685
2686         pml4phys = VM_PAGE_TO_PHYS(pml4pg);
2687         pmap->pm_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(pml4phys);
2688         CPU_FOREACH(i) {
2689                 pmap->pm_pcids[i].pm_pcid = PMAP_PCID_NONE;
2690                 pmap->pm_pcids[i].pm_gen = 0;
2691         }
2692         pmap->pm_cr3 = PMAP_NO_CR3;     /* initialize to an invalid value */
2693         pmap->pm_ucr3 = PMAP_NO_CR3;
2694         pmap->pm_pml4u = NULL;
2695
2696         pmap->pm_type = pm_type;
2697         if ((pml4pg->flags & PG_ZERO) == 0)
2698                 pagezero(pmap->pm_pml4);
2699
2700         /*
2701          * Do not install the host kernel mappings in the nested page
2702          * tables. These mappings are meaningless in the guest physical
2703          * address space.
2704          * Install minimal kernel mappings in PTI case.
2705          */
2706         if (pm_type == PT_X86) {
2707                 pmap->pm_cr3 = pml4phys;
2708                 pmap_pinit_pml4(pml4pg);
2709                 if (pti) {
2710                         pml4pgu = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2711                             VM_ALLOC_NOOBJ | VM_ALLOC_WIRED | VM_ALLOC_WAITOK);
2712                         pmap->pm_pml4u = (pml4_entry_t *)PHYS_TO_DMAP(
2713                             VM_PAGE_TO_PHYS(pml4pgu));
2714                         pmap_pinit_pml4_pti(pml4pgu);
2715                         pmap->pm_ucr3 = VM_PAGE_TO_PHYS(pml4pgu);
2716                 }
2717         }
2718
2719         pmap->pm_root.rt_root = 0;
2720         CPU_ZERO(&pmap->pm_active);
2721         TAILQ_INIT(&pmap->pm_pvchunk);
2722         bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
2723         pmap->pm_flags = flags;
2724         pmap->pm_eptgen = 0;
2725
2726         return (1);
2727 }
2728
2729 int
2730 pmap_pinit(pmap_t pmap)
2731 {
2732
2733         return (pmap_pinit_type(pmap, PT_X86, pmap_flags));
2734 }
2735
2736 /*
2737  * This routine is called if the desired page table page does not exist.
2738  *
2739  * If page table page allocation fails, this routine may sleep before
2740  * returning NULL.  It sleeps only if a lock pointer was given.
2741  *
2742  * Note: If a page allocation fails at page table level two or three,
2743  * one or two pages may be held during the wait, only to be released
2744  * afterwards.  This conservative approach is easily argued to avoid
2745  * race conditions.
2746  */
2747 static vm_page_t
2748 _pmap_allocpte(pmap_t pmap, vm_pindex_t ptepindex, struct rwlock **lockp)
2749 {
2750         vm_page_t m, pdppg, pdpg;
2751         pt_entry_t PG_A, PG_M, PG_RW, PG_V;
2752
2753         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2754
2755         PG_A = pmap_accessed_bit(pmap);
2756         PG_M = pmap_modified_bit(pmap);
2757         PG_V = pmap_valid_bit(pmap);
2758         PG_RW = pmap_rw_bit(pmap);
2759
2760         /*
2761          * Allocate a page table page.
2762          */
2763         if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
2764             VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
2765                 if (lockp != NULL) {
2766                         RELEASE_PV_LIST_LOCK(lockp);
2767                         PMAP_UNLOCK(pmap);
2768                         PMAP_ASSERT_NOT_IN_DI();
2769                         vm_wait(NULL);
2770                         PMAP_LOCK(pmap);
2771                 }
2772
2773                 /*
2774                  * Indicate the need to retry.  While waiting, the page table
2775                  * page may have been allocated.
2776                  */
2777                 return (NULL);
2778         }
2779         if ((m->flags & PG_ZERO) == 0)
2780                 pmap_zero_page(m);
2781
2782         /*
2783          * Map the pagetable page into the process address space, if
2784          * it isn't already there.
2785          */
2786
2787         if (ptepindex >= (NUPDE + NUPDPE)) {
2788                 pml4_entry_t *pml4, *pml4u;
2789                 vm_pindex_t pml4index;
2790
2791                 /* Wire up a new PDPE page */
2792                 pml4index = ptepindex - (NUPDE + NUPDPE);
2793                 pml4 = &pmap->pm_pml4[pml4index];
2794                 *pml4 = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2795                 if (pmap->pm_pml4u != NULL && pml4index < NUPML4E) {
2796                         /*
2797                          * PTI: Make all user-space mappings in the
2798                          * kernel-mode page table no-execute so that
2799                          * we detect any programming errors that leave
2800                          * the kernel-mode page table active on return
2801                          * to user space.
2802                          */
2803                         if (pmap->pm_ucr3 != PMAP_NO_CR3)
2804                                 *pml4 |= pg_nx;
2805
2806                         pml4u = &pmap->pm_pml4u[pml4index];
2807                         *pml4u = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V |
2808                             PG_A | PG_M;
2809                 }
2810
2811         } else if (ptepindex >= NUPDE) {
2812                 vm_pindex_t pml4index;
2813                 vm_pindex_t pdpindex;
2814                 pml4_entry_t *pml4;
2815                 pdp_entry_t *pdp;
2816
2817                 /* Wire up a new PDE page */
2818                 pdpindex = ptepindex - NUPDE;
2819                 pml4index = pdpindex >> NPML4EPGSHIFT;
2820
2821                 pml4 = &pmap->pm_pml4[pml4index];
2822                 if ((*pml4 & PG_V) == 0) {
2823                         /* Have to allocate a new pdp, recurse */
2824                         if (_pmap_allocpte(pmap, NUPDE + NUPDPE + pml4index,
2825                             lockp) == NULL) {
2826                                 vm_page_unwire_noq(m);
2827                                 vm_page_free_zero(m);
2828                                 return (NULL);
2829                         }
2830                 } else {
2831                         /* Add reference to pdp page */
2832                         pdppg = PHYS_TO_VM_PAGE(*pml4 & PG_FRAME);
2833                         pdppg->wire_count++;
2834                 }
2835                 pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2836
2837                 /* Now find the pdp page */
2838                 pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2839                 *pdp = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2840
2841         } else {
2842                 vm_pindex_t pml4index;
2843                 vm_pindex_t pdpindex;
2844                 pml4_entry_t *pml4;
2845                 pdp_entry_t *pdp;
2846                 pd_entry_t *pd;
2847
2848                 /* Wire up a new PTE page */
2849                 pdpindex = ptepindex >> NPDPEPGSHIFT;
2850                 pml4index = pdpindex >> NPML4EPGSHIFT;
2851
2852                 /* First, find the pdp and check that its valid. */
2853                 pml4 = &pmap->pm_pml4[pml4index];
2854                 if ((*pml4 & PG_V) == 0) {
2855                         /* Have to allocate a new pd, recurse */
2856                         if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2857                             lockp) == NULL) {
2858                                 vm_page_unwire_noq(m);
2859                                 vm_page_free_zero(m);
2860                                 return (NULL);
2861                         }
2862                         pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2863                         pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2864                 } else {
2865                         pdp = (pdp_entry_t *)PHYS_TO_DMAP(*pml4 & PG_FRAME);
2866                         pdp = &pdp[pdpindex & ((1ul << NPDPEPGSHIFT) - 1)];
2867                         if ((*pdp & PG_V) == 0) {
2868                                 /* Have to allocate a new pd, recurse */
2869                                 if (_pmap_allocpte(pmap, NUPDE + pdpindex,
2870                                     lockp) == NULL) {
2871                                         vm_page_unwire_noq(m);
2872                                         vm_page_free_zero(m);
2873                                         return (NULL);
2874                                 }
2875                         } else {
2876                                 /* Add reference to the pd page */
2877                                 pdpg = PHYS_TO_VM_PAGE(*pdp & PG_FRAME);
2878                                 pdpg->wire_count++;
2879                         }
2880                 }
2881                 pd = (pd_entry_t *)PHYS_TO_DMAP(*pdp & PG_FRAME);
2882
2883                 /* Now we know where the page directory page is */
2884                 pd = &pd[ptepindex & ((1ul << NPDEPGSHIFT) - 1)];
2885                 *pd = VM_PAGE_TO_PHYS(m) | PG_U | PG_RW | PG_V | PG_A | PG_M;
2886         }
2887
2888         pmap_resident_count_inc(pmap, 1);
2889
2890         return (m);
2891 }
2892
2893 static vm_page_t
2894 pmap_allocpde(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2895 {
2896         vm_pindex_t pdpindex, ptepindex;
2897         pdp_entry_t *pdpe, PG_V;
2898         vm_page_t pdpg;
2899
2900         PG_V = pmap_valid_bit(pmap);
2901
2902 retry:
2903         pdpe = pmap_pdpe(pmap, va);
2904         if (pdpe != NULL && (*pdpe & PG_V) != 0) {
2905                 /* Add a reference to the pd page. */
2906                 pdpg = PHYS_TO_VM_PAGE(*pdpe & PG_FRAME);
2907                 pdpg->wire_count++;
2908         } else {
2909                 /* Allocate a pd page. */
2910                 ptepindex = pmap_pde_pindex(va);
2911                 pdpindex = ptepindex >> NPDPEPGSHIFT;
2912                 pdpg = _pmap_allocpte(pmap, NUPDE + pdpindex, lockp);
2913                 if (pdpg == NULL && lockp != NULL)
2914                         goto retry;
2915         }
2916         return (pdpg);
2917 }
2918
2919 static vm_page_t
2920 pmap_allocpte(pmap_t pmap, vm_offset_t va, struct rwlock **lockp)
2921 {
2922         vm_pindex_t ptepindex;
2923         pd_entry_t *pd, PG_V;
2924         vm_page_t m;
2925
2926         PG_V = pmap_valid_bit(pmap);
2927
2928         /*
2929          * Calculate pagetable page index
2930          */
2931         ptepindex = pmap_pde_pindex(va);
2932 retry:
2933         /*
2934          * Get the page directory entry
2935          */
2936         pd = pmap_pde(pmap, va);
2937
2938         /*
2939          * This supports switching from a 2MB page to a
2940          * normal 4K page.
2941          */
2942         if (pd != NULL && (*pd & (PG_PS | PG_V)) == (PG_PS | PG_V)) {
2943                 if (!pmap_demote_pde_locked(pmap, pd, va, lockp)) {
2944                         /*
2945                          * Invalidation of the 2MB page mapping may have caused
2946                          * the deallocation of the underlying PD page.
2947                          */
2948                         pd = NULL;
2949                 }
2950         }
2951
2952         /*
2953          * If the page table page is mapped, we just increment the
2954          * hold count, and activate it.
2955          */
2956         if (pd != NULL && (*pd & PG_V) != 0) {
2957                 m = PHYS_TO_VM_PAGE(*pd & PG_FRAME);
2958                 m->wire_count++;
2959         } else {
2960                 /*
2961                  * Here if the pte page isn't mapped, or if it has been
2962                  * deallocated.
2963                  */
2964                 m = _pmap_allocpte(pmap, ptepindex, lockp);
2965                 if (m == NULL && lockp != NULL)
2966                         goto retry;
2967         }
2968         return (m);
2969 }
2970
2971
2972 /***************************************************
2973  * Pmap allocation/deallocation routines.
2974  ***************************************************/
2975
2976 /*
2977  * Release any resources held by the given physical map.
2978  * Called when a pmap initialized by pmap_pinit is being released.
2979  * Should only be called if the map contains no valid mappings.
2980  */
2981 void
2982 pmap_release(pmap_t pmap)
2983 {
2984         vm_page_t m;
2985         int i;
2986
2987         KASSERT(pmap->pm_stats.resident_count == 0,
2988             ("pmap_release: pmap resident count %ld != 0",
2989             pmap->pm_stats.resident_count));
2990         KASSERT(vm_radix_is_empty(&pmap->pm_root),
2991             ("pmap_release: pmap has reserved page table page(s)"));
2992         KASSERT(CPU_EMPTY(&pmap->pm_active),
2993             ("releasing active pmap %p", pmap));
2994
2995         m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4));
2996
2997         for (i = 0; i < NKPML4E; i++)   /* KVA */
2998                 pmap->pm_pml4[KPML4BASE + i] = 0;
2999         for (i = 0; i < ndmpdpphys; i++)/* Direct Map */
3000                 pmap->pm_pml4[DMPML4I + i] = 0;
3001         pmap->pm_pml4[PML4PML4I] = 0;   /* Recursive Mapping */
3002
3003         vm_page_unwire_noq(m);
3004         vm_page_free_zero(m);
3005
3006         if (pmap->pm_pml4u != NULL) {
3007                 m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pmap->pm_pml4u));
3008                 vm_page_unwire_noq(m);
3009                 vm_page_free(m);
3010         }
3011 }
3012
3013 static int
3014 kvm_size(SYSCTL_HANDLER_ARGS)
3015 {
3016         unsigned long ksize = VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS;
3017
3018         return sysctl_handle_long(oidp, &ksize, 0, req);
3019 }
3020 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD, 
3021     0, 0, kvm_size, "LU", "Size of KVM");
3022
3023 static int
3024 kvm_free(SYSCTL_HANDLER_ARGS)
3025 {
3026         unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
3027
3028         return sysctl_handle_long(oidp, &kfree, 0, req);
3029 }
3030 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD, 
3031     0, 0, kvm_free, "LU", "Amount of KVM free");
3032
3033 /*
3034  * grow the number of kernel page table entries, if needed
3035  */
3036 void
3037 pmap_growkernel(vm_offset_t addr)
3038 {
3039         vm_paddr_t paddr;
3040         vm_page_t nkpg;
3041         pd_entry_t *pde, newpdir;
3042         pdp_entry_t *pdpe;
3043
3044         mtx_assert(&kernel_map->system_mtx, MA_OWNED);
3045
3046         /*
3047          * Return if "addr" is within the range of kernel page table pages
3048          * that were preallocated during pmap bootstrap.  Moreover, leave
3049          * "kernel_vm_end" and the kernel page table as they were.
3050          *
3051          * The correctness of this action is based on the following
3052          * argument: vm_map_insert() allocates contiguous ranges of the
3053          * kernel virtual address space.  It calls this function if a range
3054          * ends after "kernel_vm_end".  If the kernel is mapped between
3055          * "kernel_vm_end" and "addr", then the range cannot begin at
3056          * "kernel_vm_end".  In fact, its beginning address cannot be less
3057          * than the kernel.  Thus, there is no immediate need to allocate
3058          * any new kernel page table pages between "kernel_vm_end" and
3059          * "KERNBASE".
3060          */
3061         if (KERNBASE < addr && addr <= KERNBASE + nkpt * NBPDR)
3062                 return;
3063
3064         addr = roundup2(addr, NBPDR);
3065         if (addr - 1 >= kernel_map->max_offset)
3066                 addr = kernel_map->max_offset;
3067         while (kernel_vm_end < addr) {
3068                 pdpe = pmap_pdpe(kernel_pmap, kernel_vm_end);
3069                 if ((*pdpe & X86_PG_V) == 0) {
3070                         /* We need a new PDP entry */
3071                         nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDPSHIFT,
3072                             VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ |
3073                             VM_ALLOC_WIRED | VM_ALLOC_ZERO);
3074                         if (nkpg == NULL)
3075                                 panic("pmap_growkernel: no memory to grow kernel");
3076                         if ((nkpg->flags & PG_ZERO) == 0)
3077                                 pmap_zero_page(nkpg);
3078                         paddr = VM_PAGE_TO_PHYS(nkpg);
3079                         *pdpe = (pdp_entry_t)(paddr | X86_PG_V | X86_PG_RW |
3080                             X86_PG_A | X86_PG_M);
3081                         continue; /* try again */
3082                 }
3083                 pde = pmap_pdpe_to_pde(pdpe, kernel_vm_end);
3084                 if ((*pde & X86_PG_V) != 0) {
3085                         kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3086                         if (kernel_vm_end - 1 >= kernel_map->max_offset) {
3087                                 kernel_vm_end = kernel_map->max_offset;
3088                                 break;                       
3089                         }
3090                         continue;
3091                 }
3092
3093                 nkpg = vm_page_alloc(NULL, pmap_pde_pindex(kernel_vm_end),
3094                     VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
3095                     VM_ALLOC_ZERO);
3096                 if (nkpg == NULL)
3097                         panic("pmap_growkernel: no memory to grow kernel");
3098                 if ((nkpg->flags & PG_ZERO) == 0)
3099                         pmap_zero_page(nkpg);
3100                 paddr = VM_PAGE_TO_PHYS(nkpg);
3101                 newpdir = paddr | X86_PG_V | X86_PG_RW | X86_PG_A | X86_PG_M;
3102                 pde_store(pde, newpdir);
3103
3104                 kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
3105                 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
3106                         kernel_vm_end = kernel_map->max_offset;
3107                         break;                       
3108                 }
3109         }
3110 }
3111
3112
3113 /***************************************************
3114  * page management routines.
3115  ***************************************************/
3116
3117 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
3118 CTASSERT(_NPCM == 3);
3119 CTASSERT(_NPCPV == 168);
3120
3121 static __inline struct pv_chunk *
3122 pv_to_chunk(pv_entry_t pv)
3123 {
3124
3125         return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
3126 }
3127
3128 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
3129
3130 #define PC_FREE0        0xfffffffffffffffful
3131 #define PC_FREE1        0xfffffffffffffffful
3132 #define PC_FREE2        0x000000fffffffffful
3133
3134 static const uint64_t pc_freemask[_NPCM] = { PC_FREE0, PC_FREE1, PC_FREE2 };
3135
3136 #ifdef PV_STATS
3137 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
3138
3139 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
3140         "Current number of pv entry chunks");
3141 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
3142         "Current number of pv entry chunks allocated");
3143 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
3144         "Current number of pv entry chunks frees");
3145 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
3146         "Number of times tried to get a chunk page but failed.");
3147
3148 static long pv_entry_frees, pv_entry_allocs, pv_entry_count;
3149 static int pv_entry_spare;
3150
3151 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
3152         "Current number of pv entry frees");
3153 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
3154         "Current number of pv entry allocs");
3155 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
3156         "Current number of pv entries");
3157 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
3158         "Current number of spare pv entries");
3159 #endif
3160
3161 static void
3162 reclaim_pv_chunk_leave_pmap(pmap_t pmap, pmap_t locked_pmap, bool start_di)
3163 {
3164
3165         if (pmap == NULL)
3166                 return;
3167         pmap_invalidate_all(pmap);
3168         if (pmap != locked_pmap)
3169                 PMAP_UNLOCK(pmap);
3170         if (start_di)
3171                 pmap_delayed_invl_finished();
3172 }
3173
3174 /*
3175  * We are in a serious low memory condition.  Resort to
3176  * drastic measures to free some pages so we can allocate
3177  * another pv entry chunk.
3178  *
3179  * Returns NULL if PV entries were reclaimed from the specified pmap.
3180  *
3181  * We do not, however, unmap 2mpages because subsequent accesses will
3182  * allocate per-page pv entries until repromotion occurs, thereby
3183  * exacerbating the shortage of free pv entries.
3184  */
3185 static vm_page_t
3186 reclaim_pv_chunk(pmap_t locked_pmap, struct rwlock **lockp)
3187 {
3188         struct pv_chunk *pc, *pc_marker, *pc_marker_end;
3189         struct pv_chunk_header pc_marker_b, pc_marker_end_b;
3190         struct md_page *pvh;
3191         pd_entry_t *pde;
3192         pmap_t next_pmap, pmap;
3193         pt_entry_t *pte, tpte;
3194         pt_entry_t PG_G, PG_A, PG_M, PG_RW;
3195         pv_entry_t pv;
3196         vm_offset_t va;
3197         vm_page_t m, m_pc;
3198         struct spglist free;
3199         uint64_t inuse;
3200         int bit, field, freed;
3201         bool start_di;
3202         static int active_reclaims = 0;
3203
3204         PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
3205         KASSERT(lockp != NULL, ("reclaim_pv_chunk: lockp is NULL"));
3206         pmap = NULL;
3207         m_pc = NULL;
3208         PG_G = PG_A = PG_M = PG_RW = 0;
3209         SLIST_INIT(&free);
3210         bzero(&pc_marker_b, sizeof(pc_marker_b));
3211         bzero(&pc_marker_end_b, sizeof(pc_marker_end_b));
3212         pc_marker = (struct pv_chunk *)&pc_marker_b;
3213         pc_marker_end = (struct pv_chunk *)&pc_marker_end_b;
3214
3215         /*
3216          * A delayed invalidation block should already be active if
3217          * pmap_advise() or pmap_remove() called this function by way
3218          * of pmap_demote_pde_locked().
3219          */
3220         start_di = pmap_not_in_di();
3221
3222         mtx_lock(&pv_chunks_mutex);
3223         active_reclaims++;
3224         TAILQ_INSERT_HEAD(&pv_chunks, pc_marker, pc_lru);
3225         TAILQ_INSERT_TAIL(&pv_chunks, pc_marker_end, pc_lru);
3226         while ((pc = TAILQ_NEXT(pc_marker, pc_lru)) != pc_marker_end &&
3227             SLIST_EMPTY(&free)) {
3228                 next_pmap = pc->pc_pmap;
3229                 if (next_pmap == NULL) {
3230                         /*
3231                          * The next chunk is a marker.  However, it is
3232                          * not our marker, so active_reclaims must be
3233                          * > 1.  Consequently, the next_chunk code
3234                          * will not rotate the pv_chunks list.
3235                          */
3236                         goto next_chunk;
3237                 }
3238                 mtx_unlock(&pv_chunks_mutex);
3239
3240                 /*
3241                  * A pv_chunk can only be removed from the pc_lru list
3242                  * when both pc_chunks_mutex is owned and the
3243                  * corresponding pmap is locked.
3244                  */
3245                 if (pmap != next_pmap) {
3246                         reclaim_pv_chunk_leave_pmap(pmap, locked_pmap,
3247                             start_di);
3248                         pmap = next_pmap;
3249                         /* Avoid deadlock and lock recursion. */
3250                         if (pmap > locked_pmap) {
3251                                 RELEASE_PV_LIST_LOCK(lockp);
3252                                 PMAP_LOCK(pmap);
3253                                 if (start_di)
3254                                         pmap_delayed_invl_started();
3255                                 mtx_lock(&pv_chunks_mutex);
3256                                 continue;
3257                         } else if (pmap != locked_pmap) {
3258                                 if (PMAP_TRYLOCK(pmap)) {
3259                                         if (start_di)
3260                                                 pmap_delayed_invl_started();
3261                                         mtx_lock(&pv_chunks_mutex);
3262                                         continue;
3263                                 } else {
3264                                         pmap = NULL; /* pmap is not locked */
3265                                         mtx_lock(&pv_chunks_mutex);
3266                                         pc = TAILQ_NEXT(pc_marker, pc_lru);
3267                                         if (pc == NULL ||
3268                                             pc->pc_pmap != next_pmap)
3269                                                 continue;
3270                                         goto next_chunk;
3271                                 }
3272                         } else if (start_di)
3273                                 pmap_delayed_invl_started();
3274                         PG_G = pmap_global_bit(pmap);
3275                         PG_A = pmap_accessed_bit(pmap);
3276                         PG_M = pmap_modified_bit(pmap);
3277                         PG_RW = pmap_rw_bit(pmap);
3278                 }
3279
3280                 /*
3281                  * Destroy every non-wired, 4 KB page mapping in the chunk.
3282                  */
3283                 freed = 0;
3284                 for (field = 0; field < _NPCM; field++) {
3285                         for (inuse = ~pc->pc_map[field] & pc_freemask[field];
3286                             inuse != 0; inuse &= ~(1UL << bit)) {
3287                                 bit = bsfq(inuse);
3288                                 pv = &pc->pc_pventry[field * 64 + bit];
3289                                 va = pv->pv_va;
3290                                 pde = pmap_pde(pmap, va);
3291                                 if ((*pde & PG_PS) != 0)
3292                                         continue;
3293                                 pte = pmap_pde_to_pte(pde, va);
3294                                 if ((*pte & PG_W) != 0)
3295                                         continue;
3296                                 tpte = pte_load_clear(pte);
3297                                 if ((tpte & PG_G) != 0)
3298                                         pmap_invalidate_page(pmap, va);
3299                                 m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
3300                                 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3301                                         vm_page_dirty(m);
3302                                 if ((tpte & PG_A) != 0)
3303                                         vm_page_aflag_set(m, PGA_REFERENCED);
3304                                 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3305                                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3306                                 m->md.pv_gen++;
3307                                 if (TAILQ_EMPTY(&m->md.pv_list) &&
3308                                     (m->flags & PG_FICTITIOUS) == 0) {
3309                                         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3310                                         if (TAILQ_EMPTY(&pvh->pv_list)) {
3311                                                 vm_page_aflag_clear(m,
3312                                                     PGA_WRITEABLE);
3313                                         }
3314                                 }
3315                                 pmap_delayed_invl_page(m);
3316                                 pc->pc_map[field] |= 1UL << bit;
3317                                 pmap_unuse_pt(pmap, va, *pde, &free);
3318                                 freed++;
3319                         }
3320                 }
3321                 if (freed == 0) {
3322                         mtx_lock(&pv_chunks_mutex);
3323                         goto next_chunk;
3324                 }
3325                 /* Every freed mapping is for a 4 KB page. */
3326                 pmap_resident_count_dec(pmap, freed);
3327                 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
3328                 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
3329                 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
3330                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3331                 if (pc->pc_map[0] == PC_FREE0 && pc->pc_map[1] == PC_FREE1 &&
3332                     pc->pc_map[2] == PC_FREE2) {
3333                         PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3334                         PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3335                         PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3336                         /* Entire chunk is free; return it. */
3337                         m_pc = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3338                         dump_drop_page(m_pc->phys_addr);
3339                         mtx_lock(&pv_chunks_mutex);
3340                         TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3341                         break;
3342                 }
3343                 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3344                 mtx_lock(&pv_chunks_mutex);
3345                 /* One freed pv entry in locked_pmap is sufficient. */
3346                 if (pmap == locked_pmap)
3347                         break;
3348 next_chunk:
3349                 TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3350                 TAILQ_INSERT_AFTER(&pv_chunks, pc, pc_marker, pc_lru);
3351                 if (active_reclaims == 1 && pmap != NULL) {
3352                         /*
3353                          * Rotate the pv chunks list so that we do not
3354                          * scan the same pv chunks that could not be
3355                          * freed (because they contained a wired
3356                          * and/or superpage mapping) on every
3357                          * invocation of reclaim_pv_chunk().
3358                          */
3359                         while ((pc = TAILQ_FIRST(&pv_chunks)) != pc_marker) {
3360                                 MPASS(pc->pc_pmap != NULL);
3361                                 TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3362                                 TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3363                         }
3364                 }
3365         }
3366         TAILQ_REMOVE(&pv_chunks, pc_marker, pc_lru);
3367         TAILQ_REMOVE(&pv_chunks, pc_marker_end, pc_lru);
3368         active_reclaims--;
3369         mtx_unlock(&pv_chunks_mutex);
3370         reclaim_pv_chunk_leave_pmap(pmap, locked_pmap, start_di);
3371         if (m_pc == NULL && !SLIST_EMPTY(&free)) {
3372                 m_pc = SLIST_FIRST(&free);
3373                 SLIST_REMOVE_HEAD(&free, plinks.s.ss);
3374                 /* Recycle a freed page table page. */
3375                 m_pc->wire_count = 1;
3376         }
3377         vm_page_free_pages_toq(&free, true);
3378         return (m_pc);
3379 }
3380
3381 /*
3382  * free the pv_entry back to the free list
3383  */
3384 static void
3385 free_pv_entry(pmap_t pmap, pv_entry_t pv)
3386 {
3387         struct pv_chunk *pc;
3388         int idx, field, bit;
3389
3390         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3391         PV_STAT(atomic_add_long(&pv_entry_frees, 1));
3392         PV_STAT(atomic_add_int(&pv_entry_spare, 1));
3393         PV_STAT(atomic_subtract_long(&pv_entry_count, 1));
3394         pc = pv_to_chunk(pv);
3395         idx = pv - &pc->pc_pventry[0];
3396         field = idx / 64;
3397         bit = idx % 64;
3398         pc->pc_map[field] |= 1ul << bit;
3399         if (pc->pc_map[0] != PC_FREE0 || pc->pc_map[1] != PC_FREE1 ||
3400             pc->pc_map[2] != PC_FREE2) {
3401                 /* 98% of the time, pc is already at the head of the list. */
3402                 if (__predict_false(pc != TAILQ_FIRST(&pmap->pm_pvchunk))) {
3403                         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3404                         TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3405                 }
3406                 return;
3407         }
3408         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3409         free_pv_chunk(pc);
3410 }
3411
3412 static void
3413 free_pv_chunk(struct pv_chunk *pc)
3414 {
3415         vm_page_t m;
3416
3417         mtx_lock(&pv_chunks_mutex);
3418         TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
3419         mtx_unlock(&pv_chunks_mutex);
3420         PV_STAT(atomic_subtract_int(&pv_entry_spare, _NPCPV));
3421         PV_STAT(atomic_subtract_int(&pc_chunk_count, 1));
3422         PV_STAT(atomic_add_int(&pc_chunk_frees, 1));
3423         /* entire chunk is free, return it */
3424         m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((vm_offset_t)pc));
3425         dump_drop_page(m->phys_addr);
3426         vm_page_unwire(m, PQ_NONE);
3427         vm_page_free(m);
3428 }
3429
3430 /*
3431  * Returns a new PV entry, allocating a new PV chunk from the system when
3432  * needed.  If this PV chunk allocation fails and a PV list lock pointer was
3433  * given, a PV chunk is reclaimed from an arbitrary pmap.  Otherwise, NULL is
3434  * returned.
3435  *
3436  * The given PV list lock may be released.
3437  */
3438 static pv_entry_t
3439 get_pv_entry(pmap_t pmap, struct rwlock **lockp)
3440 {
3441         int bit, field;
3442         pv_entry_t pv;
3443         struct pv_chunk *pc;
3444         vm_page_t m;
3445
3446         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3447         PV_STAT(atomic_add_long(&pv_entry_allocs, 1));
3448 retry:
3449         pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3450         if (pc != NULL) {
3451                 for (field = 0; field < _NPCM; field++) {
3452                         if (pc->pc_map[field]) {
3453                                 bit = bsfq(pc->pc_map[field]);
3454                                 break;
3455                         }
3456                 }
3457                 if (field < _NPCM) {
3458                         pv = &pc->pc_pventry[field * 64 + bit];
3459                         pc->pc_map[field] &= ~(1ul << bit);
3460                         /* If this was the last item, move it to tail */
3461                         if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 &&
3462                             pc->pc_map[2] == 0) {
3463                                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3464                                 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc,
3465                                     pc_list);
3466                         }
3467                         PV_STAT(atomic_add_long(&pv_entry_count, 1));
3468                         PV_STAT(atomic_subtract_int(&pv_entry_spare, 1));
3469                         return (pv);
3470                 }
3471         }
3472         /* No free items, allocate another chunk */
3473         m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3474             VM_ALLOC_WIRED);
3475         if (m == NULL) {
3476                 if (lockp == NULL) {
3477                         PV_STAT(pc_chunk_tryfail++);
3478                         return (NULL);
3479                 }
3480                 m = reclaim_pv_chunk(pmap, lockp);
3481                 if (m == NULL)
3482                         goto retry;
3483         }
3484         PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3485         PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3486         dump_add_page(m->phys_addr);
3487         pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3488         pc->pc_pmap = pmap;
3489         pc->pc_map[0] = PC_FREE0 & ~1ul;        /* preallocated bit 0 */
3490         pc->pc_map[1] = PC_FREE1;
3491         pc->pc_map[2] = PC_FREE2;
3492         mtx_lock(&pv_chunks_mutex);
3493         TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
3494         mtx_unlock(&pv_chunks_mutex);
3495         pv = &pc->pc_pventry[0];
3496         TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3497         PV_STAT(atomic_add_long(&pv_entry_count, 1));
3498         PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV - 1));
3499         return (pv);
3500 }
3501
3502 /*
3503  * Returns the number of one bits within the given PV chunk map.
3504  *
3505  * The erratas for Intel processors state that "POPCNT Instruction May
3506  * Take Longer to Execute Than Expected".  It is believed that the
3507  * issue is the spurious dependency on the destination register.
3508  * Provide a hint to the register rename logic that the destination
3509  * value is overwritten, by clearing it, as suggested in the
3510  * optimization manual.  It should be cheap for unaffected processors
3511  * as well.
3512  *
3513  * Reference numbers for erratas are
3514  * 4th Gen Core: HSD146
3515  * 5th Gen Core: BDM85
3516  * 6th Gen Core: SKL029
3517  */
3518 static int
3519 popcnt_pc_map_pq(uint64_t *map)
3520 {
3521         u_long result, tmp;
3522
3523         __asm __volatile("xorl %k0,%k0;popcntq %2,%0;"
3524             "xorl %k1,%k1;popcntq %3,%1;addl %k1,%k0;"
3525             "xorl %k1,%k1;popcntq %4,%1;addl %k1,%k0"
3526             : "=&r" (result), "=&r" (tmp)
3527             : "m" (map[0]), "m" (map[1]), "m" (map[2]));
3528         return (result);
3529 }
3530
3531 /*
3532  * Ensure that the number of spare PV entries in the specified pmap meets or
3533  * exceeds the given count, "needed".
3534  *
3535  * The given PV list lock may be released.
3536  */
3537 static void
3538 reserve_pv_entries(pmap_t pmap, int needed, struct rwlock **lockp)
3539 {
3540         struct pch new_tail;
3541         struct pv_chunk *pc;
3542         vm_page_t m;
3543         int avail, free;
3544         bool reclaimed;
3545
3546         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3547         KASSERT(lockp != NULL, ("reserve_pv_entries: lockp is NULL"));
3548
3549         /*
3550          * Newly allocated PV chunks must be stored in a private list until
3551          * the required number of PV chunks have been allocated.  Otherwise,
3552          * reclaim_pv_chunk() could recycle one of these chunks.  In
3553          * contrast, these chunks must be added to the pmap upon allocation.
3554          */
3555         TAILQ_INIT(&new_tail);
3556 retry:
3557         avail = 0;
3558         TAILQ_FOREACH(pc, &pmap->pm_pvchunk, pc_list) {
3559 #ifndef __POPCNT__
3560                 if ((cpu_feature2 & CPUID2_POPCNT) == 0)
3561                         bit_count((bitstr_t *)pc->pc_map, 0,
3562                             sizeof(pc->pc_map) * NBBY, &free);
3563                 else
3564 #endif
3565                 free = popcnt_pc_map_pq(pc->pc_map);
3566                 if (free == 0)
3567                         break;
3568                 avail += free;
3569                 if (avail >= needed)
3570                         break;
3571         }
3572         for (reclaimed = false; avail < needed; avail += _NPCPV) {
3573                 m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
3574                     VM_ALLOC_WIRED);
3575                 if (m == NULL) {
3576                         m = reclaim_pv_chunk(pmap, lockp);
3577                         if (m == NULL)
3578                                 goto retry;
3579                         reclaimed = true;
3580                 }
3581                 PV_STAT(atomic_add_int(&pc_chunk_count, 1));
3582                 PV_STAT(atomic_add_int(&pc_chunk_allocs, 1));
3583                 dump_add_page(m->phys_addr);
3584                 pc = (void *)PHYS_TO_DMAP(m->phys_addr);
3585                 pc->pc_pmap = pmap;
3586                 pc->pc_map[0] = PC_FREE0;
3587                 pc->pc_map[1] = PC_FREE1;
3588                 pc->pc_map[2] = PC_FREE2;
3589                 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
3590                 TAILQ_INSERT_TAIL(&new_tail, pc, pc_lru);
3591                 PV_STAT(atomic_add_int(&pv_entry_spare, _NPCPV));
3592
3593                 /*
3594                  * The reclaim might have freed a chunk from the current pmap.
3595                  * If that chunk contained available entries, we need to
3596                  * re-count the number of available entries.
3597                  */
3598                 if (reclaimed)
3599                         goto retry;
3600         }
3601         if (!TAILQ_EMPTY(&new_tail)) {
3602                 mtx_lock(&pv_chunks_mutex);
3603                 TAILQ_CONCAT(&pv_chunks, &new_tail, pc_lru);
3604                 mtx_unlock(&pv_chunks_mutex);
3605         }
3606 }
3607
3608 /*
3609  * First find and then remove the pv entry for the specified pmap and virtual
3610  * address from the specified pv list.  Returns the pv entry if found and NULL
3611  * otherwise.  This operation can be performed on pv lists for either 4KB or
3612  * 2MB page mappings.
3613  */
3614 static __inline pv_entry_t
3615 pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3616 {
3617         pv_entry_t pv;
3618
3619         TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
3620                 if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
3621                         TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
3622                         pvh->pv_gen++;
3623                         break;
3624                 }
3625         }
3626         return (pv);
3627 }
3628
3629 /*
3630  * After demotion from a 2MB page mapping to 512 4KB page mappings,
3631  * destroy the pv entry for the 2MB page mapping and reinstantiate the pv
3632  * entries for each of the 4KB page mappings.
3633  */
3634 static void
3635 pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3636     struct rwlock **lockp)
3637 {
3638         struct md_page *pvh;
3639         struct pv_chunk *pc;
3640         pv_entry_t pv;
3641         vm_offset_t va_last;
3642         vm_page_t m;
3643         int bit, field;
3644
3645         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3646         KASSERT((pa & PDRMASK) == 0,
3647             ("pmap_pv_demote_pde: pa is not 2mpage aligned"));
3648         CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3649
3650         /*
3651          * Transfer the 2mpage's pv entry for this mapping to the first
3652          * page's pv list.  Once this transfer begins, the pv list lock
3653          * must not be released until the last pv entry is reinstantiated.
3654          */
3655         pvh = pa_to_pvh(pa);
3656         va = trunc_2mpage(va);
3657         pv = pmap_pvh_remove(pvh, pmap, va);
3658         KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
3659         m = PHYS_TO_VM_PAGE(pa);
3660         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3661         m->md.pv_gen++;
3662         /* Instantiate the remaining NPTEPG - 1 pv entries. */
3663         PV_STAT(atomic_add_long(&pv_entry_allocs, NPTEPG - 1));
3664         va_last = va + NBPDR - PAGE_SIZE;
3665         for (;;) {
3666                 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
3667                 KASSERT(pc->pc_map[0] != 0 || pc->pc_map[1] != 0 ||
3668                     pc->pc_map[2] != 0, ("pmap_pv_demote_pde: missing spare"));
3669                 for (field = 0; field < _NPCM; field++) {
3670                         while (pc->pc_map[field]) {
3671                                 bit = bsfq(pc->pc_map[field]);
3672                                 pc->pc_map[field] &= ~(1ul << bit);
3673                                 pv = &pc->pc_pventry[field * 64 + bit];
3674                                 va += PAGE_SIZE;
3675                                 pv->pv_va = va;
3676                                 m++;
3677                                 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3678                             ("pmap_pv_demote_pde: page %p is not managed", m));
3679                                 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3680                                 m->md.pv_gen++;
3681                                 if (va == va_last)
3682                                         goto out;
3683                         }
3684                 }
3685                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3686                 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3687         }
3688 out:
3689         if (pc->pc_map[0] == 0 && pc->pc_map[1] == 0 && pc->pc_map[2] == 0) {
3690                 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3691                 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
3692         }
3693         PV_STAT(atomic_add_long(&pv_entry_count, NPTEPG - 1));
3694         PV_STAT(atomic_subtract_int(&pv_entry_spare, NPTEPG - 1));
3695 }
3696
3697 #if VM_NRESERVLEVEL > 0
3698 /*
3699  * After promotion from 512 4KB page mappings to a single 2MB page mapping,
3700  * replace the many pv entries for the 4KB page mappings by a single pv entry
3701  * for the 2MB page mapping.
3702  */
3703 static void
3704 pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa,
3705     struct rwlock **lockp)
3706 {
3707         struct md_page *pvh;
3708         pv_entry_t pv;
3709         vm_offset_t va_last;
3710         vm_page_t m;
3711
3712         KASSERT((pa & PDRMASK) == 0,
3713             ("pmap_pv_promote_pde: pa is not 2mpage aligned"));
3714         CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3715
3716         /*
3717          * Transfer the first page's pv entry for this mapping to the 2mpage's
3718          * pv list.  Aside from avoiding the cost of a call to get_pv_entry(),
3719          * a transfer avoids the possibility that get_pv_entry() calls
3720          * reclaim_pv_chunk() and that reclaim_pv_chunk() removes one of the
3721          * mappings that is being promoted.
3722          */
3723         m = PHYS_TO_VM_PAGE(pa);
3724         va = trunc_2mpage(va);
3725         pv = pmap_pvh_remove(&m->md, pmap, va);
3726         KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
3727         pvh = pa_to_pvh(pa);
3728         TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3729         pvh->pv_gen++;
3730         /* Free the remaining NPTEPG - 1 pv entries. */
3731         va_last = va + NBPDR - PAGE_SIZE;
3732         do {
3733                 m++;
3734                 va += PAGE_SIZE;
3735                 pmap_pvh_free(&m->md, pmap, va);
3736         } while (va < va_last);
3737 }
3738 #endif /* VM_NRESERVLEVEL > 0 */
3739
3740 /*
3741  * First find and then destroy the pv entry for the specified pmap and virtual
3742  * address.  This operation can be performed on pv lists for either 4KB or 2MB
3743  * page mappings.
3744  */
3745 static void
3746 pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
3747 {
3748         pv_entry_t pv;
3749
3750         pv = pmap_pvh_remove(pvh, pmap, va);
3751         KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
3752         free_pv_entry(pmap, pv);
3753 }
3754
3755 /*
3756  * Conditionally create the PV entry for a 4KB page mapping if the required
3757  * memory can be allocated without resorting to reclamation.
3758  */
3759 static boolean_t
3760 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m,
3761     struct rwlock **lockp)
3762 {
3763         pv_entry_t pv;
3764
3765         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3766         /* Pass NULL instead of the lock pointer to disable reclamation. */
3767         if ((pv = get_pv_entry(pmap, NULL)) != NULL) {
3768                 pv->pv_va = va;
3769                 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
3770                 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3771                 m->md.pv_gen++;
3772                 return (TRUE);
3773         } else
3774                 return (FALSE);
3775 }
3776
3777 /*
3778  * Create the PV entry for a 2MB page mapping.  Always returns true unless the
3779  * flag PMAP_ENTER_NORECLAIM is specified.  If that flag is specified, returns
3780  * false if the PV entry cannot be allocated without resorting to reclamation.
3781  */
3782 static bool
3783 pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, pd_entry_t pde, u_int flags,
3784     struct rwlock **lockp)
3785 {
3786         struct md_page *pvh;
3787         pv_entry_t pv;
3788         vm_paddr_t pa;
3789
3790         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3791         /* Pass NULL instead of the lock pointer to disable reclamation. */
3792         if ((pv = get_pv_entry(pmap, (flags & PMAP_ENTER_NORECLAIM) != 0 ?
3793             NULL : lockp)) == NULL)
3794                 return (false);
3795         pv->pv_va = va;
3796         pa = pde & PG_PS_FRAME;
3797         CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, pa);
3798         pvh = pa_to_pvh(pa);
3799         TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
3800         pvh->pv_gen++;
3801         return (true);
3802 }
3803
3804 /*
3805  * Fills a page table page with mappings to consecutive physical pages.
3806  */
3807 static void
3808 pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
3809 {
3810         pt_entry_t *pte;
3811
3812         for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
3813                 *pte = newpte;
3814                 newpte += PAGE_SIZE;
3815         }
3816 }
3817
3818 /*
3819  * Tries to demote a 2MB page mapping.  If demotion fails, the 2MB page
3820  * mapping is invalidated.
3821  */
3822 static boolean_t
3823 pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3824 {
3825         struct rwlock *lock;
3826         boolean_t rv;
3827
3828         lock = NULL;
3829         rv = pmap_demote_pde_locked(pmap, pde, va, &lock);
3830         if (lock != NULL)
3831                 rw_wunlock(lock);
3832         return (rv);
3833 }
3834
3835 static boolean_t
3836 pmap_demote_pde_locked(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
3837     struct rwlock **lockp)
3838 {
3839         pd_entry_t newpde, oldpde;
3840         pt_entry_t *firstpte, newpte;
3841         pt_entry_t PG_A, PG_G, PG_M, PG_RW, PG_V;
3842         vm_paddr_t mptepa;
3843         vm_page_t mpte;
3844         struct spglist free;
3845         vm_offset_t sva;
3846         int PG_PTE_CACHE;
3847
3848         PG_G = pmap_global_bit(pmap);
3849         PG_A = pmap_accessed_bit(pmap);
3850         PG_M = pmap_modified_bit(pmap);
3851         PG_RW = pmap_rw_bit(pmap);
3852         PG_V = pmap_valid_bit(pmap);
3853         PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
3854
3855         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3856         oldpde = *pde;
3857         KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
3858             ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
3859         if ((oldpde & PG_A) == 0 || (mpte = pmap_remove_pt_page(pmap, va)) ==
3860             NULL) {
3861                 KASSERT((oldpde & PG_W) == 0,
3862                     ("pmap_demote_pde: page table page for a wired mapping"
3863                     " is missing"));
3864
3865                 /*
3866                  * Invalidate the 2MB page mapping and return "failure" if the
3867                  * mapping was never accessed or the allocation of the new
3868                  * page table page fails.  If the 2MB page mapping belongs to
3869                  * the direct map region of the kernel's address space, then
3870                  * the page allocation request specifies the highest possible
3871                  * priority (VM_ALLOC_INTERRUPT).  Otherwise, the priority is
3872                  * normal.  Page table pages are preallocated for every other
3873                  * part of the kernel address space, so the direct map region
3874                  * is the only part of the kernel address space that must be
3875                  * handled here.
3876                  */
3877                 if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
3878                     pmap_pde_pindex(va), (va >= DMAP_MIN_ADDRESS && va <
3879                     DMAP_MAX_ADDRESS ? VM_ALLOC_INTERRUPT : VM_ALLOC_NORMAL) |
3880                     VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
3881                         SLIST_INIT(&free);
3882                         sva = trunc_2mpage(va);
3883                         pmap_remove_pde(pmap, pde, sva, &free, lockp);
3884                         if ((oldpde & PG_G) == 0)
3885                                 pmap_invalidate_pde_page(pmap, sva, oldpde);
3886                         vm_page_free_pages_toq(&free, true);
3887                         CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#lx"
3888                             " in pmap %p", va, pmap);
3889                         return (FALSE);
3890                 }
3891                 if (va < VM_MAXUSER_ADDRESS)
3892                         pmap_resident_count_inc(pmap, 1);
3893         }
3894         mptepa = VM_PAGE_TO_PHYS(mpte);
3895         firstpte = (pt_entry_t *)PHYS_TO_DMAP(mptepa);
3896         newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
3897         KASSERT((oldpde & PG_A) != 0,
3898             ("pmap_demote_pde: oldpde is missing PG_A"));
3899         KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
3900             ("pmap_demote_pde: oldpde is missing PG_M"));
3901         newpte = oldpde & ~PG_PS;
3902         newpte = pmap_swap_pat(pmap, newpte);
3903
3904         /*
3905          * If the page table page is new, initialize it.
3906          */
3907         if (mpte->wire_count == 1) {
3908                 mpte->wire_count = NPTEPG;
3909                 pmap_fill_ptp(firstpte, newpte);
3910         }
3911         KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
3912             ("pmap_demote_pde: firstpte and newpte map different physical"
3913             " addresses"));
3914
3915         /*
3916          * If the mapping has changed attributes, update the page table
3917          * entries.
3918          */
3919         if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
3920                 pmap_fill_ptp(firstpte, newpte);
3921
3922         /*
3923          * The spare PV entries must be reserved prior to demoting the
3924          * mapping, that is, prior to changing the PDE.  Otherwise, the state
3925          * of the PDE and the PV lists will be inconsistent, which can result
3926          * in reclaim_pv_chunk() attempting to remove a PV entry from the
3927          * wrong PV list and pmap_pv_demote_pde() failing to find the expected
3928          * PV entry for the 2MB page mapping that is being demoted.
3929          */
3930         if ((oldpde & PG_MANAGED) != 0)
3931                 reserve_pv_entries(pmap, NPTEPG - 1, lockp);
3932
3933         /*
3934          * Demote the mapping.  This pmap is locked.  The old PDE has
3935          * PG_A set.  If the old PDE has PG_RW set, it also has PG_M
3936          * set.  Thus, there is no danger of a race with another
3937          * processor changing the setting of PG_A and/or PG_M between
3938          * the read above and the store below. 
3939          */
3940         if (workaround_erratum383)
3941                 pmap_update_pde(pmap, va, pde, newpde);
3942         else
3943                 pde_store(pde, newpde);
3944
3945         /*
3946          * Invalidate a stale recursive mapping of the page table page.
3947          */
3948         if (va >= VM_MAXUSER_ADDRESS)
3949                 pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3950
3951         /*
3952          * Demote the PV entry.
3953          */
3954         if ((oldpde & PG_MANAGED) != 0)
3955                 pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME, lockp);
3956
3957         atomic_add_long(&pmap_pde_demotions, 1);
3958         CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#lx"
3959             " in pmap %p", va, pmap);
3960         return (TRUE);
3961 }
3962
3963 /*
3964  * pmap_remove_kernel_pde: Remove a kernel superpage mapping.
3965  */
3966 static void
3967 pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3968 {
3969         pd_entry_t newpde;
3970         vm_paddr_t mptepa;
3971         vm_page_t mpte;
3972
3973         KASSERT(pmap == kernel_pmap, ("pmap %p is not kernel_pmap", pmap));
3974         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3975         mpte = pmap_remove_pt_page(pmap, va);
3976         if (mpte == NULL)
3977                 panic("pmap_remove_kernel_pde: Missing pt page.");
3978
3979         mptepa = VM_PAGE_TO_PHYS(mpte);
3980         newpde = mptepa | X86_PG_M | X86_PG_A | X86_PG_RW | X86_PG_V;
3981
3982         /*
3983          * Initialize the page table page.
3984          */
3985         pagezero((void *)PHYS_TO_DMAP(mptepa));
3986
3987         /*
3988          * Demote the mapping.
3989          */
3990         if (workaround_erratum383)
3991                 pmap_update_pde(pmap, va, pde, newpde);
3992         else
3993                 pde_store(pde, newpde);
3994
3995         /*
3996          * Invalidate a stale recursive mapping of the page table page.
3997          */
3998         pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
3999 }
4000
4001 /*
4002  * pmap_remove_pde: do the things to unmap a superpage in a process
4003  */
4004 static int
4005 pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
4006     struct spglist *free, struct rwlock **lockp)
4007 {
4008         struct md_page *pvh;
4009         pd_entry_t oldpde;
4010         vm_offset_t eva, va;
4011         vm_page_t m, mpte;
4012         pt_entry_t PG_G, PG_A, PG_M, PG_RW;
4013
4014         PG_G = pmap_global_bit(pmap);
4015         PG_A = pmap_accessed_bit(pmap);
4016         PG_M = pmap_modified_bit(pmap);
4017         PG_RW = pmap_rw_bit(pmap);
4018
4019         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4020         KASSERT((sva & PDRMASK) == 0,
4021             ("pmap_remove_pde: sva is not 2mpage aligned"));
4022         oldpde = pte_load_clear(pdq);
4023         if (oldpde & PG_W)
4024                 pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
4025         if ((oldpde & PG_G) != 0)
4026                 pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4027         pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
4028         if (oldpde & PG_MANAGED) {
4029                 CHANGE_PV_LIST_LOCK_TO_PHYS(lockp, oldpde & PG_PS_FRAME);
4030                 pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
4031                 pmap_pvh_free(pvh, pmap, sva);
4032                 eva = sva + NBPDR;
4033                 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4034                     va < eva; va += PAGE_SIZE, m++) {
4035                         if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
4036                                 vm_page_dirty(m);
4037                         if (oldpde & PG_A)
4038                                 vm_page_aflag_set(m, PGA_REFERENCED);
4039                         if (TAILQ_EMPTY(&m->md.pv_list) &&
4040                             TAILQ_EMPTY(&pvh->pv_list))
4041                                 vm_page_aflag_clear(m, PGA_WRITEABLE);
4042                         pmap_delayed_invl_page(m);
4043                 }
4044         }
4045         if (pmap == kernel_pmap) {
4046                 pmap_remove_kernel_pde(pmap, pdq, sva);
4047         } else {
4048                 mpte = pmap_remove_pt_page(pmap, sva);
4049                 if (mpte != NULL) {
4050                         pmap_resident_count_dec(pmap, 1);
4051                         KASSERT(mpte->wire_count == NPTEPG,
4052                             ("pmap_remove_pde: pte page wire count error"));
4053                         mpte->wire_count = 0;
4054                         pmap_add_delayed_free_list(mpte, free, FALSE);
4055                 }
4056         }
4057         return (pmap_unuse_pt(pmap, sva, *pmap_pdpe(pmap, sva), free));
4058 }
4059
4060 /*
4061  * pmap_remove_pte: do the things to unmap a page in a process
4062  */
4063 static int
4064 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va, 
4065     pd_entry_t ptepde, struct spglist *free, struct rwlock **lockp)
4066 {
4067         struct md_page *pvh;
4068         pt_entry_t oldpte, PG_A, PG_M, PG_RW;
4069         vm_page_t m;
4070
4071         PG_A = pmap_accessed_bit(pmap);
4072         PG_M = pmap_modified_bit(pmap);
4073         PG_RW = pmap_rw_bit(pmap);
4074
4075         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4076         oldpte = pte_load_clear(ptq);
4077         if (oldpte & PG_W)
4078                 pmap->pm_stats.wired_count -= 1;
4079         pmap_resident_count_dec(pmap, 1);
4080         if (oldpte & PG_MANAGED) {
4081                 m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
4082                 if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4083                         vm_page_dirty(m);
4084                 if (oldpte & PG_A)
4085                         vm_page_aflag_set(m, PGA_REFERENCED);
4086                 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(lockp, m);
4087                 pmap_pvh_free(&m->md, pmap, va);
4088                 if (TAILQ_EMPTY(&m->md.pv_list) &&
4089                     (m->flags & PG_FICTITIOUS) == 0) {
4090                         pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4091                         if (TAILQ_EMPTY(&pvh->pv_list))
4092                                 vm_page_aflag_clear(m, PGA_WRITEABLE);
4093                 }
4094                 pmap_delayed_invl_page(m);
4095         }
4096         return (pmap_unuse_pt(pmap, va, ptepde, free));
4097 }
4098
4099 /*
4100  * Remove a single page from a process address space
4101  */
4102 static void
4103 pmap_remove_page(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
4104     struct spglist *free)
4105 {
4106         struct rwlock *lock;
4107         pt_entry_t *pte, PG_V;
4108
4109         PG_V = pmap_valid_bit(pmap);
4110         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4111         if ((*pde & PG_V) == 0)
4112                 return;
4113         pte = pmap_pde_to_pte(pde, va);
4114         if ((*pte & PG_V) == 0)
4115                 return;
4116         lock = NULL;
4117         pmap_remove_pte(pmap, pte, va, *pde, free, &lock);
4118         if (lock != NULL)
4119                 rw_wunlock(lock);
4120         pmap_invalidate_page(pmap, va);
4121 }
4122
4123 /*
4124  * Removes the specified range of addresses from the page table page.
4125  */
4126 static bool
4127 pmap_remove_ptes(pmap_t pmap, vm_offset_t sva, vm_offset_t eva,
4128     pd_entry_t *pde, struct spglist *free, struct rwlock **lockp)
4129 {
4130         pt_entry_t PG_G, *pte;
4131         vm_offset_t va;
4132         bool anyvalid;
4133
4134         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4135         PG_G = pmap_global_bit(pmap);
4136         anyvalid = false;
4137         va = eva;
4138         for (pte = pmap_pde_to_pte(pde, sva); sva != eva; pte++,
4139             sva += PAGE_SIZE) {
4140                 if (*pte == 0) {
4141                         if (va != eva) {
4142                                 pmap_invalidate_range(pmap, va, sva);
4143                                 va = eva;
4144                         }
4145                         continue;
4146                 }
4147                 if ((*pte & PG_G) == 0)
4148                         anyvalid = true;
4149                 else if (va == eva)
4150                         va = sva;
4151                 if (pmap_remove_pte(pmap, pte, sva, *pde, free, lockp)) {
4152                         sva += PAGE_SIZE;
4153                         break;
4154                 }
4155         }
4156         if (va != eva)
4157                 pmap_invalidate_range(pmap, va, sva);
4158         return (anyvalid);
4159 }
4160
4161 /*
4162  *      Remove the given range of addresses from the specified map.
4163  *
4164  *      It is assumed that the start and end are properly
4165  *      rounded to the page size.
4166  */
4167 void
4168 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
4169 {
4170         struct rwlock *lock;
4171         vm_offset_t va_next;
4172         pml4_entry_t *pml4e;
4173         pdp_entry_t *pdpe;
4174         pd_entry_t ptpaddr, *pde;
4175         pt_entry_t PG_G, PG_V;
4176         struct spglist free;
4177         int anyvalid;
4178
4179         PG_G = pmap_global_bit(pmap);
4180         PG_V = pmap_valid_bit(pmap);
4181
4182         /*
4183          * Perform an unsynchronized read.  This is, however, safe.
4184          */
4185         if (pmap->pm_stats.resident_count == 0)
4186                 return;
4187
4188         anyvalid = 0;
4189         SLIST_INIT(&free);
4190
4191         pmap_delayed_invl_started();
4192         PMAP_LOCK(pmap);
4193
4194         /*
4195          * special handling of removing one page.  a very
4196          * common operation and easy to short circuit some
4197          * code.
4198          */
4199         if (sva + PAGE_SIZE == eva) {
4200                 pde = pmap_pde(pmap, sva);
4201                 if (pde && (*pde & PG_PS) == 0) {
4202                         pmap_remove_page(pmap, sva, pde, &free);
4203                         goto out;
4204                 }
4205         }
4206
4207         lock = NULL;
4208         for (; sva < eva; sva = va_next) {
4209
4210                 if (pmap->pm_stats.resident_count == 0)
4211                         break;
4212
4213                 pml4e = pmap_pml4e(pmap, sva);
4214                 if ((*pml4e & PG_V) == 0) {
4215                         va_next = (sva + NBPML4) & ~PML4MASK;
4216                         if (va_next < sva)
4217                                 va_next = eva;
4218                         continue;
4219                 }
4220
4221                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4222                 if ((*pdpe & PG_V) == 0) {
4223                         va_next = (sva + NBPDP) & ~PDPMASK;
4224                         if (va_next < sva)
4225                                 va_next = eva;
4226                         continue;
4227                 }
4228
4229                 /*
4230                  * Calculate index for next page table.
4231                  */
4232                 va_next = (sva + NBPDR) & ~PDRMASK;
4233                 if (va_next < sva)
4234                         va_next = eva;
4235
4236                 pde = pmap_pdpe_to_pde(pdpe, sva);
4237                 ptpaddr = *pde;
4238
4239                 /*
4240                  * Weed out invalid mappings.
4241                  */
4242                 if (ptpaddr == 0)
4243                         continue;
4244
4245                 /*
4246                  * Check for large page.
4247                  */
4248                 if ((ptpaddr & PG_PS) != 0) {
4249                         /*
4250                          * Are we removing the entire large page?  If not,
4251                          * demote the mapping and fall through.
4252                          */
4253                         if (sva + NBPDR == va_next && eva >= va_next) {
4254                                 /*
4255                                  * The TLB entry for a PG_G mapping is
4256                                  * invalidated by pmap_remove_pde().
4257                                  */
4258                                 if ((ptpaddr & PG_G) == 0)
4259                                         anyvalid = 1;
4260                                 pmap_remove_pde(pmap, pde, sva, &free, &lock);
4261                                 continue;
4262                         } else if (!pmap_demote_pde_locked(pmap, pde, sva,
4263                             &lock)) {
4264                                 /* The large page mapping was destroyed. */
4265                                 continue;
4266                         } else
4267                                 ptpaddr = *pde;
4268                 }
4269
4270                 /*
4271                  * Limit our scan to either the end of the va represented
4272                  * by the current page table page, or to the end of the
4273                  * range being removed.
4274                  */
4275                 if (va_next > eva)
4276                         va_next = eva;
4277
4278                 if (pmap_remove_ptes(pmap, sva, va_next, pde, &free, &lock))
4279                         anyvalid = 1;
4280         }
4281         if (lock != NULL)
4282                 rw_wunlock(lock);
4283 out:
4284         if (anyvalid)
4285                 pmap_invalidate_all(pmap);
4286         PMAP_UNLOCK(pmap);
4287         pmap_delayed_invl_finished();
4288         vm_page_free_pages_toq(&free, true);
4289 }
4290
4291 /*
4292  *      Routine:        pmap_remove_all
4293  *      Function:
4294  *              Removes this physical page from
4295  *              all physical maps in which it resides.
4296  *              Reflects back modify bits to the pager.
4297  *
4298  *      Notes:
4299  *              Original versions of this routine were very
4300  *              inefficient because they iteratively called
4301  *              pmap_remove (slow...)
4302  */
4303
4304 void
4305 pmap_remove_all(vm_page_t m)
4306 {
4307         struct md_page *pvh;
4308         pv_entry_t pv;
4309         pmap_t pmap;
4310         struct rwlock *lock;
4311         pt_entry_t *pte, tpte, PG_A, PG_M, PG_RW;
4312         pd_entry_t *pde;
4313         vm_offset_t va;
4314         struct spglist free;
4315         int pvh_gen, md_gen;
4316
4317         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4318             ("pmap_remove_all: page %p is not managed", m));
4319         SLIST_INIT(&free);
4320         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
4321         pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
4322             pa_to_pvh(VM_PAGE_TO_PHYS(m));
4323 retry:
4324         rw_wlock(lock);
4325         while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
4326                 pmap = PV_PMAP(pv);
4327                 if (!PMAP_TRYLOCK(pmap)) {
4328                         pvh_gen = pvh->pv_gen;
4329                         rw_wunlock(lock);
4330                         PMAP_LOCK(pmap);
4331                         rw_wlock(lock);
4332                         if (pvh_gen != pvh->pv_gen) {
4333                                 rw_wunlock(lock);
4334                                 PMAP_UNLOCK(pmap);
4335                                 goto retry;
4336                         }
4337                 }
4338                 va = pv->pv_va;
4339                 pde = pmap_pde(pmap, va);
4340                 (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
4341                 PMAP_UNLOCK(pmap);
4342         }
4343         while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
4344                 pmap = PV_PMAP(pv);
4345                 if (!PMAP_TRYLOCK(pmap)) {
4346                         pvh_gen = pvh->pv_gen;
4347                         md_gen = m->md.pv_gen;
4348                         rw_wunlock(lock);
4349                         PMAP_LOCK(pmap);
4350                         rw_wlock(lock);
4351                         if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
4352                                 rw_wunlock(lock);
4353                                 PMAP_UNLOCK(pmap);
4354                                 goto retry;
4355                         }
4356                 }
4357                 PG_A = pmap_accessed_bit(pmap);
4358                 PG_M = pmap_modified_bit(pmap);
4359                 PG_RW = pmap_rw_bit(pmap);
4360                 pmap_resident_count_dec(pmap, 1);
4361                 pde = pmap_pde(pmap, pv->pv_va);
4362                 KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
4363                     " a 2mpage in page %p's pv list", m));
4364                 pte = pmap_pde_to_pte(pde, pv->pv_va);
4365                 tpte = pte_load_clear(pte);
4366                 if (tpte & PG_W)
4367                         pmap->pm_stats.wired_count--;
4368                 if (tpte & PG_A)
4369                         vm_page_aflag_set(m, PGA_REFERENCED);
4370
4371                 /*
4372                  * Update the vm_page_t clean and reference bits.
4373                  */
4374                 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4375                         vm_page_dirty(m);
4376                 pmap_unuse_pt(pmap, pv->pv_va, *pde, &free);
4377                 pmap_invalidate_page(pmap, pv->pv_va);
4378                 TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4379                 m->md.pv_gen++;
4380                 free_pv_entry(pmap, pv);
4381                 PMAP_UNLOCK(pmap);
4382         }
4383         vm_page_aflag_clear(m, PGA_WRITEABLE);
4384         rw_wunlock(lock);
4385         pmap_delayed_invl_wait(m);
4386         vm_page_free_pages_toq(&free, true);
4387 }
4388
4389 /*
4390  * pmap_protect_pde: do the things to protect a 2mpage in a process
4391  */
4392 static boolean_t
4393 pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
4394 {
4395         pd_entry_t newpde, oldpde;
4396         vm_offset_t eva, va;
4397         vm_page_t m;
4398         boolean_t anychanged;
4399         pt_entry_t PG_G, PG_M, PG_RW;
4400
4401         PG_G = pmap_global_bit(pmap);
4402         PG_M = pmap_modified_bit(pmap);
4403         PG_RW = pmap_rw_bit(pmap);
4404
4405         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4406         KASSERT((sva & PDRMASK) == 0,
4407             ("pmap_protect_pde: sva is not 2mpage aligned"));
4408         anychanged = FALSE;
4409 retry:
4410         oldpde = newpde = *pde;
4411         if ((oldpde & (PG_MANAGED | PG_M | PG_RW)) ==
4412             (PG_MANAGED | PG_M | PG_RW)) {
4413                 eva = sva + NBPDR;
4414                 for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
4415                     va < eva; va += PAGE_SIZE, m++)
4416                         vm_page_dirty(m);
4417         }
4418         if ((prot & VM_PROT_WRITE) == 0)
4419                 newpde &= ~(PG_RW | PG_M);
4420         if ((prot & VM_PROT_EXECUTE) == 0)
4421                 newpde |= pg_nx;
4422         if (newpde != oldpde) {
4423                 /*
4424                  * As an optimization to future operations on this PDE, clear
4425                  * PG_PROMOTED.  The impending invalidation will remove any
4426                  * lingering 4KB page mappings from the TLB.
4427                  */
4428                 if (!atomic_cmpset_long(pde, oldpde, newpde & ~PG_PROMOTED))
4429                         goto retry;
4430                 if ((oldpde & PG_G) != 0)
4431                         pmap_invalidate_pde_page(kernel_pmap, sva, oldpde);
4432                 else
4433                         anychanged = TRUE;
4434         }
4435         return (anychanged);
4436 }
4437
4438 /*
4439  *      Set the physical protection on the
4440  *      specified range of this map as requested.
4441  */
4442 void
4443 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
4444 {
4445         vm_offset_t va_next;
4446         pml4_entry_t *pml4e;
4447         pdp_entry_t *pdpe;
4448         pd_entry_t ptpaddr, *pde;
4449         pt_entry_t *pte, PG_G, PG_M, PG_RW, PG_V;
4450         boolean_t anychanged;
4451
4452         KASSERT((prot & ~VM_PROT_ALL) == 0, ("invalid prot %x", prot));
4453         if (prot == VM_PROT_NONE) {
4454                 pmap_remove(pmap, sva, eva);
4455                 return;
4456         }
4457
4458         if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
4459             (VM_PROT_WRITE|VM_PROT_EXECUTE))
4460                 return;
4461
4462         PG_G = pmap_global_bit(pmap);
4463         PG_M = pmap_modified_bit(pmap);
4464         PG_V = pmap_valid_bit(pmap);
4465         PG_RW = pmap_rw_bit(pmap);
4466         anychanged = FALSE;
4467
4468         /*
4469          * Although this function delays and batches the invalidation
4470          * of stale TLB entries, it does not need to call
4471          * pmap_delayed_invl_started() and
4472          * pmap_delayed_invl_finished(), because it does not
4473          * ordinarily destroy mappings.  Stale TLB entries from
4474          * protection-only changes need only be invalidated before the
4475          * pmap lock is released, because protection-only changes do
4476          * not destroy PV entries.  Even operations that iterate over
4477          * a physical page's PV list of mappings, like
4478          * pmap_remove_write(), acquire the pmap lock for each
4479          * mapping.  Consequently, for protection-only changes, the
4480          * pmap lock suffices to synchronize both page table and TLB
4481          * updates.
4482          *
4483          * This function only destroys a mapping if pmap_demote_pde()
4484          * fails.  In that case, stale TLB entries are immediately
4485          * invalidated.
4486          */
4487         
4488         PMAP_LOCK(pmap);
4489         for (; sva < eva; sva = va_next) {
4490
4491                 pml4e = pmap_pml4e(pmap, sva);
4492                 if ((*pml4e & PG_V) == 0) {
4493                         va_next = (sva + NBPML4) & ~PML4MASK;
4494                         if (va_next < sva)
4495                                 va_next = eva;
4496                         continue;
4497                 }
4498
4499                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
4500                 if ((*pdpe & PG_V) == 0) {
4501                         va_next = (sva + NBPDP) & ~PDPMASK;
4502                         if (va_next < sva)
4503                                 va_next = eva;
4504                         continue;
4505                 }
4506
4507                 va_next = (sva + NBPDR) & ~PDRMASK;
4508                 if (va_next < sva)
4509                         va_next = eva;
4510
4511                 pde = pmap_pdpe_to_pde(pdpe, sva);
4512                 ptpaddr = *pde;
4513
4514                 /*
4515                  * Weed out invalid mappings.
4516                  */
4517                 if (ptpaddr == 0)
4518                         continue;
4519
4520                 /*
4521                  * Check for large page.
4522                  */
4523                 if ((ptpaddr & PG_PS) != 0) {
4524                         /*
4525                          * Are we protecting the entire large page?  If not,
4526                          * demote the mapping and fall through.
4527                          */
4528                         if (sva + NBPDR == va_next && eva >= va_next) {
4529                                 /*
4530                                  * The TLB entry for a PG_G mapping is
4531                                  * invalidated by pmap_protect_pde().
4532                                  */
4533                                 if (pmap_protect_pde(pmap, pde, sva, prot))
4534                                         anychanged = TRUE;
4535                                 continue;
4536                         } else if (!pmap_demote_pde(pmap, pde, sva)) {
4537                                 /*
4538                                  * The large page mapping was destroyed.
4539                                  */
4540                                 continue;
4541                         }
4542                 }
4543
4544                 if (va_next > eva)
4545                         va_next = eva;
4546
4547                 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
4548                     sva += PAGE_SIZE) {
4549                         pt_entry_t obits, pbits;
4550                         vm_page_t m;
4551
4552 retry:
4553                         obits = pbits = *pte;
4554                         if ((pbits & PG_V) == 0)
4555                                 continue;
4556
4557                         if ((prot & VM_PROT_WRITE) == 0) {
4558                                 if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
4559                                     (PG_MANAGED | PG_M | PG_RW)) {
4560                                         m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
4561                                         vm_page_dirty(m);
4562                                 }
4563                                 pbits &= ~(PG_RW | PG_M);
4564                         }
4565                         if ((prot & VM_PROT_EXECUTE) == 0)
4566                                 pbits |= pg_nx;
4567
4568                         if (pbits != obits) {
4569                                 if (!atomic_cmpset_long(pte, obits, pbits))
4570                                         goto retry;
4571                                 if (obits & PG_G)
4572                                         pmap_invalidate_page(pmap, sva);
4573                                 else
4574                                         anychanged = TRUE;
4575                         }
4576                 }
4577         }
4578         if (anychanged)
4579                 pmap_invalidate_all(pmap);
4580         PMAP_UNLOCK(pmap);
4581 }
4582
4583 #if VM_NRESERVLEVEL > 0
4584 /*
4585  * Tries to promote the 512, contiguous 4KB page mappings that are within a
4586  * single page table page (PTP) to a single 2MB page mapping.  For promotion
4587  * to occur, two conditions must be met: (1) the 4KB page mappings must map
4588  * aligned, contiguous physical memory and (2) the 4KB page mappings must have
4589  * identical characteristics. 
4590  */
4591 static void
4592 pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va,
4593     struct rwlock **lockp)
4594 {
4595         pd_entry_t newpde;
4596         pt_entry_t *firstpte, oldpte, pa, *pte;
4597         pt_entry_t PG_G, PG_A, PG_M, PG_RW, PG_V;
4598         vm_page_t mpte;
4599         int PG_PTE_CACHE;
4600
4601         PG_A = pmap_accessed_bit(pmap);
4602         PG_G = pmap_global_bit(pmap);
4603         PG_M = pmap_modified_bit(pmap);
4604         PG_V = pmap_valid_bit(pmap);
4605         PG_RW = pmap_rw_bit(pmap);
4606         PG_PTE_CACHE = pmap_cache_mask(pmap, 0);
4607
4608         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
4609
4610         /*
4611          * Examine the first PTE in the specified PTP.  Abort if this PTE is
4612          * either invalid, unused, or does not map the first 4KB physical page
4613          * within a 2MB page. 
4614          */
4615         firstpte = (pt_entry_t *)PHYS_TO_DMAP(*pde & PG_FRAME);
4616 setpde:
4617         newpde = *firstpte;
4618         if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
4619                 atomic_add_long(&pmap_pde_p_failures, 1);
4620                 CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4621                     " in pmap %p", va, pmap);
4622                 return;
4623         }
4624         if ((newpde & (PG_M | PG_RW)) == PG_RW) {
4625                 /*
4626                  * When PG_M is already clear, PG_RW can be cleared without
4627                  * a TLB invalidation.
4628                  */
4629                 if (!atomic_cmpset_long(firstpte, newpde, newpde & ~PG_RW))
4630                         goto setpde;
4631                 newpde &= ~PG_RW;
4632         }
4633
4634         /*
4635          * Examine each of the other PTEs in the specified PTP.  Abort if this
4636          * PTE maps an unexpected 4KB physical page or does not have identical
4637          * characteristics to the first PTE.
4638          */
4639         pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
4640         for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
4641 setpte:
4642                 oldpte = *pte;
4643                 if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
4644                         atomic_add_long(&pmap_pde_p_failures, 1);
4645                         CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4646                             " in pmap %p", va, pmap);
4647                         return;
4648                 }
4649                 if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
4650                         /*
4651                          * When PG_M is already clear, PG_RW can be cleared
4652                          * without a TLB invalidation.
4653                          */
4654                         if (!atomic_cmpset_long(pte, oldpte, oldpte & ~PG_RW))
4655                                 goto setpte;
4656                         oldpte &= ~PG_RW;
4657                         CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#lx"
4658                             " in pmap %p", (oldpte & PG_FRAME & PDRMASK) |
4659                             (va & ~PDRMASK), pmap);
4660                 }
4661                 if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
4662                         atomic_add_long(&pmap_pde_p_failures, 1);
4663                         CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#lx"
4664                             " in pmap %p", va, pmap);
4665                         return;
4666                 }
4667                 pa -= PAGE_SIZE;
4668         }
4669
4670         /*
4671          * Save the page table page in its current state until the PDE
4672          * mapping the superpage is demoted by pmap_demote_pde() or
4673          * destroyed by pmap_remove_pde(). 
4674          */
4675         mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4676         KASSERT(mpte >= vm_page_array &&
4677             mpte < &vm_page_array[vm_page_array_size],
4678             ("pmap_promote_pde: page table page is out of range"));
4679         KASSERT(mpte->pindex == pmap_pde_pindex(va),
4680             ("pmap_promote_pde: page table page's pindex is wrong"));
4681         if (pmap_insert_pt_page(pmap, mpte)) {
4682                 atomic_add_long(&pmap_pde_p_failures, 1);
4683                 CTR2(KTR_PMAP,
4684                     "pmap_promote_pde: failure for va %#lx in pmap %p", va,
4685                     pmap);
4686                 return;
4687         }
4688
4689         /*
4690          * Promote the pv entries.
4691          */
4692         if ((newpde & PG_MANAGED) != 0)
4693                 pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME, lockp);
4694
4695         /*
4696          * Propagate the PAT index to its proper position.
4697          */
4698         newpde = pmap_swap_pat(pmap, newpde);
4699
4700         /*
4701          * Map the superpage.
4702          */
4703         if (workaround_erratum383)
4704                 pmap_update_pde(pmap, va, pde, PG_PS | newpde);
4705         else
4706                 pde_store(pde, PG_PROMOTED | PG_PS | newpde);
4707
4708         atomic_add_long(&pmap_pde_promotions, 1);
4709         CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#lx"
4710             " in pmap %p", va, pmap);
4711 }
4712 #endif /* VM_NRESERVLEVEL > 0 */
4713
4714 /*
4715  *      Insert the given physical page (p) at
4716  *      the specified virtual address (v) in the
4717  *      target physical map with the protection requested.
4718  *
4719  *      If specified, the page will be wired down, meaning
4720  *      that the related pte can not be reclaimed.
4721  *
4722  *      NB:  This is the only routine which MAY NOT lazy-evaluate
4723  *      or lose information.  That is, this routine must actually
4724  *      insert this page into the given map NOW.
4725  *
4726  *      When destroying both a page table and PV entry, this function
4727  *      performs the TLB invalidation before releasing the PV list
4728  *      lock, so we do not need pmap_delayed_invl_page() calls here.
4729  */
4730 int
4731 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4732     u_int flags, int8_t psind)
4733 {
4734         struct rwlock *lock;
4735         pd_entry_t *pde;
4736         pt_entry_t *pte, PG_G, PG_A, PG_M, PG_RW, PG_V;
4737         pt_entry_t newpte, origpte;
4738         pv_entry_t pv;
4739         vm_paddr_t opa, pa;
4740         vm_page_t mpte, om;
4741         int rv;
4742         boolean_t nosleep;
4743
4744         PG_A = pmap_accessed_bit(pmap);
4745         PG_G = pmap_global_bit(pmap);
4746         PG_M = pmap_modified_bit(pmap);
4747         PG_V = pmap_valid_bit(pmap);
4748         PG_RW = pmap_rw_bit(pmap);
4749
4750         va = trunc_page(va);
4751         KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
4752         KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
4753             ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%lx)",
4754             va));
4755         KASSERT((m->oflags & VPO_UNMANAGED) != 0 || va < kmi.clean_sva ||
4756             va >= kmi.clean_eva,
4757             ("pmap_enter: managed mapping within the clean submap"));
4758         if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
4759                 VM_OBJECT_ASSERT_LOCKED(m->object);
4760         KASSERT((flags & PMAP_ENTER_RESERVED) == 0,
4761             ("pmap_enter: flags %u has reserved bits set", flags));
4762         pa = VM_PAGE_TO_PHYS(m);
4763         newpte = (pt_entry_t)(pa | PG_A | PG_V);
4764         if ((flags & VM_PROT_WRITE) != 0)
4765                 newpte |= PG_M;
4766         if ((prot & VM_PROT_WRITE) != 0)
4767                 newpte |= PG_RW;
4768         KASSERT((newpte & (PG_M | PG_RW)) != PG_M,
4769             ("pmap_enter: flags includes VM_PROT_WRITE but prot doesn't"));
4770         if ((prot & VM_PROT_EXECUTE) == 0)
4771                 newpte |= pg_nx;
4772         if ((flags & PMAP_ENTER_WIRED) != 0)
4773                 newpte |= PG_W;
4774         if (va < VM_MAXUSER_ADDRESS)
4775                 newpte |= PG_U;
4776         if (pmap == kernel_pmap)
4777                 newpte |= PG_G;
4778         newpte |= pmap_cache_bits(pmap, m->md.pat_mode, psind > 0);
4779
4780         /*
4781          * Set modified bit gratuitously for writeable mappings if
4782          * the page is unmanaged. We do not want to take a fault
4783          * to do the dirty bit accounting for these mappings.
4784          */
4785         if ((m->oflags & VPO_UNMANAGED) != 0) {
4786                 if ((newpte & PG_RW) != 0)
4787                         newpte |= PG_M;
4788         } else
4789                 newpte |= PG_MANAGED;
4790
4791         lock = NULL;
4792         PMAP_LOCK(pmap);
4793         if (psind == 1) {
4794                 /* Assert the required virtual and physical alignment. */ 
4795                 KASSERT((va & PDRMASK) == 0, ("pmap_enter: va unaligned"));
4796                 KASSERT(m->psind > 0, ("pmap_enter: m->psind < psind"));
4797                 rv = pmap_enter_pde(pmap, va, newpte | PG_PS, flags, m, &lock);
4798                 goto out;
4799         }
4800         mpte = NULL;
4801
4802         /*
4803          * In the case that a page table page is not
4804          * resident, we are creating it here.
4805          */
4806 retry:
4807         pde = pmap_pde(pmap, va);
4808         if (pde != NULL && (*pde & PG_V) != 0 && ((*pde & PG_PS) == 0 ||
4809             pmap_demote_pde_locked(pmap, pde, va, &lock))) {
4810                 pte = pmap_pde_to_pte(pde, va);
4811                 if (va < VM_MAXUSER_ADDRESS && mpte == NULL) {
4812                         mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
4813                         mpte->wire_count++;
4814                 }
4815         } else if (va < VM_MAXUSER_ADDRESS) {
4816                 /*
4817                  * Here if the pte page isn't mapped, or if it has been
4818                  * deallocated.
4819                  */
4820                 nosleep = (flags & PMAP_ENTER_NOSLEEP) != 0;
4821                 mpte = _pmap_allocpte(pmap, pmap_pde_pindex(va),
4822                     nosleep ? NULL : &lock);
4823                 if (mpte == NULL && nosleep) {
4824                         rv = KERN_RESOURCE_SHORTAGE;
4825                         goto out;
4826                 }
4827                 goto retry;
4828         } else
4829                 panic("pmap_enter: invalid page directory va=%#lx", va);
4830
4831         origpte = *pte;
4832         pv = NULL;
4833
4834         /*
4835          * Is the specified virtual address already mapped?
4836          */
4837         if ((origpte & PG_V) != 0) {
4838                 /*
4839                  * Wiring change, just update stats. We don't worry about
4840                  * wiring PT pages as they remain resident as long as there
4841                  * are valid mappings in them. Hence, if a user page is wired,
4842                  * the PT page will be also.
4843                  */
4844                 if ((newpte & PG_W) != 0 && (origpte & PG_W) == 0)
4845                         pmap->pm_stats.wired_count++;
4846                 else if ((newpte & PG_W) == 0 && (origpte & PG_W) != 0)
4847                         pmap->pm_stats.wired_count--;
4848
4849                 /*
4850                  * Remove the extra PT page reference.
4851                  */
4852                 if (mpte != NULL) {
4853                         mpte->wire_count--;
4854                         KASSERT(mpte->wire_count > 0,
4855                             ("pmap_enter: missing reference to page table page,"
4856                              " va: 0x%lx", va));
4857                 }
4858
4859                 /*
4860                  * Has the physical page changed?
4861                  */
4862                 opa = origpte & PG_FRAME;
4863                 if (opa == pa) {
4864                         /*
4865                          * No, might be a protection or wiring change.
4866                          */
4867                         if ((origpte & PG_MANAGED) != 0 &&
4868                             (newpte & PG_RW) != 0)
4869                                 vm_page_aflag_set(m, PGA_WRITEABLE);
4870                         if (((origpte ^ newpte) & ~(PG_M | PG_A)) == 0)
4871                                 goto unchanged;
4872                         goto validate;
4873                 }
4874
4875                 /*
4876                  * The physical page has changed.  Temporarily invalidate
4877                  * the mapping.  This ensures that all threads sharing the
4878                  * pmap keep a consistent view of the mapping, which is
4879                  * necessary for the correct handling of COW faults.  It
4880                  * also permits reuse of the old mapping's PV entry,
4881                  * avoiding an allocation.
4882                  *
4883                  * For consistency, handle unmanaged mappings the same way.
4884                  */
4885                 origpte = pte_load_clear(pte);
4886                 KASSERT((origpte & PG_FRAME) == opa,
4887                     ("pmap_enter: unexpected pa update for %#lx", va));
4888                 if ((origpte & PG_MANAGED) != 0) {
4889                         om = PHYS_TO_VM_PAGE(opa);
4890
4891                         /*
4892                          * The pmap lock is sufficient to synchronize with
4893                          * concurrent calls to pmap_page_test_mappings() and
4894                          * pmap_ts_referenced().
4895                          */
4896                         if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
4897                                 vm_page_dirty(om);
4898                         if ((origpte & PG_A) != 0)
4899                                 vm_page_aflag_set(om, PGA_REFERENCED);
4900                         CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, opa);
4901                         pv = pmap_pvh_remove(&om->md, pmap, va);
4902                         if ((newpte & PG_MANAGED) == 0)
4903                                 free_pv_entry(pmap, pv);
4904                         if ((om->aflags & PGA_WRITEABLE) != 0 &&
4905                             TAILQ_EMPTY(&om->md.pv_list) &&
4906                             ((om->flags & PG_FICTITIOUS) != 0 ||
4907                             TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
4908                                 vm_page_aflag_clear(om, PGA_WRITEABLE);
4909                 }
4910                 if ((origpte & PG_A) != 0)
4911                         pmap_invalidate_page(pmap, va);
4912                 origpte = 0;
4913         } else {
4914                 /*
4915                  * Increment the counters.
4916                  */
4917                 if ((newpte & PG_W) != 0)
4918                         pmap->pm_stats.wired_count++;
4919                 pmap_resident_count_inc(pmap, 1);
4920         }
4921
4922         /*
4923          * Enter on the PV list if part of our managed memory.
4924          */
4925         if ((newpte & PG_MANAGED) != 0) {
4926                 if (pv == NULL) {
4927                         pv = get_pv_entry(pmap, &lock);
4928                         pv->pv_va = va;
4929                 }
4930                 CHANGE_PV_LIST_LOCK_TO_PHYS(&lock, pa);
4931                 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4932                 m->md.pv_gen++;
4933                 if ((newpte & PG_RW) != 0)
4934                         vm_page_aflag_set(m, PGA_WRITEABLE);
4935         }
4936
4937         /*
4938          * Update the PTE.
4939          */
4940         if ((origpte & PG_V) != 0) {
4941 validate:
4942                 origpte = pte_load_store(pte, newpte);
4943                 KASSERT((origpte & PG_FRAME) == pa,
4944                     ("pmap_enter: unexpected pa update for %#lx", va));
4945                 if ((newpte & PG_M) == 0 && (origpte & (PG_M | PG_RW)) ==
4946                     (PG_M | PG_RW)) {
4947                         if ((origpte & PG_MANAGED) != 0)
4948                                 vm_page_dirty(m);
4949
4950                         /*
4951                          * Although the PTE may still have PG_RW set, TLB
4952                          * invalidation may nonetheless be required because
4953                          * the PTE no longer has PG_M set.
4954                          */
4955                 } else if ((origpte & PG_NX) != 0 || (newpte & PG_NX) == 0) {
4956                         /*
4957                          * This PTE change does not require TLB invalidation.
4958                          */
4959                         goto unchanged;
4960                 }
4961                 if ((origpte & PG_A) != 0)
4962                         pmap_invalidate_page(pmap, va);
4963         } else
4964                 pte_store(pte, newpte);
4965
4966 unchanged:
4967
4968 #if VM_NRESERVLEVEL > 0
4969         /*
4970          * If both the page table page and the reservation are fully
4971          * populated, then attempt promotion.
4972          */
4973         if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
4974             pmap_ps_enabled(pmap) &&
4975             (m->flags & PG_FICTITIOUS) == 0 &&
4976             vm_reserv_level_iffullpop(m) == 0)
4977                 pmap_promote_pde(pmap, pde, va, &lock);
4978 #endif
4979
4980         rv = KERN_SUCCESS;
4981 out:
4982         if (lock != NULL)
4983                 rw_wunlock(lock);
4984         PMAP_UNLOCK(pmap);
4985         return (rv);
4986 }
4987
4988 /*
4989  * Tries to create a read- and/or execute-only 2MB page mapping.  Returns true
4990  * if successful.  Returns false if (1) a page table page cannot be allocated
4991  * without sleeping, (2) a mapping already exists at the specified virtual
4992  * address, or (3) a PV entry cannot be allocated without reclaiming another
4993  * PV entry.
4994  */
4995 static bool
4996 pmap_enter_2mpage(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
4997     struct rwlock **lockp)
4998 {
4999         pd_entry_t newpde;
5000         pt_entry_t PG_V;
5001
5002         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5003         PG_V = pmap_valid_bit(pmap);
5004         newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 1) |
5005             PG_PS | PG_V;
5006         if ((m->oflags & VPO_UNMANAGED) == 0)
5007                 newpde |= PG_MANAGED;
5008         if ((prot & VM_PROT_EXECUTE) == 0)
5009                 newpde |= pg_nx;
5010         if (va < VM_MAXUSER_ADDRESS)
5011                 newpde |= PG_U;
5012         return (pmap_enter_pde(pmap, va, newpde, PMAP_ENTER_NOSLEEP |
5013             PMAP_ENTER_NOREPLACE | PMAP_ENTER_NORECLAIM, NULL, lockp) ==
5014             KERN_SUCCESS);
5015 }
5016
5017 /*
5018  * Tries to create the specified 2MB page mapping.  Returns KERN_SUCCESS if
5019  * the mapping was created, and either KERN_FAILURE or KERN_RESOURCE_SHORTAGE
5020  * otherwise.  Returns KERN_FAILURE if PMAP_ENTER_NOREPLACE was specified and
5021  * a mapping already exists at the specified virtual address.  Returns
5022  * KERN_RESOURCE_SHORTAGE if PMAP_ENTER_NOSLEEP was specified and a page table
5023  * page allocation failed.  Returns KERN_RESOURCE_SHORTAGE if
5024  * PMAP_ENTER_NORECLAIM was specified and a PV entry allocation failed.
5025  *
5026  * The parameter "m" is only used when creating a managed, writeable mapping.
5027  */
5028 static int
5029 pmap_enter_pde(pmap_t pmap, vm_offset_t va, pd_entry_t newpde, u_int flags,
5030     vm_page_t m, struct rwlock **lockp)
5031 {
5032         struct spglist free;
5033         pd_entry_t oldpde, *pde;
5034         pt_entry_t PG_G, PG_RW, PG_V;
5035         vm_page_t mt, pdpg;
5036
5037         PG_G = pmap_global_bit(pmap);
5038         PG_RW = pmap_rw_bit(pmap);
5039         KASSERT((newpde & (pmap_modified_bit(pmap) | PG_RW)) != PG_RW,
5040             ("pmap_enter_pde: newpde is missing PG_M"));
5041         PG_V = pmap_valid_bit(pmap);
5042         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5043
5044         if ((pdpg = pmap_allocpde(pmap, va, (flags & PMAP_ENTER_NOSLEEP) != 0 ?
5045             NULL : lockp)) == NULL) {
5046                 CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5047                     " in pmap %p", va, pmap);
5048                 return (KERN_RESOURCE_SHORTAGE);
5049         }
5050         pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5051         pde = &pde[pmap_pde_index(va)];
5052         oldpde = *pde;
5053         if ((oldpde & PG_V) != 0) {
5054                 KASSERT(pdpg->wire_count > 1,
5055                     ("pmap_enter_pde: pdpg's wire count is too low"));
5056                 if ((flags & PMAP_ENTER_NOREPLACE) != 0) {
5057                         pdpg->wire_count--;
5058                         CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5059                             " in pmap %p", va, pmap);
5060                         return (KERN_FAILURE);
5061                 }
5062                 /* Break the existing mapping(s). */
5063                 SLIST_INIT(&free);
5064                 if ((oldpde & PG_PS) != 0) {
5065                         /*
5066                          * The reference to the PD page that was acquired by
5067                          * pmap_allocpde() ensures that it won't be freed.
5068                          * However, if the PDE resulted from a promotion, then
5069                          * a reserved PT page could be freed.
5070                          */
5071                         (void)pmap_remove_pde(pmap, pde, va, &free, lockp);
5072                         if ((oldpde & PG_G) == 0)
5073                                 pmap_invalidate_pde_page(pmap, va, oldpde);
5074                 } else {
5075                         pmap_delayed_invl_started();
5076                         if (pmap_remove_ptes(pmap, va, va + NBPDR, pde, &free,
5077                             lockp))
5078                                pmap_invalidate_all(pmap);
5079                         pmap_delayed_invl_finished();
5080                 }
5081                 vm_page_free_pages_toq(&free, true);
5082                 if (va >= VM_MAXUSER_ADDRESS) {
5083                         mt = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
5084                         if (pmap_insert_pt_page(pmap, mt)) {
5085                                 /*
5086                                  * XXX Currently, this can't happen because
5087                                  * we do not perform pmap_enter(psind == 1)
5088                                  * on the kernel pmap.
5089                                  */
5090                                 panic("pmap_enter_pde: trie insert failed");
5091                         }
5092                 } else
5093                         KASSERT(*pde == 0, ("pmap_enter_pde: non-zero pde %p",
5094                             pde));
5095         }
5096         if ((newpde & PG_MANAGED) != 0) {
5097                 /*
5098                  * Abort this mapping if its PV entry could not be created.
5099                  */
5100                 if (!pmap_pv_insert_pde(pmap, va, newpde, flags, lockp)) {
5101                         SLIST_INIT(&free);
5102                         if (pmap_unwire_ptp(pmap, va, pdpg, &free)) {
5103                                 /*
5104                                  * Although "va" is not mapped, paging-
5105                                  * structure caches could nonetheless have
5106                                  * entries that refer to the freed page table
5107                                  * pages.  Invalidate those entries.
5108                                  */
5109                                 pmap_invalidate_page(pmap, va);
5110                                 vm_page_free_pages_toq(&free, true);
5111                         }
5112                         CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
5113                             " in pmap %p", va, pmap);
5114                         return (KERN_RESOURCE_SHORTAGE);
5115                 }
5116                 if ((newpde & PG_RW) != 0) {
5117                         for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
5118                                 vm_page_aflag_set(mt, PGA_WRITEABLE);
5119                 }
5120         }
5121
5122         /*
5123          * Increment counters.
5124          */
5125         if ((newpde & PG_W) != 0)
5126                 pmap->pm_stats.wired_count += NBPDR / PAGE_SIZE;
5127         pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5128
5129         /*
5130          * Map the superpage.  (This is not a promoted mapping; there will not
5131          * be any lingering 4KB page mappings in the TLB.)
5132          */
5133         pde_store(pde, newpde);
5134
5135         atomic_add_long(&pmap_pde_mappings, 1);
5136         CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
5137             " in pmap %p", va, pmap);
5138         return (KERN_SUCCESS);
5139 }
5140
5141 /*
5142  * Maps a sequence of resident pages belonging to the same object.
5143  * The sequence begins with the given page m_start.  This page is
5144  * mapped at the given virtual address start.  Each subsequent page is
5145  * mapped at a virtual address that is offset from start by the same
5146  * amount as the page is offset from m_start within the object.  The
5147  * last page in the sequence is the page with the largest offset from
5148  * m_start that can be mapped at a virtual address less than the given
5149  * virtual address end.  Not every virtual page between start and end
5150  * is mapped; only those for which a resident page exists with the
5151  * corresponding offset from m_start are mapped.
5152  */
5153 void
5154 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
5155     vm_page_t m_start, vm_prot_t prot)
5156 {
5157         struct rwlock *lock;
5158         vm_offset_t va;
5159         vm_page_t m, mpte;
5160         vm_pindex_t diff, psize;
5161
5162         VM_OBJECT_ASSERT_LOCKED(m_start->object);
5163
5164         psize = atop(end - start);
5165         mpte = NULL;
5166         m = m_start;
5167         lock = NULL;
5168         PMAP_LOCK(pmap);
5169         while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
5170                 va = start + ptoa(diff);
5171                 if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
5172                     m->psind == 1 && pmap_ps_enabled(pmap) &&
5173                     pmap_enter_2mpage(pmap, va, m, prot, &lock))
5174                         m = &m[NBPDR / PAGE_SIZE - 1];
5175                 else
5176                         mpte = pmap_enter_quick_locked(pmap, va, m, prot,
5177                             mpte, &lock);
5178                 m = TAILQ_NEXT(m, listq);
5179         }
5180         if (lock != NULL)
5181                 rw_wunlock(lock);
5182         PMAP_UNLOCK(pmap);
5183 }
5184
5185 /*
5186  * this code makes some *MAJOR* assumptions:
5187  * 1. Current pmap & pmap exists.
5188  * 2. Not wired.
5189  * 3. Read access.
5190  * 4. No page table pages.
5191  * but is *MUCH* faster than pmap_enter...
5192  */
5193
5194 void
5195 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
5196 {
5197         struct rwlock *lock;
5198
5199         lock = NULL;
5200         PMAP_LOCK(pmap);
5201         (void)pmap_enter_quick_locked(pmap, va, m, prot, NULL, &lock);
5202         if (lock != NULL)
5203                 rw_wunlock(lock);
5204         PMAP_UNLOCK(pmap);
5205 }
5206
5207 static vm_page_t
5208 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
5209     vm_prot_t prot, vm_page_t mpte, struct rwlock **lockp)
5210 {
5211         struct spglist free;
5212         pt_entry_t *pte, PG_V;
5213         vm_paddr_t pa;
5214
5215         KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
5216             (m->oflags & VPO_UNMANAGED) != 0,
5217             ("pmap_enter_quick_locked: managed mapping within the clean submap"));
5218         PG_V = pmap_valid_bit(pmap);
5219         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
5220
5221         /*
5222          * In the case that a page table page is not
5223          * resident, we are creating it here.
5224          */
5225         if (va < VM_MAXUSER_ADDRESS) {
5226                 vm_pindex_t ptepindex;
5227                 pd_entry_t *ptepa;
5228
5229                 /*
5230                  * Calculate pagetable page index
5231                  */
5232                 ptepindex = pmap_pde_pindex(va);
5233                 if (mpte && (mpte->pindex == ptepindex)) {
5234                         mpte->wire_count++;
5235                 } else {
5236                         /*
5237                          * Get the page directory entry
5238                          */
5239                         ptepa = pmap_pde(pmap, va);
5240
5241                         /*
5242                          * If the page table page is mapped, we just increment
5243                          * the hold count, and activate it.  Otherwise, we
5244                          * attempt to allocate a page table page.  If this
5245                          * attempt fails, we don't retry.  Instead, we give up.
5246                          */
5247                         if (ptepa && (*ptepa & PG_V) != 0) {
5248                                 if (*ptepa & PG_PS)
5249                                         return (NULL);
5250                                 mpte = PHYS_TO_VM_PAGE(*ptepa & PG_FRAME);
5251                                 mpte->wire_count++;
5252                         } else {
5253                                 /*
5254                                  * Pass NULL instead of the PV list lock
5255                                  * pointer, because we don't intend to sleep.
5256                                  */
5257                                 mpte = _pmap_allocpte(pmap, ptepindex, NULL);
5258                                 if (mpte == NULL)
5259                                         return (mpte);
5260                         }
5261                 }
5262                 pte = (pt_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mpte));
5263                 pte = &pte[pmap_pte_index(va)];
5264         } else {
5265                 mpte = NULL;
5266                 pte = vtopte(va);
5267         }
5268         if (*pte) {
5269                 if (mpte != NULL) {
5270                         mpte->wire_count--;
5271                         mpte = NULL;
5272                 }
5273                 return (mpte);
5274         }
5275
5276         /*
5277          * Enter on the PV list if part of our managed memory.
5278          */
5279         if ((m->oflags & VPO_UNMANAGED) == 0 &&
5280             !pmap_try_insert_pv_entry(pmap, va, m, lockp)) {
5281                 if (mpte != NULL) {
5282                         SLIST_INIT(&free);
5283                         if (pmap_unwire_ptp(pmap, va, mpte, &free)) {
5284                                 /*
5285                                  * Although "va" is not mapped, paging-
5286                                  * structure caches could nonetheless have
5287                                  * entries that refer to the freed page table
5288                                  * pages.  Invalidate those entries.
5289                                  */
5290                                 pmap_invalidate_page(pmap, va);
5291                                 vm_page_free_pages_toq(&free, true);
5292                         }
5293                         mpte = NULL;
5294                 }
5295                 return (mpte);
5296         }
5297
5298         /*
5299          * Increment counters
5300          */
5301         pmap_resident_count_inc(pmap, 1);
5302
5303         pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(pmap, m->md.pat_mode, 0);
5304         if ((prot & VM_PROT_EXECUTE) == 0)
5305                 pa |= pg_nx;
5306
5307         /*
5308          * Now validate mapping with RO protection
5309          */
5310         if ((m->oflags & VPO_UNMANAGED) != 0)
5311                 pte_store(pte, pa | PG_V | PG_U);
5312         else
5313                 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
5314         return (mpte);
5315 }
5316
5317 /*
5318  * Make a temporary mapping for a physical address.  This is only intended
5319  * to be used for panic dumps.
5320  */
5321 void *
5322 pmap_kenter_temporary(vm_paddr_t pa, int i)
5323 {
5324         vm_offset_t va;
5325
5326         va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
5327         pmap_kenter(va, pa);
5328         invlpg(va);
5329         return ((void *)crashdumpmap);
5330 }
5331
5332 /*
5333  * This code maps large physical mmap regions into the
5334  * processor address space.  Note that some shortcuts
5335  * are taken, but the code works.
5336  */
5337 void
5338 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
5339     vm_pindex_t pindex, vm_size_t size)
5340 {
5341         pd_entry_t *pde;
5342         pt_entry_t PG_A, PG_M, PG_RW, PG_V;
5343         vm_paddr_t pa, ptepa;
5344         vm_page_t p, pdpg;
5345         int pat_mode;
5346
5347         PG_A = pmap_accessed_bit(pmap);
5348         PG_M = pmap_modified_bit(pmap);
5349         PG_V = pmap_valid_bit(pmap);
5350         PG_RW = pmap_rw_bit(pmap);
5351
5352         VM_OBJECT_ASSERT_WLOCKED(object);
5353         KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
5354             ("pmap_object_init_pt: non-device object"));
5355         if ((addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
5356                 if (!pmap_ps_enabled(pmap))
5357                         return;
5358                 if (!vm_object_populate(object, pindex, pindex + atop(size)))
5359                         return;
5360                 p = vm_page_lookup(object, pindex);
5361                 KASSERT(p->valid == VM_PAGE_BITS_ALL,
5362                     ("pmap_object_init_pt: invalid page %p", p));
5363                 pat_mode = p->md.pat_mode;
5364
5365                 /*
5366                  * Abort the mapping if the first page is not physically
5367                  * aligned to a 2MB page boundary.
5368                  */
5369                 ptepa = VM_PAGE_TO_PHYS(p);
5370                 if (ptepa & (NBPDR - 1))
5371                         return;
5372
5373                 /*
5374                  * Skip the first page.  Abort the mapping if the rest of
5375                  * the pages are not physically contiguous or have differing
5376                  * memory attributes.
5377                  */
5378                 p = TAILQ_NEXT(p, listq);
5379                 for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
5380                     pa += PAGE_SIZE) {
5381                         KASSERT(p->valid == VM_PAGE_BITS_ALL,
5382                             ("pmap_object_init_pt: invalid page %p", p));
5383                         if (pa != VM_PAGE_TO_PHYS(p) ||
5384                             pat_mode != p->md.pat_mode)
5385                                 return;
5386                         p = TAILQ_NEXT(p, listq);
5387                 }
5388
5389                 /*
5390                  * Map using 2MB pages.  Since "ptepa" is 2M aligned and
5391                  * "size" is a multiple of 2M, adding the PAT setting to "pa"
5392                  * will not affect the termination of this loop.
5393                  */ 
5394                 PMAP_LOCK(pmap);
5395                 for (pa = ptepa | pmap_cache_bits(pmap, pat_mode, 1);
5396                     pa < ptepa + size; pa += NBPDR) {
5397                         pdpg = pmap_allocpde(pmap, addr, NULL);
5398                         if (pdpg == NULL) {
5399                                 /*
5400                                  * The creation of mappings below is only an
5401                                  * optimization.  If a page directory page
5402                                  * cannot be allocated without blocking,
5403                                  * continue on to the next mapping rather than
5404                                  * blocking.
5405                                  */
5406                                 addr += NBPDR;
5407                                 continue;
5408                         }
5409                         pde = (pd_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pdpg));
5410                         pde = &pde[pmap_pde_index(addr)];
5411                         if ((*pde & PG_V) == 0) {
5412                                 pde_store(pde, pa | PG_PS | PG_M | PG_A |
5413                                     PG_U | PG_RW | PG_V);
5414                                 pmap_resident_count_inc(pmap, NBPDR / PAGE_SIZE);
5415                                 atomic_add_long(&pmap_pde_mappings, 1);
5416                         } else {
5417                                 /* Continue on if the PDE is already valid. */
5418                                 pdpg->wire_count--;
5419                                 KASSERT(pdpg->wire_count > 0,
5420                                     ("pmap_object_init_pt: missing reference "
5421                                     "to page directory page, va: 0x%lx", addr));
5422                         }
5423                         addr += NBPDR;
5424                 }
5425                 PMAP_UNLOCK(pmap);
5426         }
5427 }
5428
5429 /*
5430  *      Clear the wired attribute from the mappings for the specified range of
5431  *      addresses in the given pmap.  Every valid mapping within that range
5432  *      must have the wired attribute set.  In contrast, invalid mappings
5433  *      cannot have the wired attribute set, so they are ignored.
5434  *
5435  *      The wired attribute of the page table entry is not a hardware
5436  *      feature, so there is no need to invalidate any TLB entries.
5437  *      Since pmap_demote_pde() for the wired entry must never fail,
5438  *      pmap_delayed_invl_started()/finished() calls around the
5439  *      function are not needed.
5440  */
5441 void
5442 pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
5443 {
5444         vm_offset_t va_next;
5445         pml4_entry_t *pml4e;
5446         pdp_entry_t *pdpe;
5447         pd_entry_t *pde;
5448         pt_entry_t *pte, PG_V;
5449
5450         PG_V = pmap_valid_bit(pmap);
5451         PMAP_LOCK(pmap);
5452         for (; sva < eva; sva = va_next) {
5453                 pml4e = pmap_pml4e(pmap, sva);
5454                 if ((*pml4e & PG_V) == 0) {
5455                         va_next = (sva + NBPML4) & ~PML4MASK;
5456                         if (va_next < sva)
5457                                 va_next = eva;
5458                         continue;
5459                 }
5460                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
5461                 if ((*pdpe & PG_V) == 0) {
5462                         va_next = (sva + NBPDP) & ~PDPMASK;
5463                         if (va_next < sva)
5464                                 va_next = eva;
5465                         continue;
5466                 }
5467                 va_next = (sva + NBPDR) & ~PDRMASK;
5468                 if (va_next < sva)
5469                         va_next = eva;
5470                 pde = pmap_pdpe_to_pde(pdpe, sva);
5471                 if ((*pde & PG_V) == 0)
5472                         continue;
5473                 if ((*pde & PG_PS) != 0) {
5474                         if ((*pde & PG_W) == 0)
5475                                 panic("pmap_unwire: pde %#jx is missing PG_W",
5476                                     (uintmax_t)*pde);
5477
5478                         /*
5479                          * Are we unwiring the entire large page?  If not,
5480                          * demote the mapping and fall through.
5481                          */
5482                         if (sva + NBPDR == va_next && eva >= va_next) {
5483                                 atomic_clear_long(pde, PG_W);
5484                                 pmap->pm_stats.wired_count -= NBPDR /
5485                                     PAGE_SIZE;
5486                                 continue;
5487                         } else if (!pmap_demote_pde(pmap, pde, sva))
5488                                 panic("pmap_unwire: demotion failed");
5489                 }
5490                 if (va_next > eva)
5491                         va_next = eva;
5492                 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
5493                     sva += PAGE_SIZE) {
5494                         if ((*pte & PG_V) == 0)
5495                                 continue;
5496                         if ((*pte & PG_W) == 0)
5497                                 panic("pmap_unwire: pte %#jx is missing PG_W",
5498                                     (uintmax_t)*pte);
5499
5500                         /*
5501                          * PG_W must be cleared atomically.  Although the pmap
5502                          * lock synchronizes access to PG_W, another processor
5503                          * could be setting PG_M and/or PG_A concurrently.
5504                          */
5505                         atomic_clear_long(pte, PG_W);
5506                         pmap->pm_stats.wired_count--;
5507                 }
5508         }
5509         PMAP_UNLOCK(pmap);
5510 }
5511
5512 /*
5513  *      Copy the range specified by src_addr/len
5514  *      from the source map to the range dst_addr/len
5515  *      in the destination map.
5516  *
5517  *      This routine is only advisory and need not do anything.
5518  */
5519
5520 void
5521 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
5522     vm_offset_t src_addr)
5523 {
5524         struct rwlock *lock;
5525         struct spglist free;
5526         vm_offset_t addr;
5527         vm_offset_t end_addr = src_addr + len;
5528         vm_offset_t va_next;
5529         vm_page_t dst_pdpg, dstmpte, srcmpte;
5530         pt_entry_t PG_A, PG_M, PG_V;
5531
5532         if (dst_addr != src_addr)
5533                 return;
5534
5535         if (dst_pmap->pm_type != src_pmap->pm_type)
5536                 return;
5537
5538         /*
5539          * EPT page table entries that require emulation of A/D bits are
5540          * sensitive to clearing the PG_A bit (aka EPT_PG_READ). Although
5541          * we clear PG_M (aka EPT_PG_WRITE) concomitantly, the PG_U bit
5542          * (aka EPT_PG_EXECUTE) could still be set. Since some EPT
5543          * implementations flag an EPT misconfiguration for exec-only
5544          * mappings we skip this function entirely for emulated pmaps.
5545          */
5546         if (pmap_emulate_ad_bits(dst_pmap))
5547                 return;
5548
5549         lock = NULL;
5550         if (dst_pmap < src_pmap) {
5551                 PMAP_LOCK(dst_pmap);
5552                 PMAP_LOCK(src_pmap);
5553         } else {
5554                 PMAP_LOCK(src_pmap);
5555                 PMAP_LOCK(dst_pmap);
5556         }
5557
5558         PG_A = pmap_accessed_bit(dst_pmap);
5559         PG_M = pmap_modified_bit(dst_pmap);
5560         PG_V = pmap_valid_bit(dst_pmap);
5561
5562         for (addr = src_addr; addr < end_addr; addr = va_next) {
5563                 pt_entry_t *src_pte, *dst_pte;
5564                 pml4_entry_t *pml4e;
5565                 pdp_entry_t *pdpe;
5566                 pd_entry_t srcptepaddr, *pde;
5567
5568                 KASSERT(addr < UPT_MIN_ADDRESS,
5569                     ("pmap_copy: invalid to pmap_copy page tables"));
5570
5571                 pml4e = pmap_pml4e(src_pmap, addr);
5572                 if ((*pml4e & PG_V) == 0) {
5573                         va_next = (addr + NBPML4) & ~PML4MASK;
5574                         if (va_next < addr)
5575                                 va_next = end_addr;
5576                         continue;
5577                 }
5578
5579                 pdpe = pmap_pml4e_to_pdpe(pml4e, addr);
5580                 if ((*pdpe & PG_V) == 0) {
5581                         va_next = (addr + NBPDP) & ~PDPMASK;
5582                         if (va_next < addr)
5583                                 va_next = end_addr;
5584                         continue;
5585                 }
5586
5587                 va_next = (addr + NBPDR) & ~PDRMASK;
5588                 if (va_next < addr)
5589                         va_next = end_addr;
5590
5591                 pde = pmap_pdpe_to_pde(pdpe, addr);
5592                 srcptepaddr = *pde;
5593                 if (srcptepaddr == 0)
5594                         continue;
5595                         
5596                 if (srcptepaddr & PG_PS) {
5597                         if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
5598                                 continue;
5599                         dst_pdpg = pmap_allocpde(dst_pmap, addr, NULL);
5600                         if (dst_pdpg == NULL)
5601                                 break;
5602                         pde = (pd_entry_t *)
5603                             PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dst_pdpg));
5604                         pde = &pde[pmap_pde_index(addr)];
5605                         if (*pde == 0 && ((srcptepaddr & PG_MANAGED) == 0 ||
5606                             pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr,
5607                             PMAP_ENTER_NORECLAIM, &lock))) {
5608                                 *pde = srcptepaddr & ~PG_W;
5609                                 pmap_resident_count_inc(dst_pmap, NBPDR / PAGE_SIZE);
5610                                 atomic_add_long(&pmap_pde_mappings, 1);
5611                         } else
5612                                 dst_pdpg->wire_count--;
5613                         continue;
5614                 }
5615
5616                 srcptepaddr &= PG_FRAME;
5617                 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
5618                 KASSERT(srcmpte->wire_count > 0,
5619                     ("pmap_copy: source page table page is unused"));
5620
5621                 if (va_next > end_addr)
5622                         va_next = end_addr;
5623
5624                 src_pte = (pt_entry_t *)PHYS_TO_DMAP(srcptepaddr);
5625                 src_pte = &src_pte[pmap_pte_index(addr)];
5626                 dstmpte = NULL;
5627                 while (addr < va_next) {
5628                         pt_entry_t ptetemp;
5629                         ptetemp = *src_pte;
5630                         /*
5631                          * we only virtual copy managed pages
5632                          */
5633                         if ((ptetemp & PG_MANAGED) != 0) {
5634                                 if (dstmpte != NULL &&
5635                                     dstmpte->pindex == pmap_pde_pindex(addr))
5636                                         dstmpte->wire_count++;
5637                                 else if ((dstmpte = pmap_allocpte(dst_pmap,
5638                                     addr, NULL)) == NULL)
5639                                         goto out;
5640                                 dst_pte = (pt_entry_t *)
5641                                     PHYS_TO_DMAP(VM_PAGE_TO_PHYS(dstmpte));
5642                                 dst_pte = &dst_pte[pmap_pte_index(addr)];
5643                                 if (*dst_pte == 0 &&
5644                                     pmap_try_insert_pv_entry(dst_pmap, addr,
5645                                     PHYS_TO_VM_PAGE(ptetemp & PG_FRAME),
5646                                     &lock)) {
5647                                         /*
5648                                          * Clear the wired, modified, and
5649                                          * accessed (referenced) bits
5650                                          * during the copy.
5651                                          */
5652                                         *dst_pte = ptetemp & ~(PG_W | PG_M |
5653                                             PG_A);
5654                                         pmap_resident_count_inc(dst_pmap, 1);
5655                                 } else {
5656                                         SLIST_INIT(&free);
5657                                         if (pmap_unwire_ptp(dst_pmap, addr,
5658                                             dstmpte, &free)) {
5659                                                 /*
5660                                                  * Although "addr" is not
5661                                                  * mapped, paging-structure
5662                                                  * caches could nonetheless
5663                                                  * have entries that refer to
5664                                                  * the freed page table pages.
5665                                                  * Invalidate those entries.
5666                                                  */
5667                                                 pmap_invalidate_page(dst_pmap,
5668                                                     addr);
5669                                                 vm_page_free_pages_toq(&free,
5670                                                     true);
5671                                         }
5672                                         goto out;
5673                                 }
5674                                 if (dstmpte->wire_count >= srcmpte->wire_count)
5675                                         break;
5676                         }
5677                         addr += PAGE_SIZE;
5678                         src_pte++;
5679                 }
5680         }
5681 out:
5682         if (lock != NULL)
5683                 rw_wunlock(lock);
5684         PMAP_UNLOCK(src_pmap);
5685         PMAP_UNLOCK(dst_pmap);
5686 }
5687
5688 /*
5689  * Zero the specified hardware page.
5690  */
5691 void
5692 pmap_zero_page(vm_page_t m)
5693 {
5694         vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5695
5696         pagezero((void *)va);
5697 }
5698
5699 /*
5700  * Zero an an area within a single hardware page.  off and size must not
5701  * cover an area beyond a single hardware page.
5702  */
5703 void
5704 pmap_zero_page_area(vm_page_t m, int off, int size)
5705 {
5706         vm_offset_t va = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m));
5707
5708         if (off == 0 && size == PAGE_SIZE)
5709                 pagezero((void *)va);
5710         else
5711                 bzero((char *)va + off, size);
5712 }
5713
5714 /*
5715  * Copy 1 specified hardware page to another.
5716  */
5717 void
5718 pmap_copy_page(vm_page_t msrc, vm_page_t mdst)
5719 {
5720         vm_offset_t src = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(msrc));
5721         vm_offset_t dst = PHYS_TO_DMAP(VM_PAGE_TO_PHYS(mdst));
5722
5723         pagecopy((void *)src, (void *)dst);
5724 }
5725
5726 int unmapped_buf_allowed = 1;
5727
5728 void
5729 pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
5730     vm_offset_t b_offset, int xfersize)
5731 {
5732         void *a_cp, *b_cp;
5733         vm_page_t pages[2];
5734         vm_offset_t vaddr[2], a_pg_offset, b_pg_offset;
5735         int cnt;
5736         boolean_t mapped;
5737
5738         while (xfersize > 0) {
5739                 a_pg_offset = a_offset & PAGE_MASK;
5740                 pages[0] = ma[a_offset >> PAGE_SHIFT];
5741                 b_pg_offset = b_offset & PAGE_MASK;
5742                 pages[1] = mb[b_offset >> PAGE_SHIFT];
5743                 cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
5744                 cnt = min(cnt, PAGE_SIZE - b_pg_offset);
5745                 mapped = pmap_map_io_transient(pages, vaddr, 2, FALSE);
5746                 a_cp = (char *)vaddr[0] + a_pg_offset;
5747                 b_cp = (char *)vaddr[1] + b_pg_offset;
5748                 bcopy(a_cp, b_cp, cnt);
5749                 if (__predict_false(mapped))
5750                         pmap_unmap_io_transient(pages, vaddr, 2, FALSE);
5751                 a_offset += cnt;
5752                 b_offset += cnt;
5753                 xfersize -= cnt;
5754         }
5755 }
5756
5757 /*
5758  * Returns true if the pmap's pv is one of the first
5759  * 16 pvs linked to from this page.  This count may
5760  * be changed upwards or downwards in the future; it
5761  * is only necessary that true be returned for a small
5762  * subset of pmaps for proper page aging.
5763  */
5764 boolean_t
5765 pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
5766 {
5767         struct md_page *pvh;
5768         struct rwlock *lock;
5769         pv_entry_t pv;
5770         int loops = 0;
5771         boolean_t rv;
5772
5773         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5774             ("pmap_page_exists_quick: page %p is not managed", m));
5775         rv = FALSE;
5776         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5777         rw_rlock(lock);
5778         TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5779                 if (PV_PMAP(pv) == pmap) {
5780                         rv = TRUE;
5781                         break;
5782                 }
5783                 loops++;
5784                 if (loops >= 16)
5785                         break;
5786         }
5787         if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
5788                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5789                 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5790                         if (PV_PMAP(pv) == pmap) {
5791                                 rv = TRUE;
5792                                 break;
5793                         }
5794                         loops++;
5795                         if (loops >= 16)
5796                                 break;
5797                 }
5798         }
5799         rw_runlock(lock);
5800         return (rv);
5801 }
5802
5803 /*
5804  *      pmap_page_wired_mappings:
5805  *
5806  *      Return the number of managed mappings to the given physical page
5807  *      that are wired.
5808  */
5809 int
5810 pmap_page_wired_mappings(vm_page_t m)
5811 {
5812         struct rwlock *lock;
5813         struct md_page *pvh;
5814         pmap_t pmap;
5815         pt_entry_t *pte;
5816         pv_entry_t pv;
5817         int count, md_gen, pvh_gen;
5818
5819         if ((m->oflags & VPO_UNMANAGED) != 0)
5820                 return (0);
5821         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5822         rw_rlock(lock);
5823 restart:
5824         count = 0;
5825         TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5826                 pmap = PV_PMAP(pv);
5827                 if (!PMAP_TRYLOCK(pmap)) {
5828                         md_gen = m->md.pv_gen;
5829                         rw_runlock(lock);
5830                         PMAP_LOCK(pmap);
5831                         rw_rlock(lock);
5832                         if (md_gen != m->md.pv_gen) {
5833                                 PMAP_UNLOCK(pmap);
5834                                 goto restart;
5835                         }
5836                 }
5837                 pte = pmap_pte(pmap, pv->pv_va);
5838                 if ((*pte & PG_W) != 0)
5839                         count++;
5840                 PMAP_UNLOCK(pmap);
5841         }
5842         if ((m->flags & PG_FICTITIOUS) == 0) {
5843                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5844                 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
5845                         pmap = PV_PMAP(pv);
5846                         if (!PMAP_TRYLOCK(pmap)) {
5847                                 md_gen = m->md.pv_gen;
5848                                 pvh_gen = pvh->pv_gen;
5849                                 rw_runlock(lock);
5850                                 PMAP_LOCK(pmap);
5851                                 rw_rlock(lock);
5852                                 if (md_gen != m->md.pv_gen ||
5853                                     pvh_gen != pvh->pv_gen) {
5854                                         PMAP_UNLOCK(pmap);
5855                                         goto restart;
5856                                 }
5857                         }
5858                         pte = pmap_pde(pmap, pv->pv_va);
5859                         if ((*pte & PG_W) != 0)
5860                                 count++;
5861                         PMAP_UNLOCK(pmap);
5862                 }
5863         }
5864         rw_runlock(lock);
5865         return (count);
5866 }
5867
5868 /*
5869  * Returns TRUE if the given page is mapped individually or as part of
5870  * a 2mpage.  Otherwise, returns FALSE.
5871  */
5872 boolean_t
5873 pmap_page_is_mapped(vm_page_t m)
5874 {
5875         struct rwlock *lock;
5876         boolean_t rv;
5877
5878         if ((m->oflags & VPO_UNMANAGED) != 0)
5879                 return (FALSE);
5880         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
5881         rw_rlock(lock);
5882         rv = !TAILQ_EMPTY(&m->md.pv_list) ||
5883             ((m->flags & PG_FICTITIOUS) == 0 &&
5884             !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
5885         rw_runlock(lock);
5886         return (rv);
5887 }
5888
5889 /*
5890  * Destroy all managed, non-wired mappings in the given user-space
5891  * pmap.  This pmap cannot be active on any processor besides the
5892  * caller.
5893  *
5894  * This function cannot be applied to the kernel pmap.  Moreover, it
5895  * is not intended for general use.  It is only to be used during
5896  * process termination.  Consequently, it can be implemented in ways
5897  * that make it faster than pmap_remove().  First, it can more quickly
5898  * destroy mappings by iterating over the pmap's collection of PV
5899  * entries, rather than searching the page table.  Second, it doesn't
5900  * have to test and clear the page table entries atomically, because
5901  * no processor is currently accessing the user address space.  In
5902  * particular, a page table entry's dirty bit won't change state once
5903  * this function starts.
5904  *
5905  * Although this function destroys all of the pmap's managed,
5906  * non-wired mappings, it can delay and batch the invalidation of TLB
5907  * entries without calling pmap_delayed_invl_started() and
5908  * pmap_delayed_invl_finished().  Because the pmap is not active on
5909  * any other processor, none of these TLB entries will ever be used
5910  * before their eventual invalidation.  Consequently, there is no need
5911  * for either pmap_remove_all() or pmap_remove_write() to wait for
5912  * that eventual TLB invalidation.
5913  */
5914 void
5915 pmap_remove_pages(pmap_t pmap)
5916 {
5917         pd_entry_t ptepde;
5918         pt_entry_t *pte, tpte;
5919         pt_entry_t PG_M, PG_RW, PG_V;
5920         struct spglist free;
5921         vm_page_t m, mpte, mt;
5922         pv_entry_t pv;
5923         struct md_page *pvh;
5924         struct pv_chunk *pc, *npc;
5925         struct rwlock *lock;
5926         int64_t bit;
5927         uint64_t inuse, bitmask;
5928         int allfree, field, freed, idx;
5929         boolean_t superpage;
5930         vm_paddr_t pa;
5931
5932         /*
5933          * Assert that the given pmap is only active on the current
5934          * CPU.  Unfortunately, we cannot block another CPU from
5935          * activating the pmap while this function is executing.
5936          */
5937         KASSERT(pmap == PCPU_GET(curpmap), ("non-current pmap %p", pmap));
5938 #ifdef INVARIANTS
5939         {
5940                 cpuset_t other_cpus;
5941
5942                 other_cpus = all_cpus;
5943                 critical_enter();
5944                 CPU_CLR(PCPU_GET(cpuid), &other_cpus);
5945                 CPU_AND(&other_cpus, &pmap->pm_active);
5946                 critical_exit();
5947                 KASSERT(CPU_EMPTY(&other_cpus), ("pmap active %p", pmap));
5948         }
5949 #endif
5950
5951         lock = NULL;
5952         PG_M = pmap_modified_bit(pmap);
5953         PG_V = pmap_valid_bit(pmap);
5954         PG_RW = pmap_rw_bit(pmap);
5955
5956         SLIST_INIT(&free);
5957         PMAP_LOCK(pmap);
5958         TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
5959                 allfree = 1;
5960                 freed = 0;
5961                 for (field = 0; field < _NPCM; field++) {
5962                         inuse = ~pc->pc_map[field] & pc_freemask[field];
5963                         while (inuse != 0) {
5964                                 bit = bsfq(inuse);
5965                                 bitmask = 1UL << bit;
5966                                 idx = field * 64 + bit;
5967                                 pv = &pc->pc_pventry[idx];
5968                                 inuse &= ~bitmask;
5969
5970                                 pte = pmap_pdpe(pmap, pv->pv_va);
5971                                 ptepde = *pte;
5972                                 pte = pmap_pdpe_to_pde(pte, pv->pv_va);
5973                                 tpte = *pte;
5974                                 if ((tpte & (PG_PS | PG_V)) == PG_V) {
5975                                         superpage = FALSE;
5976                                         ptepde = tpte;
5977                                         pte = (pt_entry_t *)PHYS_TO_DMAP(tpte &
5978                                             PG_FRAME);
5979                                         pte = &pte[pmap_pte_index(pv->pv_va)];
5980                                         tpte = *pte;
5981                                 } else {
5982                                         /*
5983                                          * Keep track whether 'tpte' is a
5984                                          * superpage explicitly instead of
5985                                          * relying on PG_PS being set.
5986                                          *
5987                                          * This is because PG_PS is numerically
5988                                          * identical to PG_PTE_PAT and thus a
5989                                          * regular page could be mistaken for
5990                                          * a superpage.
5991                                          */
5992                                         superpage = TRUE;
5993                                 }
5994
5995                                 if ((tpte & PG_V) == 0) {
5996                                         panic("bad pte va %lx pte %lx",
5997                                             pv->pv_va, tpte);
5998                                 }
5999
6000 /*
6001  * We cannot remove wired pages from a process' mapping at this time
6002  */
6003                                 if (tpte & PG_W) {
6004                                         allfree = 0;
6005                                         continue;
6006                                 }
6007
6008                                 if (superpage)
6009                                         pa = tpte & PG_PS_FRAME;
6010                                 else
6011                                         pa = tpte & PG_FRAME;
6012
6013                                 m = PHYS_TO_VM_PAGE(pa);
6014                                 KASSERT(m->phys_addr == pa,
6015                                     ("vm_page_t %p phys_addr mismatch %016jx %016jx",
6016                                     m, (uintmax_t)m->phys_addr,
6017                                     (uintmax_t)tpte));
6018
6019                                 KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
6020                                     m < &vm_page_array[vm_page_array_size],
6021                                     ("pmap_remove_pages: bad tpte %#jx",
6022                                     (uintmax_t)tpte));
6023
6024                                 pte_clear(pte);
6025
6026                                 /*
6027                                  * Update the vm_page_t clean/reference bits.
6028                                  */
6029                                 if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6030                                         if (superpage) {
6031                                                 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6032                                                         vm_page_dirty(mt);
6033                                         } else
6034                                                 vm_page_dirty(m);
6035                                 }
6036
6037                                 CHANGE_PV_LIST_LOCK_TO_VM_PAGE(&lock, m);
6038
6039                                 /* Mark free */
6040                                 pc->pc_map[field] |= bitmask;
6041                                 if (superpage) {
6042                                         pmap_resident_count_dec(pmap, NBPDR / PAGE_SIZE);
6043                                         pvh = pa_to_pvh(tpte & PG_PS_FRAME);
6044                                         TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6045                                         pvh->pv_gen++;
6046                                         if (TAILQ_EMPTY(&pvh->pv_list)) {
6047                                                 for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
6048                                                         if ((mt->aflags & PGA_WRITEABLE) != 0 &&
6049                                                             TAILQ_EMPTY(&mt->md.pv_list))
6050                                                                 vm_page_aflag_clear(mt, PGA_WRITEABLE);
6051                                         }
6052                                         mpte = pmap_remove_pt_page(pmap, pv->pv_va);
6053                                         if (mpte != NULL) {
6054                                                 pmap_resident_count_dec(pmap, 1);
6055                                                 KASSERT(mpte->wire_count == NPTEPG,
6056                                                     ("pmap_remove_pages: pte page wire count error"));
6057                                                 mpte->wire_count = 0;
6058                                                 pmap_add_delayed_free_list(mpte, &free, FALSE);
6059                                         }
6060                                 } else {
6061                                         pmap_resident_count_dec(pmap, 1);
6062                                         TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6063                                         m->md.pv_gen++;
6064                                         if ((m->aflags & PGA_WRITEABLE) != 0 &&
6065                                             TAILQ_EMPTY(&m->md.pv_list) &&
6066                                             (m->flags & PG_FICTITIOUS) == 0) {
6067                                                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6068                                                 if (TAILQ_EMPTY(&pvh->pv_list))
6069                                                         vm_page_aflag_clear(m, PGA_WRITEABLE);
6070                                         }
6071                                 }
6072                                 pmap_unuse_pt(pmap, pv->pv_va, ptepde, &free);
6073                                 freed++;
6074                         }
6075                 }
6076                 PV_STAT(atomic_add_long(&pv_entry_frees, freed));
6077                 PV_STAT(atomic_add_int(&pv_entry_spare, freed));
6078                 PV_STAT(atomic_subtract_long(&pv_entry_count, freed));
6079                 if (allfree) {
6080                         TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
6081                         free_pv_chunk(pc);
6082                 }
6083         }
6084         if (lock != NULL)
6085                 rw_wunlock(lock);
6086         pmap_invalidate_all(pmap);
6087         PMAP_UNLOCK(pmap);
6088         vm_page_free_pages_toq(&free, true);
6089 }
6090
6091 static boolean_t
6092 pmap_page_test_mappings(vm_page_t m, boolean_t accessed, boolean_t modified)
6093 {
6094         struct rwlock *lock;
6095         pv_entry_t pv;
6096         struct md_page *pvh;
6097         pt_entry_t *pte, mask;
6098         pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6099         pmap_t pmap;
6100         int md_gen, pvh_gen;
6101         boolean_t rv;
6102
6103         rv = FALSE;
6104         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6105         rw_rlock(lock);
6106 restart:
6107         TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6108                 pmap = PV_PMAP(pv);
6109                 if (!PMAP_TRYLOCK(pmap)) {
6110                         md_gen = m->md.pv_gen;
6111                         rw_runlock(lock);
6112                         PMAP_LOCK(pmap);
6113                         rw_rlock(lock);
6114                         if (md_gen != m->md.pv_gen) {
6115                                 PMAP_UNLOCK(pmap);
6116                                 goto restart;
6117                         }
6118                 }
6119                 pte = pmap_pte(pmap, pv->pv_va);
6120                 mask = 0;
6121                 if (modified) {
6122                         PG_M = pmap_modified_bit(pmap);
6123                         PG_RW = pmap_rw_bit(pmap);
6124                         mask |= PG_RW | PG_M;
6125                 }
6126                 if (accessed) {
6127                         PG_A = pmap_accessed_bit(pmap);
6128                         PG_V = pmap_valid_bit(pmap);
6129                         mask |= PG_V | PG_A;
6130                 }
6131                 rv = (*pte & mask) == mask;
6132                 PMAP_UNLOCK(pmap);
6133                 if (rv)
6134                         goto out;
6135         }
6136         if ((m->flags & PG_FICTITIOUS) == 0) {
6137                 pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
6138                 TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
6139                         pmap = PV_PMAP(pv);
6140                         if (!PMAP_TRYLOCK(pmap)) {
6141                                 md_gen = m->md.pv_gen;
6142                                 pvh_gen = pvh->pv_gen;
6143                                 rw_runlock(lock);
6144                                 PMAP_LOCK(pmap);
6145                                 rw_rlock(lock);
6146                                 if (md_gen != m->md.pv_gen ||
6147                                     pvh_gen != pvh->pv_gen) {
6148                                         PMAP_UNLOCK(pmap);
6149                                         goto restart;
6150                                 }
6151                         }
6152                         pte = pmap_pde(pmap, pv->pv_va);
6153                         mask = 0;
6154                         if (modified) {
6155                                 PG_M = pmap_modified_bit(pmap);
6156                                 PG_RW = pmap_rw_bit(pmap);
6157                                 mask |= PG_RW | PG_M;
6158                         }
6159                         if (accessed) {
6160                                 PG_A = pmap_accessed_bit(pmap);
6161                                 PG_V = pmap_valid_bit(pmap);
6162                                 mask |= PG_V | PG_A;
6163                         }
6164                         rv = (*pte & mask) == mask;
6165                         PMAP_UNLOCK(pmap);
6166                         if (rv)
6167                                 goto out;
6168                 }
6169         }
6170 out:
6171         rw_runlock(lock);
6172         return (rv);
6173 }
6174
6175 /*
6176  *      pmap_is_modified:
6177  *
6178  *      Return whether or not the specified physical page was modified
6179  *      in any physical maps.
6180  */
6181 boolean_t
6182 pmap_is_modified(vm_page_t m)
6183 {
6184
6185         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6186             ("pmap_is_modified: page %p is not managed", m));
6187
6188         /*
6189          * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6190          * concurrently set while the object is locked.  Thus, if PGA_WRITEABLE
6191          * is clear, no PTEs can have PG_M set.
6192          */
6193         VM_OBJECT_ASSERT_WLOCKED(m->object);
6194         if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6195                 return (FALSE);
6196         return (pmap_page_test_mappings(m, FALSE, TRUE));
6197 }
6198
6199 /*
6200  *      pmap_is_prefaultable:
6201  *
6202  *      Return whether or not the specified virtual address is eligible
6203  *      for prefault.
6204  */
6205 boolean_t
6206 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
6207 {
6208         pd_entry_t *pde;
6209         pt_entry_t *pte, PG_V;
6210         boolean_t rv;
6211
6212         PG_V = pmap_valid_bit(pmap);
6213         rv = FALSE;
6214         PMAP_LOCK(pmap);
6215         pde = pmap_pde(pmap, addr);
6216         if (pde != NULL && (*pde & (PG_PS | PG_V)) == PG_V) {
6217                 pte = pmap_pde_to_pte(pde, addr);
6218                 rv = (*pte & PG_V) == 0;
6219         }
6220         PMAP_UNLOCK(pmap);
6221         return (rv);
6222 }
6223
6224 /*
6225  *      pmap_is_referenced:
6226  *
6227  *      Return whether or not the specified physical page was referenced
6228  *      in any physical maps.
6229  */
6230 boolean_t
6231 pmap_is_referenced(vm_page_t m)
6232 {
6233
6234         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6235             ("pmap_is_referenced: page %p is not managed", m));
6236         return (pmap_page_test_mappings(m, TRUE, FALSE));
6237 }
6238
6239 /*
6240  * Clear the write and modified bits in each of the given page's mappings.
6241  */
6242 void
6243 pmap_remove_write(vm_page_t m)
6244 {
6245         struct md_page *pvh;
6246         pmap_t pmap;
6247         struct rwlock *lock;
6248         pv_entry_t next_pv, pv;
6249         pd_entry_t *pde;
6250         pt_entry_t oldpte, *pte, PG_M, PG_RW;
6251         vm_offset_t va;
6252         int pvh_gen, md_gen;
6253
6254         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6255             ("pmap_remove_write: page %p is not managed", m));
6256
6257         /*
6258          * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
6259          * set by another thread while the object is locked.  Thus,
6260          * if PGA_WRITEABLE is clear, no page table entries need updating.
6261          */
6262         VM_OBJECT_ASSERT_WLOCKED(m->object);
6263         if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
6264                 return;
6265         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6266         pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6267             pa_to_pvh(VM_PAGE_TO_PHYS(m));
6268 retry_pv_loop:
6269         rw_wlock(lock);
6270         TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6271                 pmap = PV_PMAP(pv);
6272                 if (!PMAP_TRYLOCK(pmap)) {
6273                         pvh_gen = pvh->pv_gen;
6274                         rw_wunlock(lock);
6275                         PMAP_LOCK(pmap);
6276                         rw_wlock(lock);
6277                         if (pvh_gen != pvh->pv_gen) {
6278                                 PMAP_UNLOCK(pmap);
6279                                 rw_wunlock(lock);
6280                                 goto retry_pv_loop;
6281                         }
6282                 }
6283                 PG_RW = pmap_rw_bit(pmap);
6284                 va = pv->pv_va;
6285                 pde = pmap_pde(pmap, va);
6286                 if ((*pde & PG_RW) != 0)
6287                         (void)pmap_demote_pde_locked(pmap, pde, va, &lock);
6288                 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6289                     ("inconsistent pv lock %p %p for page %p",
6290                     lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6291                 PMAP_UNLOCK(pmap);
6292         }
6293         TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6294                 pmap = PV_PMAP(pv);
6295                 if (!PMAP_TRYLOCK(pmap)) {
6296                         pvh_gen = pvh->pv_gen;
6297                         md_gen = m->md.pv_gen;
6298                         rw_wunlock(lock);
6299                         PMAP_LOCK(pmap);
6300                         rw_wlock(lock);
6301                         if (pvh_gen != pvh->pv_gen ||
6302                             md_gen != m->md.pv_gen) {
6303                                 PMAP_UNLOCK(pmap);
6304                                 rw_wunlock(lock);
6305                                 goto retry_pv_loop;
6306                         }
6307                 }
6308                 PG_M = pmap_modified_bit(pmap);
6309                 PG_RW = pmap_rw_bit(pmap);
6310                 pde = pmap_pde(pmap, pv->pv_va);
6311                 KASSERT((*pde & PG_PS) == 0,
6312                     ("pmap_remove_write: found a 2mpage in page %p's pv list",
6313                     m));
6314                 pte = pmap_pde_to_pte(pde, pv->pv_va);
6315 retry:
6316                 oldpte = *pte;
6317                 if (oldpte & PG_RW) {
6318                         if (!atomic_cmpset_long(pte, oldpte, oldpte &
6319                             ~(PG_RW | PG_M)))
6320                                 goto retry;
6321                         if ((oldpte & PG_M) != 0)
6322                                 vm_page_dirty(m);
6323                         pmap_invalidate_page(pmap, pv->pv_va);
6324                 }
6325                 PMAP_UNLOCK(pmap);
6326         }
6327         rw_wunlock(lock);
6328         vm_page_aflag_clear(m, PGA_WRITEABLE);
6329         pmap_delayed_invl_wait(m);
6330 }
6331
6332 static __inline boolean_t
6333 safe_to_clear_referenced(pmap_t pmap, pt_entry_t pte)
6334 {
6335
6336         if (!pmap_emulate_ad_bits(pmap))
6337                 return (TRUE);
6338
6339         KASSERT(pmap->pm_type == PT_EPT, ("invalid pm_type %d", pmap->pm_type));
6340
6341         /*
6342          * XWR = 010 or 110 will cause an unconditional EPT misconfiguration
6343          * so we don't let the referenced (aka EPT_PG_READ) bit to be cleared
6344          * if the EPT_PG_WRITE bit is set.
6345          */
6346         if ((pte & EPT_PG_WRITE) != 0)
6347                 return (FALSE);
6348
6349         /*
6350          * XWR = 100 is allowed only if the PMAP_SUPPORTS_EXEC_ONLY is set.
6351          */
6352         if ((pte & EPT_PG_EXECUTE) == 0 ||
6353             ((pmap->pm_flags & PMAP_SUPPORTS_EXEC_ONLY) != 0))
6354                 return (TRUE);
6355         else
6356                 return (FALSE);
6357 }
6358
6359 /*
6360  *      pmap_ts_referenced:
6361  *
6362  *      Return a count of reference bits for a page, clearing those bits.
6363  *      It is not necessary for every reference bit to be cleared, but it
6364  *      is necessary that 0 only be returned when there are truly no
6365  *      reference bits set.
6366  *
6367  *      As an optimization, update the page's dirty field if a modified bit is
6368  *      found while counting reference bits.  This opportunistic update can be
6369  *      performed at low cost and can eliminate the need for some future calls
6370  *      to pmap_is_modified().  However, since this function stops after
6371  *      finding PMAP_TS_REFERENCED_MAX reference bits, it may not detect some
6372  *      dirty pages.  Those dirty pages will only be detected by a future call
6373  *      to pmap_is_modified().
6374  *
6375  *      A DI block is not needed within this function, because
6376  *      invalidations are performed before the PV list lock is
6377  *      released.
6378  */
6379 int
6380 pmap_ts_referenced(vm_page_t m)
6381 {
6382         struct md_page *pvh;
6383         pv_entry_t pv, pvf;
6384         pmap_t pmap;
6385         struct rwlock *lock;
6386         pd_entry_t oldpde, *pde;
6387         pt_entry_t *pte, PG_A, PG_M, PG_RW;
6388         vm_offset_t va;
6389         vm_paddr_t pa;
6390         int cleared, md_gen, not_cleared, pvh_gen;
6391         struct spglist free;
6392         boolean_t demoted;
6393
6394         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6395             ("pmap_ts_referenced: page %p is not managed", m));
6396         SLIST_INIT(&free);
6397         cleared = 0;
6398         pa = VM_PAGE_TO_PHYS(m);
6399         lock = PHYS_TO_PV_LIST_LOCK(pa);
6400         pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy : pa_to_pvh(pa);
6401         rw_wlock(lock);
6402 retry:
6403         not_cleared = 0;
6404         if ((pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
6405                 goto small_mappings;
6406         pv = pvf;
6407         do {
6408                 if (pvf == NULL)
6409                         pvf = pv;
6410                 pmap = PV_PMAP(pv);
6411                 if (!PMAP_TRYLOCK(pmap)) {
6412                         pvh_gen = pvh->pv_gen;
6413                         rw_wunlock(lock);
6414                         PMAP_LOCK(pmap);
6415                         rw_wlock(lock);
6416                         if (pvh_gen != pvh->pv_gen) {
6417                                 PMAP_UNLOCK(pmap);
6418                                 goto retry;
6419                         }
6420                 }
6421                 PG_A = pmap_accessed_bit(pmap);
6422                 PG_M = pmap_modified_bit(pmap);
6423                 PG_RW = pmap_rw_bit(pmap);
6424                 va = pv->pv_va;
6425                 pde = pmap_pde(pmap, pv->pv_va);
6426                 oldpde = *pde;
6427                 if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6428                         /*
6429                          * Although "oldpde" is mapping a 2MB page, because
6430                          * this function is called at a 4KB page granularity,
6431                          * we only update the 4KB page under test.
6432                          */
6433                         vm_page_dirty(m);
6434                 }
6435                 if ((oldpde & PG_A) != 0) {
6436                         /*
6437                          * Since this reference bit is shared by 512 4KB
6438                          * pages, it should not be cleared every time it is
6439                          * tested.  Apply a simple "hash" function on the
6440                          * physical page number, the virtual superpage number,
6441                          * and the pmap address to select one 4KB page out of
6442                          * the 512 on which testing the reference bit will
6443                          * result in clearing that reference bit.  This
6444                          * function is designed to avoid the selection of the
6445                          * same 4KB page for every 2MB page mapping.
6446                          *
6447                          * On demotion, a mapping that hasn't been referenced
6448                          * is simply destroyed.  To avoid the possibility of a
6449                          * subsequent page fault on a demoted wired mapping,
6450                          * always leave its reference bit set.  Moreover,
6451                          * since the superpage is wired, the current state of
6452                          * its reference bit won't affect page replacement.
6453                          */
6454                         if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
6455                             (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
6456                             (oldpde & PG_W) == 0) {
6457                                 if (safe_to_clear_referenced(pmap, oldpde)) {
6458                                         atomic_clear_long(pde, PG_A);
6459                                         pmap_invalidate_page(pmap, pv->pv_va);
6460                                         demoted = FALSE;
6461                                 } else if (pmap_demote_pde_locked(pmap, pde,
6462                                     pv->pv_va, &lock)) {
6463                                         /*
6464                                          * Remove the mapping to a single page
6465                                          * so that a subsequent access may
6466                                          * repromote.  Since the underlying
6467                                          * page table page is fully populated,
6468                                          * this removal never frees a page
6469                                          * table page.
6470                                          */
6471                                         demoted = TRUE;
6472                                         va += VM_PAGE_TO_PHYS(m) - (oldpde &
6473                                             PG_PS_FRAME);
6474                                         pte = pmap_pde_to_pte(pde, va);
6475                                         pmap_remove_pte(pmap, pte, va, *pde,
6476                                             NULL, &lock);
6477                                         pmap_invalidate_page(pmap, va);
6478                                 } else
6479                                         demoted = TRUE;
6480
6481                                 if (demoted) {
6482                                         /*
6483                                          * The superpage mapping was removed
6484                                          * entirely and therefore 'pv' is no
6485                                          * longer valid.
6486                                          */
6487                                         if (pvf == pv)
6488                                                 pvf = NULL;
6489                                         pv = NULL;
6490                                 }
6491                                 cleared++;
6492                                 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6493                                     ("inconsistent pv lock %p %p for page %p",
6494                                     lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6495                         } else
6496                                 not_cleared++;
6497                 }
6498                 PMAP_UNLOCK(pmap);
6499                 /* Rotate the PV list if it has more than one entry. */
6500                 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6501                         TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
6502                         TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
6503                         pvh->pv_gen++;
6504                 }
6505                 if (cleared + not_cleared >= PMAP_TS_REFERENCED_MAX)
6506                         goto out;
6507         } while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
6508 small_mappings:
6509         if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
6510                 goto out;
6511         pv = pvf;
6512         do {
6513                 if (pvf == NULL)
6514                         pvf = pv;
6515                 pmap = PV_PMAP(pv);
6516                 if (!PMAP_TRYLOCK(pmap)) {
6517                         pvh_gen = pvh->pv_gen;
6518                         md_gen = m->md.pv_gen;
6519                         rw_wunlock(lock);
6520                         PMAP_LOCK(pmap);
6521                         rw_wlock(lock);
6522                         if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6523                                 PMAP_UNLOCK(pmap);
6524                                 goto retry;
6525                         }
6526                 }
6527                 PG_A = pmap_accessed_bit(pmap);
6528                 PG_M = pmap_modified_bit(pmap);
6529                 PG_RW = pmap_rw_bit(pmap);
6530                 pde = pmap_pde(pmap, pv->pv_va);
6531                 KASSERT((*pde & PG_PS) == 0,
6532                     ("pmap_ts_referenced: found a 2mpage in page %p's pv list",
6533                     m));
6534                 pte = pmap_pde_to_pte(pde, pv->pv_va);
6535                 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
6536                         vm_page_dirty(m);
6537                 if ((*pte & PG_A) != 0) {
6538                         if (safe_to_clear_referenced(pmap, *pte)) {
6539                                 atomic_clear_long(pte, PG_A);
6540                                 pmap_invalidate_page(pmap, pv->pv_va);
6541                                 cleared++;
6542                         } else if ((*pte & PG_W) == 0) {
6543                                 /*
6544                                  * Wired pages cannot be paged out so
6545                                  * doing accessed bit emulation for
6546                                  * them is wasted effort. We do the
6547                                  * hard work for unwired pages only.
6548                                  */
6549                                 pmap_remove_pte(pmap, pte, pv->pv_va,
6550                                     *pde, &free, &lock);
6551                                 pmap_invalidate_page(pmap, pv->pv_va);
6552                                 cleared++;
6553                                 if (pvf == pv)
6554                                         pvf = NULL;
6555                                 pv = NULL;
6556                                 KASSERT(lock == VM_PAGE_TO_PV_LIST_LOCK(m),
6557                                     ("inconsistent pv lock %p %p for page %p",
6558                                     lock, VM_PAGE_TO_PV_LIST_LOCK(m), m));
6559                         } else
6560                                 not_cleared++;
6561                 }
6562                 PMAP_UNLOCK(pmap);
6563                 /* Rotate the PV list if it has more than one entry. */
6564                 if (pv != NULL && TAILQ_NEXT(pv, pv_next) != NULL) {
6565                         TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
6566                         TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
6567                         m->md.pv_gen++;
6568                 }
6569         } while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && cleared +
6570             not_cleared < PMAP_TS_REFERENCED_MAX);
6571 out:
6572         rw_wunlock(lock);
6573         vm_page_free_pages_toq(&free, true);
6574         return (cleared + not_cleared);
6575 }
6576
6577 /*
6578  *      Apply the given advice to the specified range of addresses within the
6579  *      given pmap.  Depending on the advice, clear the referenced and/or
6580  *      modified flags in each mapping and set the mapped page's dirty field.
6581  */
6582 void
6583 pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
6584 {
6585         struct rwlock *lock;
6586         pml4_entry_t *pml4e;
6587         pdp_entry_t *pdpe;
6588         pd_entry_t oldpde, *pde;
6589         pt_entry_t *pte, PG_A, PG_G, PG_M, PG_RW, PG_V;
6590         vm_offset_t va, va_next;
6591         vm_page_t m;
6592         boolean_t anychanged;
6593
6594         if (advice != MADV_DONTNEED && advice != MADV_FREE)
6595                 return;
6596
6597         /*
6598          * A/D bit emulation requires an alternate code path when clearing
6599          * the modified and accessed bits below. Since this function is
6600          * advisory in nature we skip it entirely for pmaps that require
6601          * A/D bit emulation.
6602          */
6603         if (pmap_emulate_ad_bits(pmap))
6604                 return;
6605
6606         PG_A = pmap_accessed_bit(pmap);
6607         PG_G = pmap_global_bit(pmap);
6608         PG_M = pmap_modified_bit(pmap);
6609         PG_V = pmap_valid_bit(pmap);
6610         PG_RW = pmap_rw_bit(pmap);
6611         anychanged = FALSE;
6612         pmap_delayed_invl_started();
6613         PMAP_LOCK(pmap);
6614         for (; sva < eva; sva = va_next) {
6615                 pml4e = pmap_pml4e(pmap, sva);
6616                 if ((*pml4e & PG_V) == 0) {
6617                         va_next = (sva + NBPML4) & ~PML4MASK;
6618                         if (va_next < sva)
6619                                 va_next = eva;
6620                         continue;
6621                 }
6622                 pdpe = pmap_pml4e_to_pdpe(pml4e, sva);
6623                 if ((*pdpe & PG_V) == 0) {
6624                         va_next = (sva + NBPDP) & ~PDPMASK;
6625                         if (va_next < sva)
6626                                 va_next = eva;
6627                         continue;
6628                 }
6629                 va_next = (sva + NBPDR) & ~PDRMASK;
6630                 if (va_next < sva)
6631                         va_next = eva;
6632                 pde = pmap_pdpe_to_pde(pdpe, sva);
6633                 oldpde = *pde;
6634                 if ((oldpde & PG_V) == 0)
6635                         continue;
6636                 else if ((oldpde & PG_PS) != 0) {
6637                         if ((oldpde & PG_MANAGED) == 0)
6638                                 continue;
6639                         lock = NULL;
6640                         if (!pmap_demote_pde_locked(pmap, pde, sva, &lock)) {
6641                                 if (lock != NULL)
6642                                         rw_wunlock(lock);
6643
6644                                 /*
6645                                  * The large page mapping was destroyed.
6646                                  */
6647                                 continue;
6648                         }
6649
6650                         /*
6651                          * Unless the page mappings are wired, remove the
6652                          * mapping to a single page so that a subsequent
6653                          * access may repromote.  Since the underlying page
6654                          * table page is fully populated, this removal never
6655                          * frees a page table page.
6656                          */
6657                         if ((oldpde & PG_W) == 0) {
6658                                 pte = pmap_pde_to_pte(pde, sva);
6659                                 KASSERT((*pte & PG_V) != 0,
6660                                     ("pmap_advise: invalid PTE"));
6661                                 pmap_remove_pte(pmap, pte, sva, *pde, NULL,
6662                                     &lock);
6663                                 anychanged = TRUE;
6664                         }
6665                         if (lock != NULL)
6666                                 rw_wunlock(lock);
6667                 }
6668                 if (va_next > eva)
6669                         va_next = eva;
6670                 va = va_next;
6671                 for (pte = pmap_pde_to_pte(pde, sva); sva != va_next; pte++,
6672                     sva += PAGE_SIZE) {
6673                         if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED | PG_V))
6674                                 goto maybe_invlrng;
6675                         else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6676                                 if (advice == MADV_DONTNEED) {
6677                                         /*
6678                                          * Future calls to pmap_is_modified()
6679                                          * can be avoided by making the page
6680                                          * dirty now.
6681                                          */
6682                                         m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
6683                                         vm_page_dirty(m);
6684                                 }
6685                                 atomic_clear_long(pte, PG_M | PG_A);
6686                         } else if ((*pte & PG_A) != 0)
6687                                 atomic_clear_long(pte, PG_A);
6688                         else
6689                                 goto maybe_invlrng;
6690
6691                         if ((*pte & PG_G) != 0) {
6692                                 if (va == va_next)
6693                                         va = sva;
6694                         } else
6695                                 anychanged = TRUE;
6696                         continue;
6697 maybe_invlrng:
6698                         if (va != va_next) {
6699                                 pmap_invalidate_range(pmap, va, sva);
6700                                 va = va_next;
6701                         }
6702                 }
6703                 if (va != va_next)
6704                         pmap_invalidate_range(pmap, va, sva);
6705         }
6706         if (anychanged)
6707                 pmap_invalidate_all(pmap);
6708         PMAP_UNLOCK(pmap);
6709         pmap_delayed_invl_finished();
6710 }
6711
6712 /*
6713  *      Clear the modify bits on the specified physical page.
6714  */
6715 void
6716 pmap_clear_modify(vm_page_t m)
6717 {
6718         struct md_page *pvh;
6719         pmap_t pmap;
6720         pv_entry_t next_pv, pv;
6721         pd_entry_t oldpde, *pde;
6722         pt_entry_t oldpte, *pte, PG_M, PG_RW, PG_V;
6723         struct rwlock *lock;
6724         vm_offset_t va;
6725         int md_gen, pvh_gen;
6726
6727         KASSERT((m->oflags & VPO_UNMANAGED) == 0,
6728             ("pmap_clear_modify: page %p is not managed", m));
6729         VM_OBJECT_ASSERT_WLOCKED(m->object);
6730         KASSERT(!vm_page_xbusied(m),
6731             ("pmap_clear_modify: page %p is exclusive busied", m));
6732
6733         /*
6734          * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
6735          * If the object containing the page is locked and the page is not
6736          * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
6737          */
6738         if ((m->aflags & PGA_WRITEABLE) == 0)
6739                 return;
6740         pvh = (m->flags & PG_FICTITIOUS) != 0 ? &pv_dummy :
6741             pa_to_pvh(VM_PAGE_TO_PHYS(m));
6742         lock = VM_PAGE_TO_PV_LIST_LOCK(m);
6743         rw_wlock(lock);
6744 restart:
6745         TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
6746                 pmap = PV_PMAP(pv);
6747                 if (!PMAP_TRYLOCK(pmap)) {
6748                         pvh_gen = pvh->pv_gen;
6749                         rw_wunlock(lock);
6750                         PMAP_LOCK(pmap);
6751                         rw_wlock(lock);
6752                         if (pvh_gen != pvh->pv_gen) {
6753                                 PMAP_UNLOCK(pmap);
6754                                 goto restart;
6755                         }
6756                 }
6757                 PG_M = pmap_modified_bit(pmap);
6758                 PG_V = pmap_valid_bit(pmap);
6759                 PG_RW = pmap_rw_bit(pmap);
6760                 va = pv->pv_va;
6761                 pde = pmap_pde(pmap, va);
6762                 oldpde = *pde;
6763                 if ((oldpde & PG_RW) != 0) {
6764                         if (pmap_demote_pde_locked(pmap, pde, va, &lock)) {
6765                                 if ((oldpde & PG_W) == 0) {
6766                                         /*
6767                                          * Write protect the mapping to a
6768                                          * single page so that a subsequent
6769                                          * write access may repromote.
6770                                          */
6771                                         va += VM_PAGE_TO_PHYS(m) - (oldpde &
6772                                             PG_PS_FRAME);
6773                                         pte = pmap_pde_to_pte(pde, va);
6774                                         oldpte = *pte;
6775                                         if ((oldpte & PG_V) != 0) {
6776                                                 while (!atomic_cmpset_long(pte,
6777                                                     oldpte,
6778                                                     oldpte & ~(PG_M | PG_RW)))
6779                                                         oldpte = *pte;
6780                                                 vm_page_dirty(m);
6781                                                 pmap_invalidate_page(pmap, va);
6782                                         }
6783                                 }
6784                         }
6785                 }
6786                 PMAP_UNLOCK(pmap);
6787         }
6788         TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
6789                 pmap = PV_PMAP(pv);
6790                 if (!PMAP_TRYLOCK(pmap)) {
6791                         md_gen = m->md.pv_gen;
6792                         pvh_gen = pvh->pv_gen;
6793                         rw_wunlock(lock);
6794                         PMAP_LOCK(pmap);
6795                         rw_wlock(lock);
6796                         if (pvh_gen != pvh->pv_gen || md_gen != m->md.pv_gen) {
6797                                 PMAP_UNLOCK(pmap);
6798                                 goto restart;
6799                         }
6800                 }
6801                 PG_M = pmap_modified_bit(pmap);
6802                 PG_RW = pmap_rw_bit(pmap);
6803                 pde = pmap_pde(pmap, pv->pv_va);
6804                 KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
6805                     " a 2mpage in page %p's pv list", m));
6806                 pte = pmap_pde_to_pte(pde, pv->pv_va);
6807                 if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
6808                         atomic_clear_long(pte, PG_M);
6809                         pmap_invalidate_page(pmap, pv->pv_va);
6810                 }
6811                 PMAP_UNLOCK(pmap);
6812         }
6813         rw_wunlock(lock);
6814 }
6815
6816 /*
6817  * Miscellaneous support routines follow
6818  */
6819
6820 /* Adjust the cache mode for a 4KB page mapped via a PTE. */
6821 static __inline void
6822 pmap_pte_attr(pt_entry_t *pte, int cache_bits, int mask)
6823 {
6824         u_int opte, npte;
6825
6826         /*
6827          * The cache mode bits are all in the low 32-bits of the
6828          * PTE, so we can just spin on updating the low 32-bits.
6829          */
6830         do {
6831                 opte = *(u_int *)pte;
6832                 npte = opte & ~mask;
6833                 npte |= cache_bits;
6834         } while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
6835 }
6836
6837 /* Adjust the cache mode for a 2MB page mapped via a PDE. */
6838 static __inline void
6839 pmap_pde_attr(pd_entry_t *pde, int cache_bits, int mask)
6840 {
6841         u_int opde, npde;
6842
6843         /*
6844          * The cache mode bits are all in the low 32-bits of the
6845          * PDE, so we can just spin on updating the low 32-bits.
6846          */
6847         do {
6848                 opde = *(u_int *)pde;
6849                 npde = opde & ~mask;
6850                 npde |= cache_bits;
6851         } while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
6852 }
6853
6854 /*
6855  * Map a set of physical memory pages into the kernel virtual
6856  * address space. Return a pointer to where it is mapped. This
6857  * routine is intended to be used for mapping device memory,
6858  * NOT real memory.
6859  */
6860 void *
6861 pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
6862 {
6863         struct pmap_preinit_mapping *ppim;
6864         vm_offset_t va, offset;
6865         vm_size_t tmpsize;
6866         int i;
6867
6868         offset = pa & PAGE_MASK;
6869         size = round_page(offset + size);
6870         pa = trunc_page(pa);
6871
6872         if (!pmap_initialized) {
6873                 va = 0;
6874                 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6875                         ppim = pmap_preinit_mapping + i;
6876                         if (ppim->va == 0) {
6877                                 ppim->pa = pa;
6878                                 ppim->sz = size;
6879                                 ppim->mode = mode;
6880                                 ppim->va = virtual_avail;
6881                                 virtual_avail += size;
6882                                 va = ppim->va;
6883                                 break;
6884                         }
6885                 }
6886                 if (va == 0)
6887                         panic("%s: too many preinit mappings", __func__);
6888         } else {
6889                 /*
6890                  * If we have a preinit mapping, re-use it.
6891                  */
6892                 for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6893                         ppim = pmap_preinit_mapping + i;
6894                         if (ppim->pa == pa && ppim->sz == size &&
6895                             ppim->mode == mode)
6896                                 return ((void *)(ppim->va + offset));
6897                 }
6898                 /*
6899                  * If the specified range of physical addresses fits within
6900                  * the direct map window, use the direct map.
6901                  */
6902                 if (pa < dmaplimit && pa + size < dmaplimit) {
6903                         va = PHYS_TO_DMAP(pa);
6904                         if (!pmap_change_attr(va, size, mode))
6905                                 return ((void *)(va + offset));
6906                 }
6907                 va = kva_alloc(size);
6908                 if (va == 0)
6909                         panic("%s: Couldn't allocate KVA", __func__);
6910         }
6911         for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
6912                 pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
6913         pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
6914         pmap_invalidate_cache_range(va, va + tmpsize, FALSE);
6915         return ((void *)(va + offset));
6916 }
6917
6918 void *
6919 pmap_mapdev(vm_paddr_t pa, vm_size_t size)
6920 {
6921
6922         return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
6923 }
6924
6925 void *
6926 pmap_mapbios(vm_paddr_t pa, vm_size_t size)
6927 {
6928
6929         return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
6930 }
6931
6932 void
6933 pmap_unmapdev(vm_offset_t va, vm_size_t size)
6934 {
6935         struct pmap_preinit_mapping *ppim;
6936         vm_offset_t offset;
6937         int i;
6938
6939         /* If we gave a direct map region in pmap_mapdev, do nothing */
6940         if (va >= DMAP_MIN_ADDRESS && va < DMAP_MAX_ADDRESS)
6941                 return;
6942         offset = va & PAGE_MASK;
6943         size = round_page(offset + size);
6944         va = trunc_page(va);
6945         for (i = 0; i < PMAP_PREINIT_MAPPING_COUNT; i++) {
6946                 ppim = pmap_preinit_mapping + i;
6947                 if (ppim->va == va && ppim->sz == size) {
6948                         if (pmap_initialized)
6949                                 return;
6950                         ppim->pa = 0;
6951                         ppim->va = 0;
6952                         ppim->sz = 0;
6953                         ppim->mode = 0;
6954                         if (va + size == virtual_avail)
6955                                 virtual_avail = va;
6956                         return;
6957                 }
6958         }
6959         if (pmap_initialized)
6960                 kva_free(va, size);
6961 }
6962
6963 /*
6964  * Tries to demote a 1GB page mapping.
6965  */
6966 static boolean_t
6967 pmap_demote_pdpe(pmap_t pmap, pdp_entry_t *pdpe, vm_offset_t va)
6968 {
6969         pdp_entry_t newpdpe, oldpdpe;
6970         pd_entry_t *firstpde, newpde, *pde;
6971         pt_entry_t PG_A, PG_M, PG_RW, PG_V;
6972         vm_paddr_t pdpgpa;
6973         vm_page_t pdpg;
6974
6975         PG_A = pmap_accessed_bit(pmap);
6976         PG_M = pmap_modified_bit(pmap);
6977         PG_V = pmap_valid_bit(pmap);
6978         PG_RW = pmap_rw_bit(pmap);
6979
6980         PMAP_LOCK_ASSERT(pmap, MA_OWNED);
6981         oldpdpe = *pdpe;
6982         KASSERT((oldpdpe & (PG_PS | PG_V)) == (PG_PS | PG_V),
6983             ("pmap_demote_pdpe: oldpdpe is missing PG_PS and/or PG_V"));
6984         if ((pdpg = vm_page_alloc(NULL, va >> PDPSHIFT, VM_ALLOC_INTERRUPT |
6985             VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
6986                 CTR2(KTR_PMAP, "pmap_demote_pdpe: failure for va %#lx"
6987                     " in pmap %p", va, pmap);
6988                 return (FALSE);
6989         }
6990         pdpgpa = VM_PAGE_TO_PHYS(pdpg);
6991         firstpde = (pd_entry_t *)PHYS_TO_DMAP(pdpgpa);
6992         newpdpe = pdpgpa | PG_M | PG_A | (oldpdpe & PG_U) | PG_RW | PG_V;
6993         KASSERT((oldpdpe & PG_A) != 0,
6994             ("pmap_demote_pdpe: oldpdpe is missing PG_A"));
6995         KASSERT((oldpdpe & (PG_M | PG_RW)) != PG_RW,
6996             ("pmap_demote_pdpe: oldpdpe is missing PG_M"));
6997         newpde = oldpdpe;
6998
6999         /*
7000          * Initialize the page directory page.
7001          */
7002         for (pde = firstpde; pde < firstpde + NPDEPG; pde++) {
7003                 *pde = newpde;
7004                 newpde += NBPDR;
7005         }
7006
7007         /*
7008          * Demote the mapping.
7009          */
7010         *pdpe = newpdpe;
7011
7012         /*
7013          * Invalidate a stale recursive mapping of the page directory page.
7014          */
7015         pmap_invalidate_page(pmap, (vm_offset_t)vtopde(va));
7016
7017         pmap_pdpe_demotions++;
7018         CTR2(KTR_PMAP, "pmap_demote_pdpe: success for va %#lx"
7019             " in pmap %p", va, pmap);
7020         return (TRUE);
7021 }
7022
7023 /*
7024  * Sets the memory attribute for the specified page.
7025  */
7026 void
7027 pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
7028 {
7029
7030         m->md.pat_mode = ma;
7031
7032         /*
7033          * If "m" is a normal page, update its direct mapping.  This update
7034          * can be relied upon to perform any cache operations that are
7035          * required for data coherence.
7036          */
7037         if ((m->flags & PG_FICTITIOUS) == 0 &&
7038             pmap_change_attr(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)), PAGE_SIZE,
7039             m->md.pat_mode))
7040                 panic("memory attribute change on the direct map failed");
7041 }
7042
7043 /*
7044  * Changes the specified virtual address range's memory type to that given by
7045  * the parameter "mode".  The specified virtual address range must be
7046  * completely contained within either the direct map or the kernel map.  If
7047  * the virtual address range is contained within the kernel map, then the
7048  * memory type for each of the corresponding ranges of the direct map is also
7049  * changed.  (The corresponding ranges of the direct map are those ranges that
7050  * map the same physical pages as the specified virtual address range.)  These
7051  * changes to the direct map are necessary because Intel describes the
7052  * behavior of their processors as "undefined" if two or more mappings to the
7053  * same physical page have different memory types.
7054  *
7055  * Returns zero if the change completed successfully, and either EINVAL or
7056  * ENOMEM if the change failed.  Specifically, EINVAL is returned if some part
7057  * of the virtual address range was not mapped, and ENOMEM is returned if
7058  * there was insufficient memory available to complete the change.  In the
7059  * latter case, the memory type may have been changed on some part of the
7060  * virtual address range or the direct map.
7061  */
7062 int
7063 pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
7064 {
7065         int error;
7066
7067         PMAP_LOCK(kernel_pmap);
7068         error = pmap_change_attr_locked(va, size, mode);
7069         PMAP_UNLOCK(kernel_pmap);
7070         return (error);
7071 }
7072
7073 static int
7074 pmap_change_attr_locked(vm_offset_t va, vm_size_t size, int mode)
7075 {
7076         vm_offset_t base, offset, tmpva;
7077         vm_paddr_t pa_start, pa_end, pa_end1;
7078         pdp_entry_t *pdpe;
7079         pd_entry_t *pde;
7080         pt_entry_t *pte;
7081         int cache_bits_pte, cache_bits_pde, error;
7082         boolean_t changed;
7083
7084         PMAP_LOCK_ASSERT(kernel_pmap, MA_OWNED);
7085         base = trunc_page(va);
7086         offset = va & PAGE_MASK;
7087         size = round_page(offset + size);
7088
7089         /*
7090          * Only supported on kernel virtual addresses, including the direct
7091          * map but excluding the recursive map.
7092          */
7093         if (base < DMAP_MIN_ADDRESS)
7094                 return (EINVAL);
7095
7096         cache_bits_pde = pmap_cache_bits(kernel_pmap, mode, 1);
7097         cache_bits_pte = pmap_cache_bits(kernel_pmap, mode, 0);
7098         changed = FALSE;
7099
7100         /*
7101          * Pages that aren't mapped aren't supported.  Also break down 2MB pages
7102          * into 4KB pages if required.
7103          */
7104         for (tmpva = base; tmpva < base + size; ) {
7105                 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7106                 if (pdpe == NULL || *pdpe == 0)
7107                         return (EINVAL);
7108                 if (*pdpe & PG_PS) {
7109                         /*
7110                          * If the current 1GB page already has the required
7111                          * memory type, then we need not demote this page. Just
7112                          * increment tmpva to the next 1GB page frame.
7113                          */
7114                         if ((*pdpe & X86_PG_PDE_CACHE) == cache_bits_pde) {
7115                                 tmpva = trunc_1gpage(tmpva) + NBPDP;
7116                                 continue;
7117                         }
7118
7119                         /*
7120                          * If the current offset aligns with a 1GB page frame
7121                          * and there is at least 1GB left within the range, then
7122                          * we need not break down this page into 2MB pages.
7123                          */
7124                         if ((tmpva & PDPMASK) == 0 &&
7125                             tmpva + PDPMASK < base + size) {
7126                                 tmpva += NBPDP;
7127                                 continue;
7128                         }
7129                         if (!pmap_demote_pdpe(kernel_pmap, pdpe, tmpva))
7130                                 return (ENOMEM);
7131                 }
7132                 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7133                 if (*pde == 0)
7134                         return (EINVAL);
7135                 if (*pde & PG_PS) {
7136                         /*
7137                          * If the current 2MB page already has the required
7138                          * memory type, then we need not demote this page. Just
7139                          * increment tmpva to the next 2MB page frame.
7140                          */
7141                         if ((*pde & X86_PG_PDE_CACHE) == cache_bits_pde) {
7142                                 tmpva = trunc_2mpage(tmpva) + NBPDR;
7143                                 continue;
7144                         }
7145
7146                         /*
7147                          * If the current offset aligns with a 2MB page frame
7148                          * and there is at least 2MB left within the range, then
7149                          * we need not break down this page into 4KB pages.
7150                          */
7151                         if ((tmpva & PDRMASK) == 0 &&
7152                             tmpva + PDRMASK < base + size) {
7153                                 tmpva += NBPDR;
7154                                 continue;
7155                         }
7156                         if (!pmap_demote_pde(kernel_pmap, pde, tmpva))
7157                                 return (ENOMEM);
7158                 }
7159                 pte = pmap_pde_to_pte(pde, tmpva);
7160                 if (*pte == 0)
7161                         return (EINVAL);
7162                 tmpva += PAGE_SIZE;
7163         }
7164         error = 0;
7165
7166         /*
7167          * Ok, all the pages exist, so run through them updating their
7168          * cache mode if required.
7169          */
7170         pa_start = pa_end = 0;
7171         for (tmpva = base; tmpva < base + size; ) {
7172                 pdpe = pmap_pdpe(kernel_pmap, tmpva);
7173                 if (*pdpe & PG_PS) {
7174                         if ((*pdpe & X86_PG_PDE_CACHE) != cache_bits_pde) {
7175                                 pmap_pde_attr(pdpe, cache_bits_pde,
7176                                     X86_PG_PDE_CACHE);
7177                                 changed = TRUE;
7178                         }
7179                         if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7180                             (*pdpe & PG_PS_FRAME) < dmaplimit) {
7181                                 if (pa_start == pa_end) {
7182                                         /* Start physical address run. */
7183                                         pa_start = *pdpe & PG_PS_FRAME;
7184                                         pa_end = pa_start + NBPDP;
7185                                 } else if (pa_end == (*pdpe & PG_PS_FRAME))
7186                                         pa_end += NBPDP;
7187                                 else {
7188                                         /* Run ended, update direct map. */
7189                                         error = pmap_change_attr_locked(
7190                                             PHYS_TO_DMAP(pa_start),
7191                                             pa_end - pa_start, mode);
7192                                         if (error != 0)
7193                                                 break;
7194                                         /* Start physical address run. */
7195                                         pa_start = *pdpe & PG_PS_FRAME;
7196                                         pa_end = pa_start + NBPDP;
7197                                 }
7198                         }
7199                         tmpva = trunc_1gpage(tmpva) + NBPDP;
7200                         continue;
7201                 }
7202                 pde = pmap_pdpe_to_pde(pdpe, tmpva);
7203                 if (*pde & PG_PS) {
7204                         if ((*pde & X86_PG_PDE_CACHE) != cache_bits_pde) {
7205                                 pmap_pde_attr(pde, cache_bits_pde,
7206                                     X86_PG_PDE_CACHE);
7207                                 changed = TRUE;
7208                         }
7209                         if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7210                             (*pde & PG_PS_FRAME) < dmaplimit) {
7211                                 if (pa_start == pa_end) {
7212                                         /* Start physical address run. */
7213                                         pa_start = *pde & PG_PS_FRAME;
7214                                         pa_end = pa_start + NBPDR;
7215                                 } else if (pa_end == (*pde & PG_PS_FRAME))
7216                                         pa_end += NBPDR;
7217                                 else {
7218                                         /* Run ended, update direct map. */
7219                                         error = pmap_change_attr_locked(
7220                                             PHYS_TO_DMAP(pa_start),
7221                                             pa_end - pa_start, mode);
7222                                         if (error != 0)
7223                                                 break;
7224                                         /* Start physical address run. */
7225                                         pa_start = *pde & PG_PS_FRAME;
7226                                         pa_end = pa_start + NBPDR;
7227                                 }
7228                         }
7229                         tmpva = trunc_2mpage(tmpva) + NBPDR;
7230                 } else {
7231                         pte = pmap_pde_to_pte(pde, tmpva);
7232                         if ((*pte & X86_PG_PTE_CACHE) != cache_bits_pte) {
7233                                 pmap_pte_attr(pte, cache_bits_pte,
7234                                     X86_PG_PTE_CACHE);
7235                                 changed = TRUE;
7236                         }
7237                         if (tmpva >= VM_MIN_KERNEL_ADDRESS &&
7238                             (*pte & PG_FRAME) < dmaplimit) {
7239                                 if (pa_start == pa_end) {
7240                                         /* Start physical address run. */
7241                                         pa_start = *pte & PG_FRAME;
7242                                         pa_end = pa_start + PAGE_SIZE;
7243                                 } else if (pa_end == (*pte & PG_FRAME))
7244                                         pa_end += PAGE_SIZE;
7245                                 else {
7246                                         /* Run ended, update direct map. */
7247                                         error = pmap_change_attr_locked(
7248                                             PHYS_TO_DMAP(pa_start),
7249                                             pa_end - pa_start, mode);
7250                                         if (error != 0)
7251                                                 break;
7252                                         /* Start physical address run. */
7253                                         pa_start = *pte & PG_FRAME;
7254                                         pa_end = pa_start + PAGE_SIZE;
7255                                 }
7256                         }
7257                         tmpva += PAGE_SIZE;
7258                 }
7259         }
7260         if (error == 0 && pa_start != pa_end && pa_start < dmaplimit) {
7261                 pa_end1 = MIN(pa_end, dmaplimit);
7262                 if (pa_start != pa_end1)
7263                         error = pmap_change_attr_locked(PHYS_TO_DMAP(pa_start),
7264                             pa_end1 - pa_start, mode);
7265         }
7266
7267         /*
7268          * Flush CPU caches if required to make sure any data isn't cached that
7269          * shouldn't be, etc.
7270          */
7271         if (changed) {
7272                 pmap_invalidate_range(kernel_pmap, base, tmpva);
7273                 pmap_invalidate_cache_range(base, tmpva, FALSE);
7274         }
7275         return (error);
7276 }
7277
7278 /*
7279  * Demotes any mapping within the direct map region that covers more than the
7280  * specified range of physical addresses.  This range's size must be a power
7281  * of two and its starting address must be a multiple of its size.  Since the
7282  * demotion does not change any attributes of the mapping, a TLB invalidation
7283  * is not mandatory.  The caller may, however, request a TLB invalidation.
7284  */
7285 void
7286 pmap_demote_DMAP(vm_paddr_t base, vm_size_t len, boolean_t invalidate)
7287 {
7288         pdp_entry_t *pdpe;
7289         pd_entry_t *pde;
7290         vm_offset_t va;
7291         boolean_t changed;
7292
7293         if (len == 0)
7294                 return;
7295         KASSERT(powerof2(len), ("pmap_demote_DMAP: len is not a power of 2"));
7296         KASSERT((base & (len - 1)) == 0,
7297             ("pmap_demote_DMAP: base is not a multiple of len"));
7298         if (len < NBPDP && base < dmaplimit) {
7299                 va = PHYS_TO_DMAP(base);
7300                 changed = FALSE;
7301                 PMAP_LOCK(kernel_pmap);
7302                 pdpe = pmap_pdpe(kernel_pmap, va);
7303                 if ((*pdpe & X86_PG_V) == 0)
7304                         panic("pmap_demote_DMAP: invalid PDPE");
7305                 if ((*pdpe & PG_PS) != 0) {
7306                         if (!pmap_demote_pdpe(kernel_pmap, pdpe, va))
7307                                 panic("pmap_demote_DMAP: PDPE failed");
7308                         changed = TRUE;
7309                 }
7310                 if (len < NBPDR) {
7311                         pde = pmap_pdpe_to_pde(pdpe, va);
7312                         if ((*pde & X86_PG_V) == 0)
7313                                 panic("pmap_demote_DMAP: invalid PDE");
7314                         if ((*pde & PG_PS) != 0) {
7315                                 if (!pmap_demote_pde(kernel_pmap, pde, va))
7316                                         panic("pmap_demote_DMAP: PDE failed");
7317                                 changed = TRUE;
7318                         }
7319                 }
7320                 if (changed && invalidate)
7321                         pmap_invalidate_page(kernel_pmap, va);
7322                 PMAP_UNLOCK(kernel_pmap);
7323         }
7324 }
7325
7326 /*
7327  * perform the pmap work for mincore
7328  */
7329 int
7330 pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
7331 {
7332         pd_entry_t *pdep;
7333         pt_entry_t pte, PG_A, PG_M, PG_RW, PG_V;
7334         vm_paddr_t pa;
7335         int val;
7336
7337         PG_A = pmap_accessed_bit(pmap);
7338         PG_M = pmap_modified_bit(pmap);
7339         PG_V = pmap_valid_bit(pmap);
7340         PG_RW = pmap_rw_bit(pmap);
7341
7342         PMAP_LOCK(pmap);
7343 retry:
7344         pdep = pmap_pde(pmap, addr);
7345         if (pdep != NULL && (*pdep & PG_V)) {
7346                 if (*pdep & PG_PS) {
7347                         pte = *pdep;
7348                         /* Compute the physical address of the 4KB page. */
7349                         pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
7350                             PG_FRAME;
7351                         val = MINCORE_SUPER;
7352                 } else {
7353                         pte = *pmap_pde_to_pte(pdep, addr);
7354                         pa = pte & PG_FRAME;
7355                         val = 0;
7356                 }
7357         } else {
7358                 pte = 0;
7359                 pa = 0;
7360                 val = 0;
7361         }
7362         if ((pte & PG_V) != 0) {
7363                 val |= MINCORE_INCORE;
7364                 if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
7365                         val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
7366                 if ((pte & PG_A) != 0)
7367                         val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
7368         }
7369         if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
7370             (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
7371             (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
7372                 /* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
7373                 if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
7374                         goto retry;
7375         } else
7376                 PA_UNLOCK_COND(*locked_pa);
7377         PMAP_UNLOCK(pmap);
7378         return (val);
7379 }
7380
7381 static uint64_t
7382 pmap_pcid_alloc(pmap_t pmap, u_int cpuid)
7383 {
7384         uint32_t gen, new_gen, pcid_next;
7385
7386         CRITICAL_ASSERT(curthread);
7387         gen = PCPU_GET(pcid_gen);
7388         if (pmap->pm_pcids[cpuid].pm_pcid == PMAP_PCID_KERN)
7389                 return (pti ? 0 : CR3_PCID_SAVE);
7390         if (pmap->pm_pcids[cpuid].pm_gen == gen)
7391                 return (CR3_PCID_SAVE);
7392         pcid_next = PCPU_GET(pcid_next);
7393         KASSERT((!pti && pcid_next <= PMAP_PCID_OVERMAX) ||
7394             (pti && pcid_next <= PMAP_PCID_OVERMAX_KERN),
7395             ("cpu %d pcid_next %#x", cpuid, pcid_next));
7396         if ((!pti && pcid_next == PMAP_PCID_OVERMAX) ||
7397             (pti && pcid_next == PMAP_PCID_OVERMAX_KERN)) {
7398                 new_gen = gen + 1;
7399                 if (new_gen == 0)
7400                         new_gen = 1;
7401                 PCPU_SET(pcid_gen, new_gen);
7402                 pcid_next = PMAP_PCID_KERN + 1;
7403         } else {
7404                 new_gen = gen;
7405         }
7406         pmap->pm_pcids[cpuid].pm_pcid = pcid_next;
7407         pmap->pm_pcids[cpuid].pm_gen = new_gen;
7408         PCPU_SET(pcid_next, pcid_next + 1);
7409         return (0);
7410 }
7411
7412 void
7413 pmap_activate_sw(struct thread *td)
7414 {
7415         pmap_t oldpmap, pmap;
7416         struct invpcid_descr d;
7417         uint64_t cached, cr3, kcr3, kern_pti_cached, rsp0, ucr3;
7418         register_t rflags;
7419         u_int cpuid;
7420         struct amd64tss *tssp;
7421
7422         rflags = 0;
7423         oldpmap = PCPU_GET(curpmap);
7424         pmap = vmspace_pmap(td->td_proc->p_vmspace);
7425         if (oldpmap == pmap)
7426                 return;
7427         cpuid = PCPU_GET(cpuid);
7428 #ifdef SMP
7429         CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
7430 #else
7431         CPU_SET(cpuid, &pmap->pm_active);
7432 #endif
7433         cr3 = rcr3();
7434         if (pmap_pcid_enabled) {
7435                 cached = pmap_pcid_alloc(pmap, cpuid);
7436                 KASSERT(pmap->pm_pcids[cpuid].pm_pcid >= 0 &&
7437                     pmap->pm_pcids[cpuid].pm_pcid < PMAP_PCID_OVERMAX,
7438                     ("pmap %p cpu %d pcid %#x", pmap, cpuid,
7439                     pmap->pm_pcids[cpuid].pm_pcid));
7440                 KASSERT(pmap->pm_pcids[cpuid].pm_pcid != PMAP_PCID_KERN ||
7441                     pmap == kernel_pmap,
7442                     ("non-kernel pmap thread %p pmap %p cpu %d pcid %#x",
7443                     td, pmap, cpuid, pmap->pm_pcids[cpuid].pm_pcid));
7444
7445                 /*
7446                  * If the INVPCID instruction is not available,
7447                  * invltlb_pcid_handler() is used for handle
7448                  * invalidate_all IPI, which checks for curpmap ==
7449                  * smp_tlb_pmap.  Below operations sequence has a
7450                  * window where %CR3 is loaded with the new pmap's
7451                  * PML4 address, but curpmap value is not yet updated.
7452                  * This causes invltlb IPI handler, called between the
7453                  * updates, to execute as NOP, which leaves stale TLB
7454                  * entries.
7455                  *
7456                  * Note that the most typical use of
7457                  * pmap_activate_sw(), from the context switch, is
7458                  * immune to this race, because interrupts are
7459                  * disabled (while the thread lock is owned), and IPI
7460                  * happends after curpmap is updated.  Protect other
7461                  * callers in a similar way, by disabling interrupts
7462                  * around the %cr3 register reload and curpmap
7463                  * assignment.
7464                  */
7465                 if (!invpcid_works)
7466                         rflags = intr_disable();
7467
7468                 kern_pti_cached = pti ? 0 : cached;
7469                 if (!kern_pti_cached || (cr3 & ~CR3_PCID_MASK) != pmap->pm_cr3) {
7470                         load_cr3(pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid |
7471                             kern_pti_cached);
7472                 }
7473                 PCPU_SET(curpmap, pmap);
7474                 if (pti) {
7475                         kcr3 = pmap->pm_cr3 | pmap->pm_pcids[cpuid].pm_pcid;
7476                         ucr3 = pmap->pm_ucr3 | pmap->pm_pcids[cpuid].pm_pcid |
7477                             PMAP_PCID_USER_PT;
7478
7479                         if (!cached && pmap->pm_ucr3 != PMAP_NO_CR3) {
7480                                 /*
7481                                  * Manually invalidate translations cached
7482                                  * from the user page table.  They are not
7483                                  * flushed by reload of cr3 with the kernel
7484                                  * page table pointer above.
7485                                  */
7486                                 if (invpcid_works) {
7487                                         d.pcid = PMAP_PCID_USER_PT |
7488                                             pmap->pm_pcids[cpuid].pm_pcid;
7489                                         d.pad = 0;
7490                                         d.addr = 0;
7491                                         invpcid(&d, INVPCID_CTX);
7492                                 } else {
7493                                         pmap_pti_pcid_invalidate(ucr3, kcr3);
7494                                 }
7495                         }
7496
7497                         PCPU_SET(kcr3, kcr3 | CR3_PCID_SAVE);
7498                         PCPU_SET(ucr3, ucr3 | CR3_PCID_SAVE);
7499                 }
7500                 if (!invpcid_works)
7501                         intr_restore(rflags);
7502                 if (cached)
7503                         PCPU_INC(pm_save_cnt);
7504         } else if (cr3 != pmap->pm_cr3) {
7505                 load_cr3(pmap->pm_cr3);
7506                 PCPU_SET(curpmap, pmap);
7507                 if (pti) {
7508                         PCPU_SET(kcr3, pmap->pm_cr3);
7509                         PCPU_SET(ucr3, pmap->pm_ucr3);
7510                 }
7511         }
7512         if (pmap->pm_ucr3 != PMAP_NO_CR3) {
7513                 rsp0 = ((vm_offset_t)PCPU_PTR(pti_stack) +
7514                     PC_PTI_STACK_SZ * sizeof(uint64_t)) & ~0xful;
7515                 tssp = PCPU_GET(tssp);
7516                 tssp->tss_rsp0 = rsp0;
7517         }
7518 #ifdef SMP
7519         CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
7520 #else
7521         CPU_CLR(cpuid, &oldpmap->pm_active);
7522 #endif
7523 }
7524
7525 void
7526 pmap_activate(struct thread *td)
7527 {
7528
7529         critical_enter();
7530         pmap_activate_sw(td);
7531         critical_exit();
7532 }
7533
7534 void
7535 pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
7536 {
7537 }
7538
7539 /*
7540  *      Increase the starting virtual address of the given mapping if a
7541  *      different alignment might result in more superpage mappings.
7542  */
7543 void
7544 pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
7545     vm_offset_t *addr, vm_size_t size)
7546 {
7547         vm_offset_t superpage_offset;
7548
7549         if (size < NBPDR)
7550                 return;
7551         if (object != NULL && (object->flags & OBJ_COLORED) != 0)
7552                 offset += ptoa(object->pg_color);
7553         superpage_offset = offset & PDRMASK;
7554         if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
7555             (*addr & PDRMASK) == superpage_offset)
7556                 return;
7557         if ((*addr & PDRMASK) < superpage_offset)
7558                 *addr = (*addr & ~PDRMASK) + superpage_offset;
7559         else
7560                 *addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
7561 }
7562
7563 #ifdef INVARIANTS
7564 static unsigned long num_dirty_emulations;
7565 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_dirty_emulations, CTLFLAG_RW,
7566              &num_dirty_emulations, 0, NULL);
7567
7568 static unsigned long num_accessed_emulations;
7569 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_accessed_emulations, CTLFLAG_RW,
7570              &num_accessed_emulations, 0, NULL);
7571
7572 static unsigned long num_superpage_accessed_emulations;
7573 SYSCTL_ULONG(_vm_pmap, OID_AUTO, num_superpage_accessed_emulations, CTLFLAG_RW,
7574              &num_superpage_accessed_emulations, 0, NULL);
7575
7576 static unsigned long ad_emulation_superpage_promotions;
7577 SYSCTL_ULONG(_vm_pmap, OID_AUTO, ad_emulation_superpage_promotions, CTLFLAG_RW,
7578              &ad_emulation_superpage_promotions, 0, NULL);
7579 #endif  /* INVARIANTS */
7580
7581 int
7582 pmap_emulate_accessed_dirty(pmap_t pmap, vm_offset_t va, int ftype)
7583 {
7584         int rv;
7585         struct rwlock *lock;
7586 #if VM_NRESERVLEVEL > 0
7587         vm_page_t m, mpte;
7588 #endif
7589         pd_entry_t *pde;
7590         pt_entry_t *pte, PG_A, PG_M, PG_RW, PG_V;
7591
7592         KASSERT(ftype == VM_PROT_READ || ftype == VM_PROT_WRITE,
7593             ("pmap_emulate_accessed_dirty: invalid fault type %d", ftype));
7594
7595         if (!pmap_emulate_ad_bits(pmap))
7596                 return (-1);
7597
7598         PG_A = pmap_accessed_bit(pmap);
7599         PG_M = pmap_modified_bit(pmap);
7600         PG_V = pmap_valid_bit(pmap);
7601         PG_RW = pmap_rw_bit(pmap);
7602
7603         rv = -1;
7604         lock = NULL;
7605         PMAP_LOCK(pmap);
7606
7607         pde = pmap_pde(pmap, va);
7608         if (pde == NULL || (*pde & PG_V) == 0)
7609                 goto done;
7610
7611         if ((*pde & PG_PS) != 0) {
7612                 if (ftype == VM_PROT_READ) {
7613 #ifdef INVARIANTS
7614                         atomic_add_long(&num_superpage_accessed_emulations, 1);
7615 #endif
7616                         *pde |= PG_A;
7617                         rv = 0;
7618                 }
7619                 goto done;
7620         }
7621
7622         pte = pmap_pde_to_pte(pde, va);
7623         if ((*pte & PG_V) == 0)
7624                 goto done;
7625
7626         if (ftype == VM_PROT_WRITE) {
7627                 if ((*pte & PG_RW) == 0)
7628                         goto done;
7629                 /*
7630                  * Set the modified and accessed bits simultaneously.
7631                  *
7632                  * Intel EPT PTEs that do software emulation of A/D bits map
7633                  * PG_A and PG_M to EPT_PG_READ and EPT_PG_WRITE respectively.
7634                  * An EPT misconfiguration is triggered if the PTE is writable
7635                  * but not readable (WR=10). This is avoided by setting PG_A
7636                  * and PG_M simultaneously.
7637                  */
7638                 *pte |= PG_M | PG_A;
7639         } else {
7640                 *pte |= PG_A;
7641         }
7642
7643 #if VM_NRESERVLEVEL > 0
7644         /* try to promote the mapping */
7645         if (va < VM_MAXUSER_ADDRESS)
7646                 mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
7647         else
7648                 mpte = NULL;
7649
7650         m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
7651
7652         if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
7653             pmap_ps_enabled(pmap) &&
7654             (m->flags & PG_FICTITIOUS) == 0 &&
7655             vm_reserv_level_iffullpop(m) == 0) {
7656                 pmap_promote_pde(pmap, pde, va, &lock);
7657 #ifdef INVARIANTS
7658                 atomic_add_long(&ad_emulation_superpage_promotions, 1);
7659 #endif
7660         }
7661 #endif
7662
7663 #ifdef INVARIANTS
7664         if (ftype == VM_PROT_WRITE)
7665                 atomic_add_long(&num_dirty_emulations, 1);
7666         else
7667                 atomic_add_long(&num_accessed_emulations, 1);
7668 #endif
7669         rv = 0;         /* success */
7670 done:
7671         if (lock != NULL)
7672                 rw_wunlock(lock);
7673         PMAP_UNLOCK(pmap);
7674         return (rv);
7675 }
7676
7677 void
7678 pmap_get_mapping(pmap_t pmap, vm_offset_t va, uint64_t *ptr, int *num)
7679 {
7680         pml4_entry_t *pml4;
7681         pdp_entry_t *pdp;
7682         pd_entry_t *pde;
7683         pt_entry_t *pte, PG_V;
7684         int idx;
7685
7686         idx = 0;
7687         PG_V = pmap_valid_bit(pmap);
7688         PMAP_LOCK(pmap);
7689
7690         pml4 = pmap_pml4e(pmap, va);
7691         ptr[idx++] = *pml4;
7692         if ((*pml4 & PG_V) == 0)
7693                 goto done;
7694
7695         pdp = pmap_pml4e_to_pdpe(pml4, va);
7696         ptr[idx++] = *pdp;
7697         if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0)
7698                 goto done;
7699
7700         pde = pmap_pdpe_to_pde(pdp, va);
7701         ptr[idx++] = *pde;
7702         if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0)
7703                 goto done;
7704
7705         pte = pmap_pde_to_pte(pde, va);
7706         ptr[idx++] = *pte;
7707
7708 done:
7709         PMAP_UNLOCK(pmap);
7710         *num = idx;
7711 }
7712
7713 /**
7714  * Get the kernel virtual address of a set of physical pages. If there are
7715  * physical addresses not covered by the DMAP perform a transient mapping
7716  * that will be removed when calling pmap_unmap_io_transient.
7717  *
7718  * \param page        The pages the caller wishes to obtain the virtual
7719  *                    address on the kernel memory map.
7720  * \param vaddr       On return contains the kernel virtual memory address
7721  *                    of the pages passed in the page parameter.
7722  * \param count       Number of pages passed in.
7723  * \param can_fault   TRUE if the thread using the mapped pages can take
7724  *                    page faults, FALSE otherwise.
7725  *
7726  * \returns TRUE if the caller must call pmap_unmap_io_transient when
7727  *          finished or FALSE otherwise.
7728  *
7729  */
7730 boolean_t
7731 pmap_map_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7732     boolean_t can_fault)
7733 {
7734         vm_paddr_t paddr;
7735         boolean_t needs_mapping;
7736         pt_entry_t *pte;
7737         int cache_bits, error __unused, i;
7738
7739         /*
7740          * Allocate any KVA space that we need, this is done in a separate
7741          * loop to prevent calling vmem_alloc while pinned.
7742          */
7743         needs_mapping = FALSE;
7744         for (i = 0; i < count; i++) {
7745                 paddr = VM_PAGE_TO_PHYS(page[i]);
7746                 if (__predict_false(paddr >= dmaplimit)) {
7747                         error = vmem_alloc(kernel_arena, PAGE_SIZE,
7748                             M_BESTFIT | M_WAITOK, &vaddr[i]);
7749                         KASSERT(error == 0, ("vmem_alloc failed: %d", error));
7750                         needs_mapping = TRUE;
7751                 } else {
7752                         vaddr[i] = PHYS_TO_DMAP(paddr);
7753                 }
7754         }
7755
7756         /* Exit early if everything is covered by the DMAP */
7757         if (!needs_mapping)
7758                 return (FALSE);
7759
7760         /*
7761          * NB:  The sequence of updating a page table followed by accesses
7762          * to the corresponding pages used in the !DMAP case is subject to
7763          * the situation described in the "AMD64 Architecture Programmer's
7764          * Manual Volume 2: System Programming" rev. 3.23, "7.3.1 Special
7765          * Coherency Considerations".  Therefore, issuing the INVLPG right
7766          * after modifying the PTE bits is crucial.
7767          */
7768         if (!can_fault)
7769                 sched_pin();
7770         for (i = 0; i < count; i++) {
7771                 paddr = VM_PAGE_TO_PHYS(page[i]);
7772                 if (paddr >= dmaplimit) {
7773                         if (can_fault) {
7774                                 /*
7775                                  * Slow path, since we can get page faults
7776                                  * while mappings are active don't pin the
7777                                  * thread to the CPU and instead add a global
7778                                  * mapping visible to all CPUs.
7779                                  */
7780                                 pmap_qenter(vaddr[i], &page[i], 1);
7781                         } else {
7782                                 pte = vtopte(vaddr[i]);
7783                                 cache_bits = pmap_cache_bits(kernel_pmap,
7784                                     page[i]->md.pat_mode, 0);
7785                                 pte_store(pte, paddr | X86_PG_RW | X86_PG_V |
7786                                     cache_bits);
7787                                 invlpg(vaddr[i]);
7788                         }
7789                 }
7790         }
7791
7792         return (needs_mapping);
7793 }
7794
7795 void
7796 pmap_unmap_io_transient(vm_page_t page[], vm_offset_t vaddr[], int count,
7797     boolean_t can_fault)
7798 {
7799         vm_paddr_t paddr;
7800         int i;
7801
7802         if (!can_fault)
7803                 sched_unpin();
7804         for (i = 0; i < count; i++) {
7805                 paddr = VM_PAGE_TO_PHYS(page[i]);
7806                 if (paddr >= dmaplimit) {
7807                         if (can_fault)
7808                                 pmap_qremove(vaddr[i], 1);
7809                         vmem_free(kernel_arena, vaddr[i], PAGE_SIZE);
7810                 }
7811         }
7812 }
7813
7814 vm_offset_t
7815 pmap_quick_enter_page(vm_page_t m)
7816 {
7817         vm_paddr_t paddr;
7818
7819         paddr = VM_PAGE_TO_PHYS(m);
7820         if (paddr < dmaplimit)
7821                 return (PHYS_TO_DMAP(paddr));
7822         mtx_lock_spin(&qframe_mtx);
7823         KASSERT(*vtopte(qframe) == 0, ("qframe busy"));
7824         pte_store(vtopte(qframe), paddr | X86_PG_RW | X86_PG_V | X86_PG_A |
7825             X86_PG_M | pmap_cache_bits(kernel_pmap, m->md.pat_mode, 0));
7826         return (qframe);
7827 }
7828
7829 void
7830 pmap_quick_remove_page(vm_offset_t addr)
7831 {
7832
7833         if (addr != qframe)
7834                 return;
7835         pte_store(vtopte(qframe), 0);
7836         invlpg(qframe);
7837         mtx_unlock_spin(&qframe_mtx);
7838 }
7839
7840 static vm_page_t
7841 pmap_pti_alloc_page(void)
7842 {
7843         vm_page_t m;
7844
7845         VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7846         m = vm_page_grab(pti_obj, pti_pg_idx++, VM_ALLOC_NOBUSY |
7847             VM_ALLOC_WIRED | VM_ALLOC_ZERO);
7848         return (m);
7849 }
7850
7851 static bool
7852 pmap_pti_free_page(vm_page_t m)
7853 {
7854
7855         KASSERT(m->wire_count > 0, ("page %p not wired", m));
7856         if (!vm_page_unwire_noq(m))
7857                 return (false);
7858         vm_page_free_zero(m);
7859         return (true);
7860 }
7861
7862 static void
7863 pmap_pti_init(void)
7864 {
7865         vm_page_t pml4_pg;
7866         pdp_entry_t *pdpe;
7867         vm_offset_t va;
7868         int i;
7869
7870         if (!pti)
7871                 return;
7872         pti_obj = vm_pager_allocate(OBJT_PHYS, NULL, 0, VM_PROT_ALL, 0, NULL);
7873         VM_OBJECT_WLOCK(pti_obj);
7874         pml4_pg = pmap_pti_alloc_page();
7875         pti_pml4 = (pml4_entry_t *)PHYS_TO_DMAP(VM_PAGE_TO_PHYS(pml4_pg));
7876         for (va = VM_MIN_KERNEL_ADDRESS; va <= VM_MAX_KERNEL_ADDRESS &&
7877             va >= VM_MIN_KERNEL_ADDRESS && va > NBPML4; va += NBPML4) {
7878                 pdpe = pmap_pti_pdpe(va);
7879                 pmap_pti_wire_pte(pdpe);
7880         }
7881         pmap_pti_add_kva_locked((vm_offset_t)&__pcpu[0],
7882             (vm_offset_t)&__pcpu[0] + sizeof(__pcpu[0]) * MAXCPU, false);
7883         pmap_pti_add_kva_locked((vm_offset_t)gdt, (vm_offset_t)gdt +
7884             sizeof(struct user_segment_descriptor) * NGDT * MAXCPU, false);
7885         pmap_pti_add_kva_locked((vm_offset_t)idt, (vm_offset_t)idt +
7886             sizeof(struct gate_descriptor) * NIDT, false);
7887         pmap_pti_add_kva_locked((vm_offset_t)common_tss,
7888             (vm_offset_t)common_tss + sizeof(struct amd64tss) * MAXCPU, false);
7889         CPU_FOREACH(i) {
7890                 /* Doublefault stack IST 1 */
7891                 va = common_tss[i].tss_ist1;
7892                 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7893                 /* NMI stack IST 2 */
7894                 va = common_tss[i].tss_ist2 + sizeof(struct nmi_pcpu);
7895                 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7896                 /* MC# stack IST 3 */
7897                 va = common_tss[i].tss_ist3 + sizeof(struct nmi_pcpu);
7898                 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7899                 /* DB# stack IST 4 */
7900                 va = common_tss[i].tss_ist4 + sizeof(struct nmi_pcpu);
7901                 pmap_pti_add_kva_locked(va - PAGE_SIZE, va, false);
7902         }
7903         pmap_pti_add_kva_locked((vm_offset_t)kernphys + KERNBASE,
7904             (vm_offset_t)etext, true);
7905         pti_finalized = true;
7906         VM_OBJECT_WUNLOCK(pti_obj);
7907 }
7908 SYSINIT(pmap_pti, SI_SUB_CPU + 1, SI_ORDER_ANY, pmap_pti_init, NULL);
7909
7910 static pdp_entry_t *
7911 pmap_pti_pdpe(vm_offset_t va)
7912 {
7913         pml4_entry_t *pml4e;
7914         pdp_entry_t *pdpe;
7915         vm_page_t m;
7916         vm_pindex_t pml4_idx;
7917         vm_paddr_t mphys;
7918
7919         VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7920
7921         pml4_idx = pmap_pml4e_index(va);
7922         pml4e = &pti_pml4[pml4_idx];
7923         m = NULL;
7924         if (*pml4e == 0) {
7925                 if (pti_finalized)
7926                         panic("pml4 alloc after finalization\n");
7927                 m = pmap_pti_alloc_page();
7928                 if (*pml4e != 0) {
7929                         pmap_pti_free_page(m);
7930                         mphys = *pml4e & ~PAGE_MASK;
7931                 } else {
7932                         mphys = VM_PAGE_TO_PHYS(m);
7933                         *pml4e = mphys | X86_PG_RW | X86_PG_V;
7934                 }
7935         } else {
7936                 mphys = *pml4e & ~PAGE_MASK;
7937         }
7938         pdpe = (pdp_entry_t *)PHYS_TO_DMAP(mphys) + pmap_pdpe_index(va);
7939         return (pdpe);
7940 }
7941
7942 static void
7943 pmap_pti_wire_pte(void *pte)
7944 {
7945         vm_page_t m;
7946
7947         VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7948         m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7949         m->wire_count++;
7950 }
7951
7952 static void
7953 pmap_pti_unwire_pde(void *pde, bool only_ref)
7954 {
7955         vm_page_t m;
7956
7957         VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7958         m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pde));
7959         MPASS(m->wire_count > 0);
7960         MPASS(only_ref || m->wire_count > 1);
7961         pmap_pti_free_page(m);
7962 }
7963
7964 static void
7965 pmap_pti_unwire_pte(void *pte, vm_offset_t va)
7966 {
7967         vm_page_t m;
7968         pd_entry_t *pde;
7969
7970         VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7971         m = PHYS_TO_VM_PAGE(DMAP_TO_PHYS((uintptr_t)pte));
7972         MPASS(m->wire_count > 0);
7973         if (pmap_pti_free_page(m)) {
7974                 pde = pmap_pti_pde(va);
7975                 MPASS((*pde & (X86_PG_PS | X86_PG_V)) == X86_PG_V);
7976                 *pde = 0;
7977                 pmap_pti_unwire_pde(pde, false);
7978         }
7979 }
7980
7981 static pd_entry_t *
7982 pmap_pti_pde(vm_offset_t va)
7983 {
7984         pdp_entry_t *pdpe;
7985         pd_entry_t *pde;
7986         vm_page_t m;
7987         vm_pindex_t pd_idx;
7988         vm_paddr_t mphys;
7989
7990         VM_OBJECT_ASSERT_WLOCKED(pti_obj);
7991
7992         pdpe = pmap_pti_pdpe(va);
7993         if (*pdpe == 0) {
7994                 m = pmap_pti_alloc_page();
7995                 if (*pdpe != 0) {
7996                         pmap_pti_free_page(m);
7997                         MPASS((*pdpe & X86_PG_PS) == 0);
7998                         mphys = *pdpe & ~PAGE_MASK;
7999                 } else {
8000                         mphys =  VM_PAGE_TO_PHYS(m);
8001                         *pdpe = mphys | X86_PG_RW | X86_PG_V;
8002                 }
8003         } else {
8004                 MPASS((*pdpe & X86_PG_PS) == 0);
8005                 mphys = *pdpe & ~PAGE_MASK;
8006         }
8007
8008         pde = (pd_entry_t *)PHYS_TO_DMAP(mphys);
8009         pd_idx = pmap_pde_index(va);
8010         pde += pd_idx;
8011         return (pde);
8012 }
8013
8014 static pt_entry_t *
8015 pmap_pti_pte(vm_offset_t va, bool *unwire_pde)
8016 {
8017         pd_entry_t *pde;
8018         pt_entry_t *pte;
8019         vm_page_t m;
8020         vm_paddr_t mphys;
8021
8022         VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8023
8024         pde = pmap_pti_pde(va);
8025         if (unwire_pde != NULL) {
8026                 *unwire_pde = true;
8027                 pmap_pti_wire_pte(pde);
8028         }
8029         if (*pde == 0) {
8030                 m = pmap_pti_alloc_page();
8031                 if (*pde != 0) {
8032                         pmap_pti_free_page(m);
8033                         MPASS((*pde & X86_PG_PS) == 0);
8034                         mphys = *pde & ~(PAGE_MASK | pg_nx);
8035                 } else {
8036                         mphys = VM_PAGE_TO_PHYS(m);
8037                         *pde = mphys | X86_PG_RW | X86_PG_V;
8038                         if (unwire_pde != NULL)
8039                                 *unwire_pde = false;
8040                 }
8041         } else {
8042                 MPASS((*pde & X86_PG_PS) == 0);
8043                 mphys = *pde & ~(PAGE_MASK | pg_nx);
8044         }
8045
8046         pte = (pt_entry_t *)PHYS_TO_DMAP(mphys);
8047         pte += pmap_pte_index(va);
8048
8049         return (pte);
8050 }
8051
8052 static void
8053 pmap_pti_add_kva_locked(vm_offset_t sva, vm_offset_t eva, bool exec)
8054 {
8055         vm_paddr_t pa;
8056         pd_entry_t *pde;
8057         pt_entry_t *pte, ptev;
8058         bool unwire_pde;
8059
8060         VM_OBJECT_ASSERT_WLOCKED(pti_obj);
8061
8062         sva = trunc_page(sva);
8063         MPASS(sva > VM_MAXUSER_ADDRESS);
8064         eva = round_page(eva);
8065         MPASS(sva < eva);
8066         for (; sva < eva; sva += PAGE_SIZE) {
8067                 pte = pmap_pti_pte(sva, &unwire_pde);
8068                 pa = pmap_kextract(sva);
8069                 ptev = pa | X86_PG_RW | X86_PG_V | X86_PG_A | X86_PG_G |
8070                     (exec ? 0 : pg_nx) | pmap_cache_bits(kernel_pmap,
8071                     VM_MEMATTR_DEFAULT, FALSE);
8072                 if (*pte == 0) {
8073                         pte_store(pte, ptev);
8074                         pmap_pti_wire_pte(pte);
8075                 } else {
8076                         KASSERT(!pti_finalized,
8077                             ("pti overlap after fin %#lx %#lx %#lx",
8078                             sva, *pte, ptev));
8079                         KASSERT(*pte == ptev,
8080                             ("pti non-identical pte after fin %#lx %#lx %#lx",
8081                             sva, *pte, ptev));
8082                 }
8083                 if (unwire_pde) {
8084                         pde = pmap_pti_pde(sva);
8085                         pmap_pti_unwire_pde(pde, true);
8086                 }
8087         }
8088 }
8089
8090 void
8091 pmap_pti_add_kva(vm_offset_t sva, vm_offset_t eva, bool exec)
8092 {
8093
8094         if (!pti)
8095                 return;
8096         VM_OBJECT_WLOCK(pti_obj);
8097         pmap_pti_add_kva_locked(sva, eva, exec);
8098         VM_OBJECT_WUNLOCK(pti_obj);
8099 }
8100
8101 void
8102 pmap_pti_remove_kva(vm_offset_t sva, vm_offset_t eva)
8103 {
8104         pt_entry_t *pte;
8105         vm_offset_t va;
8106
8107         if (!pti)
8108                 return;
8109         sva = rounddown2(sva, PAGE_SIZE);
8110         MPASS(sva > VM_MAXUSER_ADDRESS);
8111         eva = roundup2(eva, PAGE_SIZE);
8112         MPASS(sva < eva);
8113         VM_OBJECT_WLOCK(pti_obj);
8114         for (va = sva; va < eva; va += PAGE_SIZE) {
8115                 pte = pmap_pti_pte(va, NULL);
8116                 KASSERT((*pte & X86_PG_V) != 0,
8117                     ("invalid pte va %#lx pte %#lx pt %#lx", va,
8118                     (u_long)pte, *pte));
8119                 pte_clear(pte);
8120                 pmap_pti_unwire_pte(pte, va);
8121         }
8122         pmap_invalidate_range(kernel_pmap, sva, eva);
8123         VM_OBJECT_WUNLOCK(pti_obj);
8124 }
8125
8126 #include "opt_ddb.h"
8127 #ifdef DDB
8128 #include <sys/kdb.h>
8129 #include <ddb/ddb.h>
8130
8131 DB_SHOW_COMMAND(pte, pmap_print_pte)
8132 {
8133         pmap_t pmap;
8134         pml4_entry_t *pml4;
8135         pdp_entry_t *pdp;
8136         pd_entry_t *pde;
8137         pt_entry_t *pte, PG_V;
8138         vm_offset_t va;
8139
8140         if (!have_addr) {
8141                 db_printf("show pte addr\n");
8142                 return;
8143         }
8144         va = (vm_offset_t)addr;
8145
8146         if (kdb_thread != NULL)
8147                 pmap = vmspace_pmap(kdb_thread->td_proc->p_vmspace);
8148         else
8149                 pmap = PCPU_GET(curpmap);
8150
8151         PG_V = pmap_valid_bit(pmap);
8152         pml4 = pmap_pml4e(pmap, va);
8153         db_printf("VA %#016lx pml4e %#016lx", va, *pml4);
8154         if ((*pml4 & PG_V) == 0) {
8155                 db_printf("\n");
8156                 return;
8157         }
8158         pdp = pmap_pml4e_to_pdpe(pml4, va);
8159         db_printf(" pdpe %#016lx", *pdp);
8160         if ((*pdp & PG_V) == 0 || (*pdp & PG_PS) != 0) {
8161                 db_printf("\n");
8162                 return;
8163         }
8164         pde = pmap_pdpe_to_pde(pdp, va);
8165         db_printf(" pde %#016lx", *pde);
8166         if ((*pde & PG_V) == 0 || (*pde & PG_PS) != 0) {
8167                 db_printf("\n");
8168                 return;
8169         }
8170         pte = pmap_pde_to_pte(pde, va);
8171         db_printf(" pte %#016lx\n", *pte);
8172 }
8173
8174 DB_SHOW_COMMAND(phys2dmap, pmap_phys2dmap)
8175 {
8176         vm_paddr_t a;
8177
8178         if (have_addr) {
8179                 a = (vm_paddr_t)addr;
8180                 db_printf("0x%jx\n", (uintmax_t)PHYS_TO_DMAP(a));
8181         } else {
8182                 db_printf("show phys2dmap addr\n");
8183         }
8184 }
8185 #endif