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