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