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