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