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