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