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