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