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