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