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