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