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