pmap.c revision 270920
1323124Sdes/*-
2285031Sdes * Copyright (c) 1991 Regents of the University of California.
3285031Sdes * All rights reserved.
4285031Sdes * Copyright (c) 1994 John S. Dyson
5285031Sdes * All rights reserved.
6285031Sdes * Copyright (c) 1994 David Greenman
7285031Sdes * All rights reserved.
8285031Sdes * Copyright (c) 2005-2010 Alan L. Cox <alc@cs.rice.edu>
9285031Sdes * All rights reserved.
10285031Sdes *
11285031Sdes * This code is derived from software contributed to Berkeley by
12285031Sdes * the Systems Programming Group of the University of Utah Computer
13285031Sdes * Science Department and William Jolitz of UUNET Technologies Inc.
14285031Sdes *
15285031Sdes * Redistribution and use in source and binary forms, with or without
16285031Sdes * modification, are permitted provided that the following conditions
17285031Sdes * are met:
18285031Sdes * 1. Redistributions of source code must retain the above copyright
19285031Sdes *    notice, this list of conditions and the following disclaimer.
20285031Sdes * 2. Redistributions in binary form must reproduce the above copyright
21285031Sdes *    notice, this list of conditions and the following disclaimer in the
22285031Sdes *    documentation and/or other materials provided with the distribution.
23285031Sdes * 3. All advertising materials mentioning features or use of this software
24285031Sdes *    must display the following acknowledgement:
25285031Sdes *	This product includes software developed by the University of
26285031Sdes *	California, Berkeley and its contributors.
27285031Sdes * 4. Neither the name of the University nor the names of its contributors
28285031Sdes *    may be used to endorse or promote products derived from this software
29285031Sdes *    without specific prior written permission.
30285031Sdes *
31285031Sdes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
32285031Sdes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33285031Sdes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34285031Sdes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
35285031Sdes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36285031Sdes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
37285031Sdes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38285031Sdes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
39285031Sdes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
40285031Sdes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
41296781Sdes * SUCH DAMAGE.
42296781Sdes *
43285031Sdes *	from:	@(#)pmap.c	7.7 (Berkeley)	5/12/91
44285031Sdes */
45285031Sdes/*-
46285031Sdes * Copyright (c) 2003 Networks Associates Technology, Inc.
47285031Sdes * All rights reserved.
48285031Sdes *
49285031Sdes * This software was developed for the FreeBSD Project by Jake Burkholder,
50296781Sdes * Safeport Network Services, and Network Associates Laboratories, the
51285031Sdes * Security Research Division of Network Associates, Inc. under
52285031Sdes * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
53285031Sdes * CHATS research program.
54285031Sdes *
55285031Sdes * Redistribution and use in source and binary forms, with or without
56285031Sdes * modification, are permitted provided that the following conditions
57285031Sdes * are met:
58285031Sdes * 1. Redistributions of source code must retain the above copyright
59296781Sdes *    notice, this list of conditions and the following disclaimer.
60285031Sdes * 2. Redistributions in binary form must reproduce the above copyright
61285031Sdes *    notice, this list of conditions and the following disclaimer in the
62285031Sdes *    documentation and/or other materials provided with the distribution.
63285031Sdes *
64285031Sdes * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
65285031Sdes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
66285031Sdes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
67285031Sdes * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
68285031Sdes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
69285031Sdes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
70285031Sdes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
71285031Sdes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
72285031Sdes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
73285031Sdes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
74285031Sdes * SUCH DAMAGE.
75285031Sdes */
76285031Sdes
77285031Sdes#include <sys/cdefs.h>
78285031Sdes__FBSDID("$FreeBSD: stable/10/sys/i386/i386/pmap.c 270920 2014-09-01 07:58:15Z kib $");
79285031Sdes
80285031Sdes/*
81285031Sdes *	Manages physical address maps.
82285031Sdes *
83285031Sdes *	Since the information managed by this module is
84285031Sdes *	also stored by the logical address mapping module,
85285031Sdes *	this module may throw away valid virtual-to-physical
86285031Sdes *	mappings at almost any time.  However, invalidations
87285031Sdes *	of virtual-to-physical mappings must be done as
88285031Sdes *	requested.
89285031Sdes *
90285031Sdes *	In order to cope with hardware architectures which
91285031Sdes *	make virtual-to-physical map invalidates expensive,
92285031Sdes *	this module may delay invalidate or reduced protection
93285031Sdes *	operations until such time as they are actually
94285031Sdes *	necessary.  This module is given full information as
95285031Sdes *	to which processors are currently using which maps,
96285031Sdes *	and to when physical maps must be made correct.
97285031Sdes */
98285031Sdes
99285031Sdes#include "opt_apic.h"
100285031Sdes#include "opt_cpu.h"
101285031Sdes#include "opt_pmap.h"
102285031Sdes#include "opt_smp.h"
103285031Sdes#include "opt_xbox.h"
104323124Sdes
105323124Sdes#include <sys/param.h>
106323124Sdes#include <sys/systm.h>
107285031Sdes#include <sys/kernel.h>
108285031Sdes#include <sys/ktr.h>
109285031Sdes#include <sys/lock.h>
110285031Sdes#include <sys/malloc.h>
111285031Sdes#include <sys/mman.h>
112285031Sdes#include <sys/msgbuf.h>
113285031Sdes#include <sys/mutex.h>
114285031Sdes#include <sys/proc.h>
115285031Sdes#include <sys/rwlock.h>
116285031Sdes#include <sys/sf_buf.h>
117285031Sdes#include <sys/sx.h>
118285031Sdes#include <sys/vmmeter.h>
119285031Sdes#include <sys/sched.h>
120285031Sdes#include <sys/sysctl.h>
121323124Sdes#ifdef SMP
122323124Sdes#include <sys/smp.h>
123323124Sdes#else
124285031Sdes#include <sys/cpuset.h>
125285031Sdes#endif
126285031Sdes
127285031Sdes#include <vm/vm.h>
128285031Sdes#include <vm/vm_param.h>
129285031Sdes#include <vm/vm_kern.h>
130285031Sdes#include <vm/vm_page.h>
131285031Sdes#include <vm/vm_map.h>
132285031Sdes#include <vm/vm_object.h>
133285031Sdes#include <vm/vm_extern.h>
134285031Sdes#include <vm/vm_pageout.h>
135285031Sdes#include <vm/vm_pager.h>
136285031Sdes#include <vm/vm_radix.h>
137285031Sdes#include <vm/vm_reserv.h>
138285031Sdes#include <vm/uma.h>
139285031Sdes
140285031Sdes#ifdef DEV_APIC
141285031Sdes#include <sys/bus.h>
142285031Sdes#include <machine/intr_machdep.h>
143285031Sdes#include <machine/apicvar.h>
144285031Sdes#endif
145285031Sdes#include <machine/cpu.h>
146285031Sdes#include <machine/cputypes.h>
147285031Sdes#include <machine/md_var.h>
148285031Sdes#include <machine/pcb.h>
149285031Sdes#include <machine/specialreg.h>
150285031Sdes#ifdef SMP
151285031Sdes#include <machine/smp.h>
152285031Sdes#endif
153285031Sdes
154285031Sdes#ifdef XBOX
155285031Sdes#include <machine/xbox.h>
156285031Sdes#endif
157285031Sdes
158285031Sdes#if !defined(CPU_DISABLE_SSE) && defined(I686_CPU)
159285031Sdes#define CPU_ENABLE_SSE
160285031Sdes#endif
161285031Sdes
162285031Sdes#ifndef PMAP_SHPGPERPROC
163285031Sdes#define PMAP_SHPGPERPROC 200
164285031Sdes#endif
165285031Sdes
166285031Sdes#if !defined(DIAGNOSTIC)
167285031Sdes#ifdef __GNUC_GNU_INLINE__
168285031Sdes#define PMAP_INLINE	__attribute__((__gnu_inline__)) inline
169285031Sdes#else
170285031Sdes#define PMAP_INLINE	extern inline
171285031Sdes#endif
172285031Sdes#else
173285031Sdes#define PMAP_INLINE
174285031Sdes#endif
175285031Sdes
176285031Sdes#ifdef PV_STATS
177285031Sdes#define PV_STAT(x)	do { x ; } while (0)
178285031Sdes#else
179285031Sdes#define PV_STAT(x)	do { } while (0)
180285031Sdes#endif
181285031Sdes
182285031Sdes#define	pa_index(pa)	((pa) >> PDRSHIFT)
183285031Sdes#define	pa_to_pvh(pa)	(&pv_table[pa_index(pa)])
184285031Sdes
185285031Sdes/*
186285031Sdes * Get PDEs and PTEs for user/kernel address space
187285031Sdes */
188285031Sdes#define	pmap_pde(m, v)	(&((m)->pm_pdir[(vm_offset_t)(v) >> PDRSHIFT]))
189285031Sdes#define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
190285031Sdes
191285031Sdes#define pmap_pde_v(pte)		((*(int *)pte & PG_V) != 0)
192285031Sdes#define pmap_pte_w(pte)		((*(int *)pte & PG_W) != 0)
193285031Sdes#define pmap_pte_m(pte)		((*(int *)pte & PG_M) != 0)
194285031Sdes#define pmap_pte_u(pte)		((*(int *)pte & PG_A) != 0)
195285031Sdes#define pmap_pte_v(pte)		((*(int *)pte & PG_V) != 0)
196285031Sdes
197285031Sdes#define pmap_pte_set_w(pte, v)	((v) ? atomic_set_int((u_int *)(pte), PG_W) : \
198285031Sdes    atomic_clear_int((u_int *)(pte), PG_W))
199285031Sdes#define pmap_pte_set_prot(pte, v) ((*(int *)pte &= ~PG_PROT), (*(int *)pte |= (v)))
200285031Sdes
201285031Sdesstruct pmap kernel_pmap_store;
202285031SdesLIST_HEAD(pmaplist, pmap);
203285031Sdesstatic struct pmaplist allpmaps;
204285031Sdesstatic struct mtx allpmaps_lock;
205285031Sdes
206285031Sdesvm_offset_t virtual_avail;	/* VA of first avail page (after kernel bss) */
207285031Sdesvm_offset_t virtual_end;	/* VA of last avail page (end of kernel AS) */
208285031Sdesint pgeflag = 0;		/* PG_G or-in */
209285031Sdesint pseflag = 0;		/* PG_PS or-in */
210285031Sdes
211285031Sdesstatic int nkpt = NKPT;
212285031Sdesvm_offset_t kernel_vm_end = KERNBASE + NKPT * NBPDR;
213285031Sdesextern u_int32_t KERNend;
214285031Sdesextern u_int32_t KPTphys;
215285031Sdes
216285031Sdes#ifdef PAE
217285031Sdespt_entry_t pg_nx;
218285031Sdesstatic uma_zone_t pdptzone;
219285031Sdes#endif
220285031Sdes
221285031Sdesstatic SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
222285031Sdes
223285031Sdesstatic int pat_works = 1;
224285031SdesSYSCTL_INT(_vm_pmap, OID_AUTO, pat_works, CTLFLAG_RD, &pat_works, 1,
225285031Sdes    "Is page attribute table fully functional?");
226285031Sdes
227285031Sdesstatic int pg_ps_enabled = 1;
228285031SdesSYSCTL_INT(_vm_pmap, OID_AUTO, pg_ps_enabled, CTLFLAG_RDTUN, &pg_ps_enabled, 0,
229285031Sdes    "Are large page mappings enabled?");
230285031Sdes
231285031Sdes#define	PAT_INDEX_SIZE	8
232285031Sdesstatic int pat_index[PAT_INDEX_SIZE];	/* cache mode to PAT index conversion */
233285031Sdes
234285031Sdesstatic struct rwlock_padalign pvh_global_lock;
235285031Sdes
236285031Sdes/*
237285031Sdes * Data for the pv entry allocation mechanism
238285031Sdes */
239285031Sdesstatic TAILQ_HEAD(pch, pv_chunk) pv_chunks = TAILQ_HEAD_INITIALIZER(pv_chunks);
240285031Sdesstatic int pv_entry_count = 0, pv_entry_max = 0, pv_entry_high_water = 0;
241285031Sdesstatic struct md_page *pv_table;
242285031Sdesstatic int shpgperproc = PMAP_SHPGPERPROC;
243285031Sdes
244285031Sdesstruct pv_chunk *pv_chunkbase;		/* KVA block for pv_chunks */
245285031Sdesint pv_maxchunks;			/* How many chunks we have KVA for */
246285031Sdesvm_offset_t pv_vafree;			/* freelist stored in the PTE */
247285031Sdes
248285031Sdes/*
249285031Sdes * All those kernel PT submaps that BSD is so fond of
250285031Sdes */
251285031Sdesstruct sysmaps {
252285031Sdes	struct	mtx lock;
253285031Sdes	pt_entry_t *CMAP1;
254285031Sdes	pt_entry_t *CMAP2;
255285031Sdes	caddr_t	CADDR1;
256285031Sdes	caddr_t	CADDR2;
257285031Sdes};
258285031Sdesstatic struct sysmaps sysmaps_pcpu[MAXCPU];
259285031Sdespt_entry_t *CMAP3;
260285031Sdesstatic pd_entry_t *KPTD;
261285031Sdescaddr_t ptvmmap = 0;
262285031Sdescaddr_t CADDR3;
263285031Sdesstruct msgbuf *msgbufp = 0;
264285031Sdes
265285031Sdes/*
266285031Sdes * Crashdump maps.
267285031Sdes */
268285031Sdesstatic caddr_t crashdumpmap;
269285031Sdes
270285031Sdesstatic pt_entry_t *PMAP1 = 0, *PMAP2;
271285031Sdesstatic pt_entry_t *PADDR1 = 0, *PADDR2;
272285031Sdes#ifdef SMP
273285031Sdesstatic int PMAP1cpu;
274285031Sdesstatic int PMAP1changedcpu;
275285031SdesSYSCTL_INT(_debug, OID_AUTO, PMAP1changedcpu, CTLFLAG_RD,
276285031Sdes	   &PMAP1changedcpu, 0,
277285031Sdes	   "Number of times pmap_pte_quick changed CPU with same PMAP1");
278285031Sdes#endif
279285031Sdesstatic int PMAP1changed;
280285031SdesSYSCTL_INT(_debug, OID_AUTO, PMAP1changed, CTLFLAG_RD,
281285031Sdes	   &PMAP1changed, 0,
282285031Sdes	   "Number of times pmap_pte_quick changed PMAP1");
283285031Sdesstatic int PMAP1unchanged;
284285031SdesSYSCTL_INT(_debug, OID_AUTO, PMAP1unchanged, CTLFLAG_RD,
285285031Sdes	   &PMAP1unchanged, 0,
286285031Sdes	   "Number of times pmap_pte_quick didn't change PMAP1");
287285031Sdesstatic struct mtx PMAP2mutex;
288285031Sdes
289285031Sdesstatic void	free_pv_chunk(struct pv_chunk *pc);
290285031Sdesstatic void	free_pv_entry(pmap_t pmap, pv_entry_t pv);
291285031Sdesstatic pv_entry_t get_pv_entry(pmap_t pmap, boolean_t try);
292285031Sdesstatic void	pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa);
293285031Sdesstatic boolean_t pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa);
294285031Sdesstatic void	pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa);
295285031Sdesstatic void	pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va);
296285031Sdesstatic pv_entry_t pmap_pvh_remove(struct md_page *pvh, pmap_t pmap,
297285031Sdes		    vm_offset_t va);
298285031Sdesstatic int	pmap_pvh_wired_mappings(struct md_page *pvh, int count);
299285031Sdes
300285031Sdesstatic boolean_t pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
301285031Sdesstatic boolean_t pmap_enter_pde(pmap_t pmap, vm_offset_t va, vm_page_t m,
302285031Sdes    vm_prot_t prot);
303285031Sdesstatic vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
304285031Sdes    vm_page_t m, vm_prot_t prot, vm_page_t mpte);
305285031Sdesstatic void pmap_flush_page(vm_page_t m);
306285031Sdesstatic int pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte);
307285031Sdesstatic void pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte);
308285031Sdesstatic boolean_t pmap_is_modified_pvh(struct md_page *pvh);
309285031Sdesstatic boolean_t pmap_is_referenced_pvh(struct md_page *pvh);
310285031Sdesstatic void pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode);
311285031Sdesstatic void pmap_kenter_pde(vm_offset_t va, pd_entry_t newpde);
312285031Sdesstatic vm_page_t pmap_lookup_pt_page(pmap_t pmap, vm_offset_t va);
313285031Sdesstatic void pmap_pde_attr(pd_entry_t *pde, int cache_bits);
314285031Sdesstatic void pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va);
315285031Sdesstatic boolean_t pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva,
316285031Sdes    vm_prot_t prot);
317285031Sdesstatic void pmap_pte_attr(pt_entry_t *pte, int cache_bits);
318285031Sdesstatic void pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
319285031Sdes    struct spglist *free);
320285031Sdesstatic int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva,
321285031Sdes    struct spglist *free);
322285031Sdesstatic void pmap_remove_pt_page(pmap_t pmap, vm_page_t mpte);
323285031Sdesstatic void pmap_remove_page(struct pmap *pmap, vm_offset_t va,
324285031Sdes    struct spglist *free);
325285031Sdesstatic void pmap_remove_entry(struct pmap *pmap, vm_page_t m,
326285031Sdes					vm_offset_t va);
327285031Sdesstatic void pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t m);
328285031Sdesstatic boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
329285031Sdes    vm_page_t m);
330285031Sdesstatic void pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde,
331285031Sdes    pd_entry_t newpde);
332285031Sdesstatic void pmap_update_pde_invalidate(vm_offset_t va, pd_entry_t newpde);
333285031Sdes
334285031Sdesstatic vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va, u_int flags);
335285031Sdes
336285031Sdesstatic vm_page_t _pmap_allocpte(pmap_t pmap, u_int ptepindex, u_int flags);
337285031Sdesstatic void _pmap_unwire_ptp(pmap_t pmap, vm_page_t m, struct spglist *free);
338285031Sdesstatic pt_entry_t *pmap_pte_quick(pmap_t pmap, vm_offset_t va);
339285031Sdesstatic void pmap_pte_release(pt_entry_t *pte);
340285031Sdesstatic int pmap_unuse_pt(pmap_t, vm_offset_t, struct spglist *);
341285031Sdes#ifdef PAE
342285031Sdesstatic void *pmap_pdpt_allocf(uma_zone_t zone, int bytes, u_int8_t *flags, int wait);
343285031Sdes#endif
344285031Sdesstatic void pmap_set_pg(void);
345285031Sdes
346285031Sdesstatic __inline void pagezero(void *page);
347285031Sdes
348285031SdesCTASSERT(1 << PDESHIFT == sizeof(pd_entry_t));
349285031SdesCTASSERT(1 << PTESHIFT == sizeof(pt_entry_t));
350285031Sdes
351285031Sdes/*
352285031Sdes * If you get an error here, then you set KVA_PAGES wrong! See the
353285031Sdes * description of KVA_PAGES in sys/i386/include/pmap.h. It must be
354285031Sdes * multiple of 4 for a normal kernel, or a multiple of 8 for a PAE.
355285031Sdes */
356285031SdesCTASSERT(KERNBASE % (1 << 24) == 0);
357285031Sdes
358285031Sdes/*
359285031Sdes *	Bootstrap the system enough to run with virtual memory.
360285031Sdes *
361285031Sdes *	On the i386 this is called after mapping has already been enabled
362285031Sdes *	and just syncs the pmap module with what has already been done.
363285031Sdes *	[We can't call it easily with mapping off since the kernel is not
364285031Sdes *	mapped with PA == VA, hence we would have to relocate every address
365285031Sdes *	from the linked base (virtual) address "KERNBASE" to the actual
366285031Sdes *	(physical) address starting relative to 0]
367285031Sdes */
368285031Sdesvoid
369285031Sdespmap_bootstrap(vm_paddr_t firstaddr)
370285031Sdes{
371285031Sdes	vm_offset_t va;
372285031Sdes	pt_entry_t *pte, *unused;
373285031Sdes	struct sysmaps *sysmaps;
374285031Sdes	int i;
375285031Sdes
376285031Sdes	/*
377285031Sdes	 * Initialize the first available kernel virtual address.  However,
378285031Sdes	 * using "firstaddr" may waste a few pages of the kernel virtual
379285031Sdes	 * address space, because locore may not have mapped every physical
380285031Sdes	 * page that it allocated.  Preferably, locore would provide a first
381285031Sdes	 * unused virtual address in addition to "firstaddr".
382285031Sdes	 */
383285031Sdes	virtual_avail = (vm_offset_t) KERNBASE + firstaddr;
384285031Sdes
385285031Sdes	virtual_end = VM_MAX_KERNEL_ADDRESS;
386285031Sdes
387285031Sdes	/*
388285031Sdes	 * Initialize the kernel pmap (which is statically allocated).
389285031Sdes	 */
390285031Sdes	PMAP_LOCK_INIT(kernel_pmap);
391285031Sdes	kernel_pmap->pm_pdir = (pd_entry_t *) (KERNBASE + (u_int)IdlePTD);
392285031Sdes#ifdef PAE
393285031Sdes	kernel_pmap->pm_pdpt = (pdpt_entry_t *) (KERNBASE + (u_int)IdlePDPT);
394285031Sdes#endif
395285031Sdes	CPU_FILL(&kernel_pmap->pm_active);	/* don't allow deactivation */
396285031Sdes	TAILQ_INIT(&kernel_pmap->pm_pvchunk);
397285031Sdes
398285031Sdes 	/*
399285031Sdes	 * Initialize the global pv list lock.
400285031Sdes	 */
401285031Sdes	rw_init(&pvh_global_lock, "pmap pv global");
402285031Sdes
403285031Sdes	LIST_INIT(&allpmaps);
404285031Sdes
405285031Sdes	/*
406285031Sdes	 * Request a spin mutex so that changes to allpmaps cannot be
407285031Sdes	 * preempted by smp_rendezvous_cpus().  Otherwise,
408285031Sdes	 * pmap_update_pde_kernel() could access allpmaps while it is
409285031Sdes	 * being changed.
410285031Sdes	 */
411285031Sdes	mtx_init(&allpmaps_lock, "allpmaps", NULL, MTX_SPIN);
412285031Sdes	mtx_lock_spin(&allpmaps_lock);
413285031Sdes	LIST_INSERT_HEAD(&allpmaps, kernel_pmap, pm_list);
414285031Sdes	mtx_unlock_spin(&allpmaps_lock);
415285031Sdes
416285031Sdes	/*
417285031Sdes	 * Reserve some special page table entries/VA space for temporary
418285031Sdes	 * mapping of pages.
419285031Sdes	 */
420285031Sdes#define	SYSMAP(c, p, v, n)	\
421285031Sdes	v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
422285031Sdes
423285031Sdes	va = virtual_avail;
424285031Sdes	pte = vtopte(va);
425285031Sdes
426285031Sdes	/*
427285031Sdes	 * CMAP1/CMAP2 are used for zeroing and copying pages.
428285031Sdes	 * CMAP3 is used for the idle process page zeroing.
429285031Sdes	 */
430285031Sdes	for (i = 0; i < MAXCPU; i++) {
431285031Sdes		sysmaps = &sysmaps_pcpu[i];
432285031Sdes		mtx_init(&sysmaps->lock, "SYSMAPS", NULL, MTX_DEF);
433285031Sdes		SYSMAP(caddr_t, sysmaps->CMAP1, sysmaps->CADDR1, 1)
434285031Sdes		SYSMAP(caddr_t, sysmaps->CMAP2, sysmaps->CADDR2, 1)
435285031Sdes	}
436285031Sdes	SYSMAP(caddr_t, CMAP3, CADDR3, 1)
437285031Sdes
438285031Sdes	/*
439285031Sdes	 * Crashdump maps.
440285031Sdes	 */
441285031Sdes	SYSMAP(caddr_t, unused, crashdumpmap, MAXDUMPPGS)
442285031Sdes
443285031Sdes	/*
444285031Sdes	 * ptvmmap is used for reading arbitrary physical pages via /dev/mem.
445285031Sdes	 */
446285031Sdes	SYSMAP(caddr_t, unused, ptvmmap, 1)
447285031Sdes
448285031Sdes	/*
449285031Sdes	 * msgbufp is used to map the system message buffer.
450285031Sdes	 */
451285031Sdes	SYSMAP(struct msgbuf *, unused, msgbufp, atop(round_page(msgbufsize)))
452285031Sdes
453285031Sdes	/*
454285031Sdes	 * KPTmap is used by pmap_kextract().
455285031Sdes	 *
456285031Sdes	 * KPTmap is first initialized by locore.  However, that initial
457285031Sdes	 * KPTmap can only support NKPT page table pages.  Here, a larger
458285031Sdes	 * KPTmap is created that can support KVA_PAGES page table pages.
459285031Sdes	 */
460285031Sdes	SYSMAP(pt_entry_t *, KPTD, KPTmap, KVA_PAGES)
461285031Sdes
462285031Sdes	for (i = 0; i < NKPT; i++)
463285031Sdes		KPTD[i] = (KPTphys + (i << PAGE_SHIFT)) | pgeflag | PG_RW | PG_V;
464285031Sdes
465285031Sdes	/*
466285031Sdes	 * Adjust the start of the KPTD and KPTmap so that the implementation
467285031Sdes	 * of pmap_kextract() and pmap_growkernel() can be made simpler.
468285031Sdes	 */
469285031Sdes	KPTD -= KPTDI;
470285031Sdes	KPTmap -= i386_btop(KPTDI << PDRSHIFT);
471285031Sdes
472285031Sdes	/*
473285031Sdes	 * PADDR1 and PADDR2 are used by pmap_pte_quick() and pmap_pte(),
474285031Sdes	 * respectively.
475285031Sdes	 */
476285031Sdes	SYSMAP(pt_entry_t *, PMAP1, PADDR1, 1)
477285031Sdes	SYSMAP(pt_entry_t *, PMAP2, PADDR2, 1)
478285031Sdes
479285031Sdes	mtx_init(&PMAP2mutex, "PMAP2", NULL, MTX_DEF);
480285031Sdes
481285031Sdes	virtual_avail = va;
482285031Sdes
483285031Sdes	/*
484285031Sdes	 * Leave in place an identity mapping (virt == phys) for the low 1 MB
485285031Sdes	 * physical memory region that is used by the ACPI wakeup code.  This
486285031Sdes	 * mapping must not have PG_G set.
487285031Sdes	 */
488285031Sdes#ifdef XBOX
489285031Sdes	/* FIXME: This is gross, but needed for the XBOX. Since we are in such
490285031Sdes	 * an early stadium, we cannot yet neatly map video memory ... :-(
491285031Sdes	 * Better fixes are very welcome! */
492285031Sdes	if (!arch_i386_is_xbox)
493285031Sdes#endif
494285031Sdes	for (i = 1; i < NKPT; i++)
495285031Sdes		PTD[i] = 0;
496285031Sdes
497285031Sdes	/* Initialize the PAT MSR if present. */
498285031Sdes	pmap_init_pat();
499285031Sdes
500285031Sdes	/* Turn on PG_G on kernel page(s) */
501285031Sdes	pmap_set_pg();
502285031Sdes}
503285031Sdes
504285031Sdes/*
505285031Sdes * Setup the PAT MSR.
506285031Sdes */
507285031Sdesvoid
508285031Sdespmap_init_pat(void)
509285031Sdes{
510285031Sdes	int pat_table[PAT_INDEX_SIZE];
511285031Sdes	uint64_t pat_msr;
512285031Sdes	u_long cr0, cr4;
513285031Sdes	int i;
514285031Sdes
515285031Sdes	/* Set default PAT index table. */
516285031Sdes	for (i = 0; i < PAT_INDEX_SIZE; i++)
517285031Sdes		pat_table[i] = -1;
518285031Sdes	pat_table[PAT_WRITE_BACK] = 0;
519285031Sdes	pat_table[PAT_WRITE_THROUGH] = 1;
520285031Sdes	pat_table[PAT_UNCACHEABLE] = 3;
521285031Sdes	pat_table[PAT_WRITE_COMBINING] = 3;
522285031Sdes	pat_table[PAT_WRITE_PROTECTED] = 3;
523285031Sdes	pat_table[PAT_UNCACHED] = 3;
524285031Sdes
525285031Sdes	/* Bail if this CPU doesn't implement PAT. */
526285031Sdes	if ((cpu_feature & CPUID_PAT) == 0) {
527285031Sdes		for (i = 0; i < PAT_INDEX_SIZE; i++)
528285031Sdes			pat_index[i] = pat_table[i];
529285031Sdes		pat_works = 0;
530285031Sdes		return;
531285031Sdes	}
532285031Sdes
533285031Sdes	/*
534285031Sdes	 * Due to some Intel errata, we can only safely use the lower 4
535285031Sdes	 * PAT entries.
536285031Sdes	 *
537296781Sdes	 *   Intel Pentium III Processor Specification Update
538296781Sdes	 * Errata E.27 (Upper Four PAT Entries Not Usable With Mode B
539285031Sdes	 * or Mode C Paging)
540296781Sdes	 *
541285031Sdes	 *   Intel Pentium IV  Processor Specification Update
542	 * Errata N46 (PAT Index MSB May Be Calculated Incorrectly)
543	 */
544	if (cpu_vendor_id == CPU_VENDOR_INTEL &&
545	    !(CPUID_TO_FAMILY(cpu_id) == 6 && CPUID_TO_MODEL(cpu_id) >= 0xe))
546		pat_works = 0;
547
548	/* Initialize default PAT entries. */
549	pat_msr = PAT_VALUE(0, PAT_WRITE_BACK) |
550	    PAT_VALUE(1, PAT_WRITE_THROUGH) |
551	    PAT_VALUE(2, PAT_UNCACHED) |
552	    PAT_VALUE(3, PAT_UNCACHEABLE) |
553	    PAT_VALUE(4, PAT_WRITE_BACK) |
554	    PAT_VALUE(5, PAT_WRITE_THROUGH) |
555	    PAT_VALUE(6, PAT_UNCACHED) |
556	    PAT_VALUE(7, PAT_UNCACHEABLE);
557
558	if (pat_works) {
559		/*
560		 * Leave the indices 0-3 at the default of WB, WT, UC-, and UC.
561		 * Program 5 and 6 as WP and WC.
562		 * Leave 4 and 7 as WB and UC.
563		 */
564		pat_msr &= ~(PAT_MASK(5) | PAT_MASK(6));
565		pat_msr |= PAT_VALUE(5, PAT_WRITE_PROTECTED) |
566		    PAT_VALUE(6, PAT_WRITE_COMBINING);
567		pat_table[PAT_UNCACHED] = 2;
568		pat_table[PAT_WRITE_PROTECTED] = 5;
569		pat_table[PAT_WRITE_COMBINING] = 6;
570	} else {
571		/*
572		 * Just replace PAT Index 2 with WC instead of UC-.
573		 */
574		pat_msr &= ~PAT_MASK(2);
575		pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
576		pat_table[PAT_WRITE_COMBINING] = 2;
577	}
578
579	/* Disable PGE. */
580	cr4 = rcr4();
581	load_cr4(cr4 & ~CR4_PGE);
582
583	/* Disable caches (CD = 1, NW = 0). */
584	cr0 = rcr0();
585	load_cr0((cr0 & ~CR0_NW) | CR0_CD);
586
587	/* Flushes caches and TLBs. */
588	wbinvd();
589	invltlb();
590
591	/* Update PAT and index table. */
592	wrmsr(MSR_PAT, pat_msr);
593	for (i = 0; i < PAT_INDEX_SIZE; i++)
594		pat_index[i] = pat_table[i];
595
596	/* Flush caches and TLBs again. */
597	wbinvd();
598	invltlb();
599
600	/* Restore caches and PGE. */
601	load_cr0(cr0);
602	load_cr4(cr4);
603}
604
605/*
606 * Set PG_G on kernel pages.  Only the BSP calls this when SMP is turned on.
607 */
608static void
609pmap_set_pg(void)
610{
611	pt_entry_t *pte;
612	vm_offset_t va, endva;
613
614	if (pgeflag == 0)
615		return;
616
617	endva = KERNBASE + KERNend;
618
619	if (pseflag) {
620		va = KERNBASE + KERNLOAD;
621		while (va  < endva) {
622			pdir_pde(PTD, va) |= pgeflag;
623			invltlb();	/* Play it safe, invltlb() every time */
624			va += NBPDR;
625		}
626	} else {
627		va = (vm_offset_t)btext;
628		while (va < endva) {
629			pte = vtopte(va);
630			if (*pte)
631				*pte |= pgeflag;
632			invltlb();	/* Play it safe, invltlb() every time */
633			va += PAGE_SIZE;
634		}
635	}
636}
637
638/*
639 * Initialize a vm_page's machine-dependent fields.
640 */
641void
642pmap_page_init(vm_page_t m)
643{
644
645	TAILQ_INIT(&m->md.pv_list);
646	m->md.pat_mode = PAT_WRITE_BACK;
647}
648
649#ifdef PAE
650static void *
651pmap_pdpt_allocf(uma_zone_t zone, int bytes, u_int8_t *flags, int wait)
652{
653
654	/* Inform UMA that this allocator uses kernel_map/object. */
655	*flags = UMA_SLAB_KERNEL;
656	return ((void *)kmem_alloc_contig(kernel_arena, bytes, wait, 0x0ULL,
657	    0xffffffffULL, 1, 0, VM_MEMATTR_DEFAULT));
658}
659#endif
660
661/*
662 * ABuse the pte nodes for unmapped kva to thread a kva freelist through.
663 * Requirements:
664 *  - Must deal with pages in order to ensure that none of the PG_* bits
665 *    are ever set, PG_V in particular.
666 *  - Assumes we can write to ptes without pte_store() atomic ops, even
667 *    on PAE systems.  This should be ok.
668 *  - Assumes nothing will ever test these addresses for 0 to indicate
669 *    no mapping instead of correctly checking PG_V.
670 *  - Assumes a vm_offset_t will fit in a pte (true for i386).
671 * Because PG_V is never set, there can be no mappings to invalidate.
672 */
673static vm_offset_t
674pmap_ptelist_alloc(vm_offset_t *head)
675{
676	pt_entry_t *pte;
677	vm_offset_t va;
678
679	va = *head;
680	if (va == 0)
681		panic("pmap_ptelist_alloc: exhausted ptelist KVA");
682	pte = vtopte(va);
683	*head = *pte;
684	if (*head & PG_V)
685		panic("pmap_ptelist_alloc: va with PG_V set!");
686	*pte = 0;
687	return (va);
688}
689
690static void
691pmap_ptelist_free(vm_offset_t *head, vm_offset_t va)
692{
693	pt_entry_t *pte;
694
695	if (va & PG_V)
696		panic("pmap_ptelist_free: freeing va with PG_V set!");
697	pte = vtopte(va);
698	*pte = *head;		/* virtual! PG_V is 0 though */
699	*head = va;
700}
701
702static void
703pmap_ptelist_init(vm_offset_t *head, void *base, int npages)
704{
705	int i;
706	vm_offset_t va;
707
708	*head = 0;
709	for (i = npages - 1; i >= 0; i--) {
710		va = (vm_offset_t)base + i * PAGE_SIZE;
711		pmap_ptelist_free(head, va);
712	}
713}
714
715
716/*
717 *	Initialize the pmap module.
718 *	Called by vm_init, to initialize any structures that the pmap
719 *	system needs to map virtual memory.
720 */
721void
722pmap_init(void)
723{
724	vm_page_t mpte;
725	vm_size_t s;
726	int i, pv_npg;
727
728	/*
729	 * Initialize the vm page array entries for the kernel pmap's
730	 * page table pages.
731	 */
732	for (i = 0; i < NKPT; i++) {
733		mpte = PHYS_TO_VM_PAGE(KPTphys + (i << PAGE_SHIFT));
734		KASSERT(mpte >= vm_page_array &&
735		    mpte < &vm_page_array[vm_page_array_size],
736		    ("pmap_init: page table page is out of range"));
737		mpte->pindex = i + KPTDI;
738		mpte->phys_addr = KPTphys + (i << PAGE_SHIFT);
739	}
740
741	/*
742	 * Initialize the address space (zone) for the pv entries.  Set a
743	 * high water mark so that the system can recover from excessive
744	 * numbers of pv entries.
745	 */
746	TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
747	pv_entry_max = shpgperproc * maxproc + cnt.v_page_count;
748	TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
749	pv_entry_max = roundup(pv_entry_max, _NPCPV);
750	pv_entry_high_water = 9 * (pv_entry_max / 10);
751
752	/*
753	 * If the kernel is running on a virtual machine, then it must assume
754	 * that MCA is enabled by the hypervisor.  Moreover, the kernel must
755	 * be prepared for the hypervisor changing the vendor and family that
756	 * are reported by CPUID.  Consequently, the workaround for AMD Family
757	 * 10h Erratum 383 is enabled if the processor's feature set does not
758	 * include at least one feature that is only supported by older Intel
759	 * or newer AMD processors.
760	 */
761	if (vm_guest == VM_GUEST_VM && (cpu_feature & CPUID_SS) == 0 &&
762	    (cpu_feature2 & (CPUID2_SSSE3 | CPUID2_SSE41 | CPUID2_AESNI |
763	    CPUID2_AVX | CPUID2_XSAVE)) == 0 && (amd_feature2 & (AMDID2_XOP |
764	    AMDID2_FMA4)) == 0)
765		workaround_erratum383 = 1;
766
767	/*
768	 * Are large page mappings supported and enabled?
769	 */
770	TUNABLE_INT_FETCH("vm.pmap.pg_ps_enabled", &pg_ps_enabled);
771	if (pseflag == 0)
772		pg_ps_enabled = 0;
773	else if (pg_ps_enabled) {
774		KASSERT(MAXPAGESIZES > 1 && pagesizes[1] == 0,
775		    ("pmap_init: can't assign to pagesizes[1]"));
776		pagesizes[1] = NBPDR;
777	}
778
779	/*
780	 * Calculate the size of the pv head table for superpages.
781	 */
782	for (i = 0; phys_avail[i + 1]; i += 2);
783	pv_npg = round_4mpage(phys_avail[(i - 2) + 1]) / NBPDR;
784
785	/*
786	 * Allocate memory for the pv head table for superpages.
787	 */
788	s = (vm_size_t)(pv_npg * sizeof(struct md_page));
789	s = round_page(s);
790	pv_table = (struct md_page *)kmem_malloc(kernel_arena, s,
791	    M_WAITOK | M_ZERO);
792	for (i = 0; i < pv_npg; i++)
793		TAILQ_INIT(&pv_table[i].pv_list);
794
795	pv_maxchunks = MAX(pv_entry_max / _NPCPV, maxproc);
796	pv_chunkbase = (struct pv_chunk *)kva_alloc(PAGE_SIZE * pv_maxchunks);
797	if (pv_chunkbase == NULL)
798		panic("pmap_init: not enough kvm for pv chunks");
799	pmap_ptelist_init(&pv_vafree, pv_chunkbase, pv_maxchunks);
800#ifdef PAE
801	pdptzone = uma_zcreate("PDPT", NPGPTD * sizeof(pdpt_entry_t), NULL,
802	    NULL, NULL, NULL, (NPGPTD * sizeof(pdpt_entry_t)) - 1,
803	    UMA_ZONE_VM | UMA_ZONE_NOFREE);
804	uma_zone_set_allocf(pdptzone, pmap_pdpt_allocf);
805#endif
806}
807
808
809SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_max, CTLFLAG_RD, &pv_entry_max, 0,
810	"Max number of PV entries");
811SYSCTL_INT(_vm_pmap, OID_AUTO, shpgperproc, CTLFLAG_RD, &shpgperproc, 0,
812	"Page share factor per proc");
813
814static SYSCTL_NODE(_vm_pmap, OID_AUTO, pde, CTLFLAG_RD, 0,
815    "2/4MB page mapping counters");
816
817static u_long pmap_pde_demotions;
818SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, demotions, CTLFLAG_RD,
819    &pmap_pde_demotions, 0, "2/4MB page demotions");
820
821static u_long pmap_pde_mappings;
822SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, mappings, CTLFLAG_RD,
823    &pmap_pde_mappings, 0, "2/4MB page mappings");
824
825static u_long pmap_pde_p_failures;
826SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, p_failures, CTLFLAG_RD,
827    &pmap_pde_p_failures, 0, "2/4MB page promotion failures");
828
829static u_long pmap_pde_promotions;
830SYSCTL_ULONG(_vm_pmap_pde, OID_AUTO, promotions, CTLFLAG_RD,
831    &pmap_pde_promotions, 0, "2/4MB page promotions");
832
833/***************************************************
834 * Low level helper routines.....
835 ***************************************************/
836
837/*
838 * Determine the appropriate bits to set in a PTE or PDE for a specified
839 * caching mode.
840 */
841int
842pmap_cache_bits(int mode, boolean_t is_pde)
843{
844	int cache_bits, pat_flag, pat_idx;
845
846	if (mode < 0 || mode >= PAT_INDEX_SIZE || pat_index[mode] < 0)
847		panic("Unknown caching mode %d\n", mode);
848
849	/* The PAT bit is different for PTE's and PDE's. */
850	pat_flag = is_pde ? PG_PDE_PAT : PG_PTE_PAT;
851
852	/* Map the caching mode to a PAT index. */
853	pat_idx = pat_index[mode];
854
855	/* Map the 3-bit index value into the PAT, PCD, and PWT bits. */
856	cache_bits = 0;
857	if (pat_idx & 0x4)
858		cache_bits |= pat_flag;
859	if (pat_idx & 0x2)
860		cache_bits |= PG_NC_PCD;
861	if (pat_idx & 0x1)
862		cache_bits |= PG_NC_PWT;
863	return (cache_bits);
864}
865
866/*
867 * The caller is responsible for maintaining TLB consistency.
868 */
869static void
870pmap_kenter_pde(vm_offset_t va, pd_entry_t newpde)
871{
872	pd_entry_t *pde;
873	pmap_t pmap;
874	boolean_t PTD_updated;
875
876	PTD_updated = FALSE;
877	mtx_lock_spin(&allpmaps_lock);
878	LIST_FOREACH(pmap, &allpmaps, pm_list) {
879		if ((pmap->pm_pdir[PTDPTDI] & PG_FRAME) == (PTDpde[0] &
880		    PG_FRAME))
881			PTD_updated = TRUE;
882		pde = pmap_pde(pmap, va);
883		pde_store(pde, newpde);
884	}
885	mtx_unlock_spin(&allpmaps_lock);
886	KASSERT(PTD_updated,
887	    ("pmap_kenter_pde: current page table is not in allpmaps"));
888}
889
890/*
891 * After changing the page size for the specified virtual address in the page
892 * table, flush the corresponding entries from the processor's TLB.  Only the
893 * calling processor's TLB is affected.
894 *
895 * The calling thread must be pinned to a processor.
896 */
897static void
898pmap_update_pde_invalidate(vm_offset_t va, pd_entry_t newpde)
899{
900	u_long cr4;
901
902	if ((newpde & PG_PS) == 0)
903		/* Demotion: flush a specific 2MB page mapping. */
904		invlpg(va);
905	else if ((newpde & PG_G) == 0)
906		/*
907		 * Promotion: flush every 4KB page mapping from the TLB
908		 * because there are too many to flush individually.
909		 */
910		invltlb();
911	else {
912		/*
913		 * Promotion: flush every 4KB page mapping from the TLB,
914		 * including any global (PG_G) mappings.
915		 */
916		cr4 = rcr4();
917		load_cr4(cr4 & ~CR4_PGE);
918		/*
919		 * Although preemption at this point could be detrimental to
920		 * performance, it would not lead to an error.  PG_G is simply
921		 * ignored if CR4.PGE is clear.  Moreover, in case this block
922		 * is re-entered, the load_cr4() either above or below will
923		 * modify CR4.PGE flushing the TLB.
924		 */
925		load_cr4(cr4 | CR4_PGE);
926	}
927}
928#ifdef SMP
929/*
930 * For SMP, these functions have to use the IPI mechanism for coherence.
931 *
932 * N.B.: Before calling any of the following TLB invalidation functions,
933 * the calling processor must ensure that all stores updating a non-
934 * kernel page table are globally performed.  Otherwise, another
935 * processor could cache an old, pre-update entry without being
936 * invalidated.  This can happen one of two ways: (1) The pmap becomes
937 * active on another processor after its pm_active field is checked by
938 * one of the following functions but before a store updating the page
939 * table is globally performed. (2) The pmap becomes active on another
940 * processor before its pm_active field is checked but due to
941 * speculative loads one of the following functions stills reads the
942 * pmap as inactive on the other processor.
943 *
944 * The kernel page table is exempt because its pm_active field is
945 * immutable.  The kernel page table is always active on every
946 * processor.
947 */
948void
949pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
950{
951	cpuset_t other_cpus;
952	u_int cpuid;
953
954	sched_pin();
955	if (pmap == kernel_pmap || !CPU_CMP(&pmap->pm_active, &all_cpus)) {
956		invlpg(va);
957		smp_invlpg(va);
958	} else {
959		cpuid = PCPU_GET(cpuid);
960		other_cpus = all_cpus;
961		CPU_CLR(cpuid, &other_cpus);
962		if (CPU_ISSET(cpuid, &pmap->pm_active))
963			invlpg(va);
964		CPU_AND(&other_cpus, &pmap->pm_active);
965		if (!CPU_EMPTY(&other_cpus))
966			smp_masked_invlpg(other_cpus, va);
967	}
968	sched_unpin();
969}
970
971void
972pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
973{
974	cpuset_t other_cpus;
975	vm_offset_t addr;
976	u_int cpuid;
977
978	sched_pin();
979	if (pmap == kernel_pmap || !CPU_CMP(&pmap->pm_active, &all_cpus)) {
980		for (addr = sva; addr < eva; addr += PAGE_SIZE)
981			invlpg(addr);
982		smp_invlpg_range(sva, eva);
983	} else {
984		cpuid = PCPU_GET(cpuid);
985		other_cpus = all_cpus;
986		CPU_CLR(cpuid, &other_cpus);
987		if (CPU_ISSET(cpuid, &pmap->pm_active))
988			for (addr = sva; addr < eva; addr += PAGE_SIZE)
989				invlpg(addr);
990		CPU_AND(&other_cpus, &pmap->pm_active);
991		if (!CPU_EMPTY(&other_cpus))
992			smp_masked_invlpg_range(other_cpus, sva, eva);
993	}
994	sched_unpin();
995}
996
997void
998pmap_invalidate_all(pmap_t pmap)
999{
1000	cpuset_t other_cpus;
1001	u_int cpuid;
1002
1003	sched_pin();
1004	if (pmap == kernel_pmap || !CPU_CMP(&pmap->pm_active, &all_cpus)) {
1005		invltlb();
1006		smp_invltlb();
1007	} else {
1008		cpuid = PCPU_GET(cpuid);
1009		other_cpus = all_cpus;
1010		CPU_CLR(cpuid, &other_cpus);
1011		if (CPU_ISSET(cpuid, &pmap->pm_active))
1012			invltlb();
1013		CPU_AND(&other_cpus, &pmap->pm_active);
1014		if (!CPU_EMPTY(&other_cpus))
1015			smp_masked_invltlb(other_cpus);
1016	}
1017	sched_unpin();
1018}
1019
1020void
1021pmap_invalidate_cache(void)
1022{
1023
1024	sched_pin();
1025	wbinvd();
1026	smp_cache_flush();
1027	sched_unpin();
1028}
1029
1030struct pde_action {
1031	cpuset_t invalidate;	/* processors that invalidate their TLB */
1032	vm_offset_t va;
1033	pd_entry_t *pde;
1034	pd_entry_t newpde;
1035	u_int store;		/* processor that updates the PDE */
1036};
1037
1038static void
1039pmap_update_pde_kernel(void *arg)
1040{
1041	struct pde_action *act = arg;
1042	pd_entry_t *pde;
1043	pmap_t pmap;
1044
1045	if (act->store == PCPU_GET(cpuid)) {
1046
1047		/*
1048		 * Elsewhere, this operation requires allpmaps_lock for
1049		 * synchronization.  Here, it does not because it is being
1050		 * performed in the context of an all_cpus rendezvous.
1051		 */
1052		LIST_FOREACH(pmap, &allpmaps, pm_list) {
1053			pde = pmap_pde(pmap, act->va);
1054			pde_store(pde, act->newpde);
1055		}
1056	}
1057}
1058
1059static void
1060pmap_update_pde_user(void *arg)
1061{
1062	struct pde_action *act = arg;
1063
1064	if (act->store == PCPU_GET(cpuid))
1065		pde_store(act->pde, act->newpde);
1066}
1067
1068static void
1069pmap_update_pde_teardown(void *arg)
1070{
1071	struct pde_action *act = arg;
1072
1073	if (CPU_ISSET(PCPU_GET(cpuid), &act->invalidate))
1074		pmap_update_pde_invalidate(act->va, act->newpde);
1075}
1076
1077/*
1078 * Change the page size for the specified virtual address in a way that
1079 * prevents any possibility of the TLB ever having two entries that map the
1080 * same virtual address using different page sizes.  This is the recommended
1081 * workaround for Erratum 383 on AMD Family 10h processors.  It prevents a
1082 * machine check exception for a TLB state that is improperly diagnosed as a
1083 * hardware error.
1084 */
1085static void
1086pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1087{
1088	struct pde_action act;
1089	cpuset_t active, other_cpus;
1090	u_int cpuid;
1091
1092	sched_pin();
1093	cpuid = PCPU_GET(cpuid);
1094	other_cpus = all_cpus;
1095	CPU_CLR(cpuid, &other_cpus);
1096	if (pmap == kernel_pmap)
1097		active = all_cpus;
1098	else
1099		active = pmap->pm_active;
1100	if (CPU_OVERLAP(&active, &other_cpus)) {
1101		act.store = cpuid;
1102		act.invalidate = active;
1103		act.va = va;
1104		act.pde = pde;
1105		act.newpde = newpde;
1106		CPU_SET(cpuid, &active);
1107		smp_rendezvous_cpus(active,
1108		    smp_no_rendevous_barrier, pmap == kernel_pmap ?
1109		    pmap_update_pde_kernel : pmap_update_pde_user,
1110		    pmap_update_pde_teardown, &act);
1111	} else {
1112		if (pmap == kernel_pmap)
1113			pmap_kenter_pde(va, newpde);
1114		else
1115			pde_store(pde, newpde);
1116		if (CPU_ISSET(cpuid, &active))
1117			pmap_update_pde_invalidate(va, newpde);
1118	}
1119	sched_unpin();
1120}
1121#else /* !SMP */
1122/*
1123 * Normal, non-SMP, 486+ invalidation functions.
1124 * We inline these within pmap.c for speed.
1125 */
1126PMAP_INLINE void
1127pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
1128{
1129
1130	if (pmap == kernel_pmap || !CPU_EMPTY(&pmap->pm_active))
1131		invlpg(va);
1132}
1133
1134PMAP_INLINE void
1135pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1136{
1137	vm_offset_t addr;
1138
1139	if (pmap == kernel_pmap || !CPU_EMPTY(&pmap->pm_active))
1140		for (addr = sva; addr < eva; addr += PAGE_SIZE)
1141			invlpg(addr);
1142}
1143
1144PMAP_INLINE void
1145pmap_invalidate_all(pmap_t pmap)
1146{
1147
1148	if (pmap == kernel_pmap || !CPU_EMPTY(&pmap->pm_active))
1149		invltlb();
1150}
1151
1152PMAP_INLINE void
1153pmap_invalidate_cache(void)
1154{
1155
1156	wbinvd();
1157}
1158
1159static void
1160pmap_update_pde(pmap_t pmap, vm_offset_t va, pd_entry_t *pde, pd_entry_t newpde)
1161{
1162
1163	if (pmap == kernel_pmap)
1164		pmap_kenter_pde(va, newpde);
1165	else
1166		pde_store(pde, newpde);
1167	if (pmap == kernel_pmap || !CPU_EMPTY(&pmap->pm_active))
1168		pmap_update_pde_invalidate(va, newpde);
1169}
1170#endif /* !SMP */
1171
1172#define	PMAP_CLFLUSH_THRESHOLD	(2 * 1024 * 1024)
1173
1174void
1175pmap_invalidate_cache_range(vm_offset_t sva, vm_offset_t eva)
1176{
1177
1178	KASSERT((sva & PAGE_MASK) == 0,
1179	    ("pmap_invalidate_cache_range: sva not page-aligned"));
1180	KASSERT((eva & PAGE_MASK) == 0,
1181	    ("pmap_invalidate_cache_range: eva not page-aligned"));
1182
1183	if (cpu_feature & CPUID_SS)
1184		; /* If "Self Snoop" is supported, do nothing. */
1185	else if ((cpu_feature & CPUID_CLFSH) != 0 &&
1186	    eva - sva < PMAP_CLFLUSH_THRESHOLD) {
1187
1188#ifdef DEV_APIC
1189		/*
1190		 * XXX: Some CPUs fault, hang, or trash the local APIC
1191		 * registers if we use CLFLUSH on the local APIC
1192		 * range.  The local APIC is always uncached, so we
1193		 * don't need to flush for that range anyway.
1194		 */
1195		if (pmap_kextract(sva) == lapic_paddr)
1196			return;
1197#endif
1198		/*
1199		 * Otherwise, do per-cache line flush.  Use the mfence
1200		 * instruction to insure that previous stores are
1201		 * included in the write-back.  The processor
1202		 * propagates flush to other processors in the cache
1203		 * coherence domain.
1204		 */
1205		mfence();
1206		for (; sva < eva; sva += cpu_clflush_line_size)
1207			clflush(sva);
1208		mfence();
1209	} else {
1210
1211		/*
1212		 * No targeted cache flush methods are supported by CPU,
1213		 * or the supplied range is bigger than 2MB.
1214		 * Globally invalidate cache.
1215		 */
1216		pmap_invalidate_cache();
1217	}
1218}
1219
1220void
1221pmap_invalidate_cache_pages(vm_page_t *pages, int count)
1222{
1223	int i;
1224
1225	if (count >= PMAP_CLFLUSH_THRESHOLD / PAGE_SIZE ||
1226	    (cpu_feature & CPUID_CLFSH) == 0) {
1227		pmap_invalidate_cache();
1228	} else {
1229		for (i = 0; i < count; i++)
1230			pmap_flush_page(pages[i]);
1231	}
1232}
1233
1234/*
1235 * Are we current address space or kernel?  N.B. We return FALSE when
1236 * a pmap's page table is in use because a kernel thread is borrowing
1237 * it.  The borrowed page table can change spontaneously, making any
1238 * dependence on its continued use subject to a race condition.
1239 */
1240static __inline int
1241pmap_is_current(pmap_t pmap)
1242{
1243
1244	return (pmap == kernel_pmap ||
1245	    (pmap == vmspace_pmap(curthread->td_proc->p_vmspace) &&
1246	    (pmap->pm_pdir[PTDPTDI] & PG_FRAME) == (PTDpde[0] & PG_FRAME)));
1247}
1248
1249/*
1250 * If the given pmap is not the current or kernel pmap, the returned pte must
1251 * be released by passing it to pmap_pte_release().
1252 */
1253pt_entry_t *
1254pmap_pte(pmap_t pmap, vm_offset_t va)
1255{
1256	pd_entry_t newpf;
1257	pd_entry_t *pde;
1258
1259	pde = pmap_pde(pmap, va);
1260	if (*pde & PG_PS)
1261		return (pde);
1262	if (*pde != 0) {
1263		/* are we current address space or kernel? */
1264		if (pmap_is_current(pmap))
1265			return (vtopte(va));
1266		mtx_lock(&PMAP2mutex);
1267		newpf = *pde & PG_FRAME;
1268		if ((*PMAP2 & PG_FRAME) != newpf) {
1269			*PMAP2 = newpf | PG_RW | PG_V | PG_A | PG_M;
1270			pmap_invalidate_page(kernel_pmap, (vm_offset_t)PADDR2);
1271		}
1272		return (PADDR2 + (i386_btop(va) & (NPTEPG - 1)));
1273	}
1274	return (NULL);
1275}
1276
1277/*
1278 * Releases a pte that was obtained from pmap_pte().  Be prepared for the pte
1279 * being NULL.
1280 */
1281static __inline void
1282pmap_pte_release(pt_entry_t *pte)
1283{
1284
1285	if ((pt_entry_t *)((vm_offset_t)pte & ~PAGE_MASK) == PADDR2)
1286		mtx_unlock(&PMAP2mutex);
1287}
1288
1289/*
1290 * NB:  The sequence of updating a page table followed by accesses to the
1291 * corresponding pages is subject to the situation described in the "AMD64
1292 * Architecture Programmer's Manual Volume 2: System Programming" rev. 3.23,
1293 * "7.3.1 Special Coherency Considerations".  Therefore, issuing the INVLPG
1294 * right after modifying the PTE bits is crucial.
1295 */
1296static __inline void
1297invlcaddr(void *caddr)
1298{
1299
1300	invlpg((u_int)caddr);
1301}
1302
1303/*
1304 * Super fast pmap_pte routine best used when scanning
1305 * the pv lists.  This eliminates many coarse-grained
1306 * invltlb calls.  Note that many of the pv list
1307 * scans are across different pmaps.  It is very wasteful
1308 * to do an entire invltlb for checking a single mapping.
1309 *
1310 * If the given pmap is not the current pmap, pvh_global_lock
1311 * must be held and curthread pinned to a CPU.
1312 */
1313static pt_entry_t *
1314pmap_pte_quick(pmap_t pmap, vm_offset_t va)
1315{
1316	pd_entry_t newpf;
1317	pd_entry_t *pde;
1318
1319	pde = pmap_pde(pmap, va);
1320	if (*pde & PG_PS)
1321		return (pde);
1322	if (*pde != 0) {
1323		/* are we current address space or kernel? */
1324		if (pmap_is_current(pmap))
1325			return (vtopte(va));
1326		rw_assert(&pvh_global_lock, RA_WLOCKED);
1327		KASSERT(curthread->td_pinned > 0, ("curthread not pinned"));
1328		newpf = *pde & PG_FRAME;
1329		if ((*PMAP1 & PG_FRAME) != newpf) {
1330			*PMAP1 = newpf | PG_RW | PG_V | PG_A | PG_M;
1331#ifdef SMP
1332			PMAP1cpu = PCPU_GET(cpuid);
1333#endif
1334			invlcaddr(PADDR1);
1335			PMAP1changed++;
1336		} else
1337#ifdef SMP
1338		if (PMAP1cpu != PCPU_GET(cpuid)) {
1339			PMAP1cpu = PCPU_GET(cpuid);
1340			invlcaddr(PADDR1);
1341			PMAP1changedcpu++;
1342		} else
1343#endif
1344			PMAP1unchanged++;
1345		return (PADDR1 + (i386_btop(va) & (NPTEPG - 1)));
1346	}
1347	return (0);
1348}
1349
1350/*
1351 *	Routine:	pmap_extract
1352 *	Function:
1353 *		Extract the physical page address associated
1354 *		with the given map/virtual_address pair.
1355 */
1356vm_paddr_t
1357pmap_extract(pmap_t pmap, vm_offset_t va)
1358{
1359	vm_paddr_t rtval;
1360	pt_entry_t *pte;
1361	pd_entry_t pde;
1362
1363	rtval = 0;
1364	PMAP_LOCK(pmap);
1365	pde = pmap->pm_pdir[va >> PDRSHIFT];
1366	if (pde != 0) {
1367		if ((pde & PG_PS) != 0)
1368			rtval = (pde & PG_PS_FRAME) | (va & PDRMASK);
1369		else {
1370			pte = pmap_pte(pmap, va);
1371			rtval = (*pte & PG_FRAME) | (va & PAGE_MASK);
1372			pmap_pte_release(pte);
1373		}
1374	}
1375	PMAP_UNLOCK(pmap);
1376	return (rtval);
1377}
1378
1379/*
1380 *	Routine:	pmap_extract_and_hold
1381 *	Function:
1382 *		Atomically extract and hold the physical page
1383 *		with the given pmap and virtual address pair
1384 *		if that mapping permits the given protection.
1385 */
1386vm_page_t
1387pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
1388{
1389	pd_entry_t pde;
1390	pt_entry_t pte, *ptep;
1391	vm_page_t m;
1392	vm_paddr_t pa;
1393
1394	pa = 0;
1395	m = NULL;
1396	PMAP_LOCK(pmap);
1397retry:
1398	pde = *pmap_pde(pmap, va);
1399	if (pde != 0) {
1400		if (pde & PG_PS) {
1401			if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
1402				if (vm_page_pa_tryrelock(pmap, (pde &
1403				    PG_PS_FRAME) | (va & PDRMASK), &pa))
1404					goto retry;
1405				m = PHYS_TO_VM_PAGE((pde & PG_PS_FRAME) |
1406				    (va & PDRMASK));
1407				vm_page_hold(m);
1408			}
1409		} else {
1410			ptep = pmap_pte(pmap, va);
1411			pte = *ptep;
1412			pmap_pte_release(ptep);
1413			if (pte != 0 &&
1414			    ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
1415				if (vm_page_pa_tryrelock(pmap, pte & PG_FRAME,
1416				    &pa))
1417					goto retry;
1418				m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
1419				vm_page_hold(m);
1420			}
1421		}
1422	}
1423	PA_UNLOCK_COND(pa);
1424	PMAP_UNLOCK(pmap);
1425	return (m);
1426}
1427
1428/***************************************************
1429 * Low level mapping routines.....
1430 ***************************************************/
1431
1432/*
1433 * Add a wired page to the kva.
1434 * Note: not SMP coherent.
1435 *
1436 * This function may be used before pmap_bootstrap() is called.
1437 */
1438PMAP_INLINE void
1439pmap_kenter(vm_offset_t va, vm_paddr_t pa)
1440{
1441	pt_entry_t *pte;
1442
1443	pte = vtopte(va);
1444	pte_store(pte, pa | PG_RW | PG_V | pgeflag);
1445}
1446
1447static __inline void
1448pmap_kenter_attr(vm_offset_t va, vm_paddr_t pa, int mode)
1449{
1450	pt_entry_t *pte;
1451
1452	pte = vtopte(va);
1453	pte_store(pte, pa | PG_RW | PG_V | pgeflag | pmap_cache_bits(mode, 0));
1454}
1455
1456/*
1457 * Remove a page from the kernel pagetables.
1458 * Note: not SMP coherent.
1459 *
1460 * This function may be used before pmap_bootstrap() is called.
1461 */
1462PMAP_INLINE void
1463pmap_kremove(vm_offset_t va)
1464{
1465	pt_entry_t *pte;
1466
1467	pte = vtopte(va);
1468	pte_clear(pte);
1469}
1470
1471/*
1472 *	Used to map a range of physical addresses into kernel
1473 *	virtual address space.
1474 *
1475 *	The value passed in '*virt' is a suggested virtual address for
1476 *	the mapping. Architectures which can support a direct-mapped
1477 *	physical to virtual region can return the appropriate address
1478 *	within that region, leaving '*virt' unchanged. Other
1479 *	architectures should map the pages starting at '*virt' and
1480 *	update '*virt' with the first usable address after the mapped
1481 *	region.
1482 */
1483vm_offset_t
1484pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
1485{
1486	vm_offset_t va, sva;
1487	vm_paddr_t superpage_offset;
1488	pd_entry_t newpde;
1489
1490	va = *virt;
1491	/*
1492	 * Does the physical address range's size and alignment permit at
1493	 * least one superpage mapping to be created?
1494	 */
1495	superpage_offset = start & PDRMASK;
1496	if ((end - start) - ((NBPDR - superpage_offset) & PDRMASK) >= NBPDR) {
1497		/*
1498		 * Increase the starting virtual address so that its alignment
1499		 * does not preclude the use of superpage mappings.
1500		 */
1501		if ((va & PDRMASK) < superpage_offset)
1502			va = (va & ~PDRMASK) + superpage_offset;
1503		else if ((va & PDRMASK) > superpage_offset)
1504			va = ((va + PDRMASK) & ~PDRMASK) + superpage_offset;
1505	}
1506	sva = va;
1507	while (start < end) {
1508		if ((start & PDRMASK) == 0 && end - start >= NBPDR &&
1509		    pseflag) {
1510			KASSERT((va & PDRMASK) == 0,
1511			    ("pmap_map: misaligned va %#x", va));
1512			newpde = start | PG_PS | pgeflag | PG_RW | PG_V;
1513			pmap_kenter_pde(va, newpde);
1514			va += NBPDR;
1515			start += NBPDR;
1516		} else {
1517			pmap_kenter(va, start);
1518			va += PAGE_SIZE;
1519			start += PAGE_SIZE;
1520		}
1521	}
1522	pmap_invalidate_range(kernel_pmap, sva, va);
1523	*virt = va;
1524	return (sva);
1525}
1526
1527
1528/*
1529 * Add a list of wired pages to the kva
1530 * this routine is only used for temporary
1531 * kernel mappings that do not need to have
1532 * page modification or references recorded.
1533 * Note that old mappings are simply written
1534 * over.  The page *must* be wired.
1535 * Note: SMP coherent.  Uses a ranged shootdown IPI.
1536 */
1537void
1538pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
1539{
1540	pt_entry_t *endpte, oldpte, pa, *pte;
1541	vm_page_t m;
1542
1543	oldpte = 0;
1544	pte = vtopte(sva);
1545	endpte = pte + count;
1546	while (pte < endpte) {
1547		m = *ma++;
1548		pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(m->md.pat_mode, 0);
1549		if ((*pte & (PG_FRAME | PG_PTE_CACHE)) != pa) {
1550			oldpte |= *pte;
1551			pte_store(pte, pa | pgeflag | PG_RW | PG_V);
1552		}
1553		pte++;
1554	}
1555	if (__predict_false((oldpte & PG_V) != 0))
1556		pmap_invalidate_range(kernel_pmap, sva, sva + count *
1557		    PAGE_SIZE);
1558}
1559
1560/*
1561 * This routine tears out page mappings from the
1562 * kernel -- it is meant only for temporary mappings.
1563 * Note: SMP coherent.  Uses a ranged shootdown IPI.
1564 */
1565void
1566pmap_qremove(vm_offset_t sva, int count)
1567{
1568	vm_offset_t va;
1569
1570	va = sva;
1571	while (count-- > 0) {
1572		pmap_kremove(va);
1573		va += PAGE_SIZE;
1574	}
1575	pmap_invalidate_range(kernel_pmap, sva, va);
1576}
1577
1578/***************************************************
1579 * Page table page management routines.....
1580 ***************************************************/
1581static __inline void
1582pmap_free_zero_pages(struct spglist *free)
1583{
1584	vm_page_t m;
1585
1586	while ((m = SLIST_FIRST(free)) != NULL) {
1587		SLIST_REMOVE_HEAD(free, plinks.s.ss);
1588		/* Preserve the page's PG_ZERO setting. */
1589		vm_page_free_toq(m);
1590	}
1591}
1592
1593/*
1594 * Schedule the specified unused page table page to be freed.  Specifically,
1595 * add the page to the specified list of pages that will be released to the
1596 * physical memory manager after the TLB has been updated.
1597 */
1598static __inline void
1599pmap_add_delayed_free_list(vm_page_t m, struct spglist *free,
1600    boolean_t set_PG_ZERO)
1601{
1602
1603	if (set_PG_ZERO)
1604		m->flags |= PG_ZERO;
1605	else
1606		m->flags &= ~PG_ZERO;
1607	SLIST_INSERT_HEAD(free, m, plinks.s.ss);
1608}
1609
1610/*
1611 * Inserts the specified page table page into the specified pmap's collection
1612 * of idle page table pages.  Each of a pmap's page table pages is responsible
1613 * for mapping a distinct range of virtual addresses.  The pmap's collection is
1614 * ordered by this virtual address range.
1615 */
1616static __inline int
1617pmap_insert_pt_page(pmap_t pmap, vm_page_t mpte)
1618{
1619
1620	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1621	return (vm_radix_insert(&pmap->pm_root, mpte));
1622}
1623
1624/*
1625 * Looks for a page table page mapping the specified virtual address in the
1626 * specified pmap's collection of idle page table pages.  Returns NULL if there
1627 * is no page table page corresponding to the specified virtual address.
1628 */
1629static __inline vm_page_t
1630pmap_lookup_pt_page(pmap_t pmap, vm_offset_t va)
1631{
1632
1633	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1634	return (vm_radix_lookup(&pmap->pm_root, va >> PDRSHIFT));
1635}
1636
1637/*
1638 * Removes the specified page table page from the specified pmap's collection
1639 * of idle page table pages.  The specified page table page must be a member of
1640 * the pmap's collection.
1641 */
1642static __inline void
1643pmap_remove_pt_page(pmap_t pmap, vm_page_t mpte)
1644{
1645
1646	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1647	vm_radix_remove(&pmap->pm_root, mpte->pindex);
1648}
1649
1650/*
1651 * Decrements a page table page's wire count, which is used to record the
1652 * number of valid page table entries within the page.  If the wire count
1653 * drops to zero, then the page table page is unmapped.  Returns TRUE if the
1654 * page table page was unmapped and FALSE otherwise.
1655 */
1656static inline boolean_t
1657pmap_unwire_ptp(pmap_t pmap, vm_page_t m, struct spglist *free)
1658{
1659
1660	--m->wire_count;
1661	if (m->wire_count == 0) {
1662		_pmap_unwire_ptp(pmap, m, free);
1663		return (TRUE);
1664	} else
1665		return (FALSE);
1666}
1667
1668static void
1669_pmap_unwire_ptp(pmap_t pmap, vm_page_t m, struct spglist *free)
1670{
1671	vm_offset_t pteva;
1672
1673	/*
1674	 * unmap the page table page
1675	 */
1676	pmap->pm_pdir[m->pindex] = 0;
1677	--pmap->pm_stats.resident_count;
1678
1679	/*
1680	 * This is a release store so that the ordinary store unmapping
1681	 * the page table page is globally performed before TLB shoot-
1682	 * down is begun.
1683	 */
1684	atomic_subtract_rel_int(&cnt.v_wire_count, 1);
1685
1686	/*
1687	 * Do an invltlb to make the invalidated mapping
1688	 * take effect immediately.
1689	 */
1690	pteva = VM_MAXUSER_ADDRESS + i386_ptob(m->pindex);
1691	pmap_invalidate_page(pmap, pteva);
1692
1693	/*
1694	 * Put page on a list so that it is released after
1695	 * *ALL* TLB shootdown is done
1696	 */
1697	pmap_add_delayed_free_list(m, free, TRUE);
1698}
1699
1700/*
1701 * After removing a page table entry, this routine is used to
1702 * conditionally free the page, and manage the hold/wire counts.
1703 */
1704static int
1705pmap_unuse_pt(pmap_t pmap, vm_offset_t va, struct spglist *free)
1706{
1707	pd_entry_t ptepde;
1708	vm_page_t mpte;
1709
1710	if (va >= VM_MAXUSER_ADDRESS)
1711		return (0);
1712	ptepde = *pmap_pde(pmap, va);
1713	mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
1714	return (pmap_unwire_ptp(pmap, mpte, free));
1715}
1716
1717/*
1718 * Initialize the pmap for the swapper process.
1719 */
1720void
1721pmap_pinit0(pmap_t pmap)
1722{
1723
1724	PMAP_LOCK_INIT(pmap);
1725	/*
1726	 * Since the page table directory is shared with the kernel pmap,
1727	 * which is already included in the list "allpmaps", this pmap does
1728	 * not need to be inserted into that list.
1729	 */
1730	pmap->pm_pdir = (pd_entry_t *)(KERNBASE + (vm_offset_t)IdlePTD);
1731#ifdef PAE
1732	pmap->pm_pdpt = (pdpt_entry_t *)(KERNBASE + (vm_offset_t)IdlePDPT);
1733#endif
1734	pmap->pm_root.rt_root = 0;
1735	CPU_ZERO(&pmap->pm_active);
1736	PCPU_SET(curpmap, pmap);
1737	TAILQ_INIT(&pmap->pm_pvchunk);
1738	bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1739}
1740
1741/*
1742 * Initialize a preallocated and zeroed pmap structure,
1743 * such as one in a vmspace structure.
1744 */
1745int
1746pmap_pinit(pmap_t pmap)
1747{
1748	vm_page_t m, ptdpg[NPGPTD];
1749	vm_paddr_t pa;
1750	int i;
1751
1752	/*
1753	 * No need to allocate page table space yet but we do need a valid
1754	 * page directory table.
1755	 */
1756	if (pmap->pm_pdir == NULL) {
1757		pmap->pm_pdir = (pd_entry_t *)kva_alloc(NBPTD);
1758		if (pmap->pm_pdir == NULL)
1759			return (0);
1760#ifdef PAE
1761		pmap->pm_pdpt = uma_zalloc(pdptzone, M_WAITOK | M_ZERO);
1762		KASSERT(((vm_offset_t)pmap->pm_pdpt &
1763		    ((NPGPTD * sizeof(pdpt_entry_t)) - 1)) == 0,
1764		    ("pmap_pinit: pdpt misaligned"));
1765		KASSERT(pmap_kextract((vm_offset_t)pmap->pm_pdpt) < (4ULL<<30),
1766		    ("pmap_pinit: pdpt above 4g"));
1767#endif
1768		pmap->pm_root.rt_root = 0;
1769	}
1770	KASSERT(vm_radix_is_empty(&pmap->pm_root),
1771	    ("pmap_pinit: pmap has reserved page table page(s)"));
1772
1773	/*
1774	 * allocate the page directory page(s)
1775	 */
1776	for (i = 0; i < NPGPTD;) {
1777		m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ |
1778		    VM_ALLOC_WIRED | VM_ALLOC_ZERO);
1779		if (m == NULL)
1780			VM_WAIT;
1781		else {
1782			ptdpg[i++] = m;
1783		}
1784	}
1785
1786	pmap_qenter((vm_offset_t)pmap->pm_pdir, ptdpg, NPGPTD);
1787
1788	for (i = 0; i < NPGPTD; i++)
1789		if ((ptdpg[i]->flags & PG_ZERO) == 0)
1790			pagezero(pmap->pm_pdir + (i * NPDEPG));
1791
1792	mtx_lock_spin(&allpmaps_lock);
1793	LIST_INSERT_HEAD(&allpmaps, pmap, pm_list);
1794	/* Copy the kernel page table directory entries. */
1795	bcopy(PTD + KPTDI, pmap->pm_pdir + KPTDI, nkpt * sizeof(pd_entry_t));
1796	mtx_unlock_spin(&allpmaps_lock);
1797
1798	/* install self-referential address mapping entry(s) */
1799	for (i = 0; i < NPGPTD; i++) {
1800		pa = VM_PAGE_TO_PHYS(ptdpg[i]);
1801		pmap->pm_pdir[PTDPTDI + i] = pa | PG_V | PG_RW | PG_A | PG_M;
1802#ifdef PAE
1803		pmap->pm_pdpt[i] = pa | PG_V;
1804#endif
1805	}
1806
1807	CPU_ZERO(&pmap->pm_active);
1808	TAILQ_INIT(&pmap->pm_pvchunk);
1809	bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1810
1811	return (1);
1812}
1813
1814/*
1815 * this routine is called if the page table page is not
1816 * mapped correctly.
1817 */
1818static vm_page_t
1819_pmap_allocpte(pmap_t pmap, u_int ptepindex, u_int flags)
1820{
1821	vm_paddr_t ptepa;
1822	vm_page_t m;
1823
1824	/*
1825	 * Allocate a page table page.
1826	 */
1827	if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
1828	    VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
1829		if ((flags & PMAP_ENTER_NOSLEEP) == 0) {
1830			PMAP_UNLOCK(pmap);
1831			rw_wunlock(&pvh_global_lock);
1832			VM_WAIT;
1833			rw_wlock(&pvh_global_lock);
1834			PMAP_LOCK(pmap);
1835		}
1836
1837		/*
1838		 * Indicate the need to retry.  While waiting, the page table
1839		 * page may have been allocated.
1840		 */
1841		return (NULL);
1842	}
1843	if ((m->flags & PG_ZERO) == 0)
1844		pmap_zero_page(m);
1845
1846	/*
1847	 * Map the pagetable page into the process address space, if
1848	 * it isn't already there.
1849	 */
1850
1851	pmap->pm_stats.resident_count++;
1852
1853	ptepa = VM_PAGE_TO_PHYS(m);
1854	pmap->pm_pdir[ptepindex] =
1855		(pd_entry_t) (ptepa | PG_U | PG_RW | PG_V | PG_A | PG_M);
1856
1857	return (m);
1858}
1859
1860static vm_page_t
1861pmap_allocpte(pmap_t pmap, vm_offset_t va, u_int flags)
1862{
1863	u_int ptepindex;
1864	pd_entry_t ptepa;
1865	vm_page_t m;
1866
1867	/*
1868	 * Calculate pagetable page index
1869	 */
1870	ptepindex = va >> PDRSHIFT;
1871retry:
1872	/*
1873	 * Get the page directory entry
1874	 */
1875	ptepa = pmap->pm_pdir[ptepindex];
1876
1877	/*
1878	 * This supports switching from a 4MB page to a
1879	 * normal 4K page.
1880	 */
1881	if (ptepa & PG_PS) {
1882		(void)pmap_demote_pde(pmap, &pmap->pm_pdir[ptepindex], va);
1883		ptepa = pmap->pm_pdir[ptepindex];
1884	}
1885
1886	/*
1887	 * If the page table page is mapped, we just increment the
1888	 * hold count, and activate it.
1889	 */
1890	if (ptepa) {
1891		m = PHYS_TO_VM_PAGE(ptepa & PG_FRAME);
1892		m->wire_count++;
1893	} else {
1894		/*
1895		 * Here if the pte page isn't mapped, or if it has
1896		 * been deallocated.
1897		 */
1898		m = _pmap_allocpte(pmap, ptepindex, flags);
1899		if (m == NULL && (flags & PMAP_ENTER_NOSLEEP) == 0)
1900			goto retry;
1901	}
1902	return (m);
1903}
1904
1905
1906/***************************************************
1907* Pmap allocation/deallocation routines.
1908 ***************************************************/
1909
1910#ifdef SMP
1911/*
1912 * Deal with a SMP shootdown of other users of the pmap that we are
1913 * trying to dispose of.  This can be a bit hairy.
1914 */
1915static cpuset_t *lazymask;
1916static u_int lazyptd;
1917static volatile u_int lazywait;
1918
1919void pmap_lazyfix_action(void);
1920
1921void
1922pmap_lazyfix_action(void)
1923{
1924
1925#ifdef COUNT_IPIS
1926	(*ipi_lazypmap_counts[PCPU_GET(cpuid)])++;
1927#endif
1928	if (rcr3() == lazyptd)
1929		load_cr3(curpcb->pcb_cr3);
1930	CPU_CLR_ATOMIC(PCPU_GET(cpuid), lazymask);
1931	atomic_store_rel_int(&lazywait, 1);
1932}
1933
1934static void
1935pmap_lazyfix_self(u_int cpuid)
1936{
1937
1938	if (rcr3() == lazyptd)
1939		load_cr3(curpcb->pcb_cr3);
1940	CPU_CLR_ATOMIC(cpuid, lazymask);
1941}
1942
1943
1944static void
1945pmap_lazyfix(pmap_t pmap)
1946{
1947	cpuset_t mymask, mask;
1948	u_int cpuid, spins;
1949	int lsb;
1950
1951	mask = pmap->pm_active;
1952	while (!CPU_EMPTY(&mask)) {
1953		spins = 50000000;
1954
1955		/* Find least significant set bit. */
1956		lsb = CPU_FFS(&mask);
1957		MPASS(lsb != 0);
1958		lsb--;
1959		CPU_SETOF(lsb, &mask);
1960		mtx_lock_spin(&smp_ipi_mtx);
1961#ifdef PAE
1962		lazyptd = vtophys(pmap->pm_pdpt);
1963#else
1964		lazyptd = vtophys(pmap->pm_pdir);
1965#endif
1966		cpuid = PCPU_GET(cpuid);
1967
1968		/* Use a cpuset just for having an easy check. */
1969		CPU_SETOF(cpuid, &mymask);
1970		if (!CPU_CMP(&mask, &mymask)) {
1971			lazymask = &pmap->pm_active;
1972			pmap_lazyfix_self(cpuid);
1973		} else {
1974			atomic_store_rel_int((u_int *)&lazymask,
1975			    (u_int)&pmap->pm_active);
1976			atomic_store_rel_int(&lazywait, 0);
1977			ipi_selected(mask, IPI_LAZYPMAP);
1978			while (lazywait == 0) {
1979				ia32_pause();
1980				if (--spins == 0)
1981					break;
1982			}
1983		}
1984		mtx_unlock_spin(&smp_ipi_mtx);
1985		if (spins == 0)
1986			printf("pmap_lazyfix: spun for 50000000\n");
1987		mask = pmap->pm_active;
1988	}
1989}
1990
1991#else	/* SMP */
1992
1993/*
1994 * Cleaning up on uniprocessor is easy.  For various reasons, we're
1995 * unlikely to have to even execute this code, including the fact
1996 * that the cleanup is deferred until the parent does a wait(2), which
1997 * means that another userland process has run.
1998 */
1999static void
2000pmap_lazyfix(pmap_t pmap)
2001{
2002	u_int cr3;
2003
2004	cr3 = vtophys(pmap->pm_pdir);
2005	if (cr3 == rcr3()) {
2006		load_cr3(curpcb->pcb_cr3);
2007		CPU_CLR(PCPU_GET(cpuid), &pmap->pm_active);
2008	}
2009}
2010#endif	/* SMP */
2011
2012/*
2013 * Release any resources held by the given physical map.
2014 * Called when a pmap initialized by pmap_pinit is being released.
2015 * Should only be called if the map contains no valid mappings.
2016 */
2017void
2018pmap_release(pmap_t pmap)
2019{
2020	vm_page_t m, ptdpg[NPGPTD];
2021	int i;
2022
2023	KASSERT(pmap->pm_stats.resident_count == 0,
2024	    ("pmap_release: pmap resident count %ld != 0",
2025	    pmap->pm_stats.resident_count));
2026	KASSERT(vm_radix_is_empty(&pmap->pm_root),
2027	    ("pmap_release: pmap has reserved page table page(s)"));
2028
2029	pmap_lazyfix(pmap);
2030	mtx_lock_spin(&allpmaps_lock);
2031	LIST_REMOVE(pmap, pm_list);
2032	mtx_unlock_spin(&allpmaps_lock);
2033
2034	for (i = 0; i < NPGPTD; i++)
2035		ptdpg[i] = PHYS_TO_VM_PAGE(pmap->pm_pdir[PTDPTDI + i] &
2036		    PG_FRAME);
2037
2038	bzero(pmap->pm_pdir + PTDPTDI, (nkpt + NPGPTD) *
2039	    sizeof(*pmap->pm_pdir));
2040
2041	pmap_qremove((vm_offset_t)pmap->pm_pdir, NPGPTD);
2042
2043	for (i = 0; i < NPGPTD; i++) {
2044		m = ptdpg[i];
2045#ifdef PAE
2046		KASSERT(VM_PAGE_TO_PHYS(m) == (pmap->pm_pdpt[i] & PG_FRAME),
2047		    ("pmap_release: got wrong ptd page"));
2048#endif
2049		m->wire_count--;
2050		atomic_subtract_int(&cnt.v_wire_count, 1);
2051		vm_page_free_zero(m);
2052	}
2053}
2054
2055static int
2056kvm_size(SYSCTL_HANDLER_ARGS)
2057{
2058	unsigned long ksize = VM_MAX_KERNEL_ADDRESS - KERNBASE;
2059
2060	return (sysctl_handle_long(oidp, &ksize, 0, req));
2061}
2062SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
2063    0, 0, kvm_size, "IU", "Size of KVM");
2064
2065static int
2066kvm_free(SYSCTL_HANDLER_ARGS)
2067{
2068	unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
2069
2070	return (sysctl_handle_long(oidp, &kfree, 0, req));
2071}
2072SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
2073    0, 0, kvm_free, "IU", "Amount of KVM free");
2074
2075/*
2076 * grow the number of kernel page table entries, if needed
2077 */
2078void
2079pmap_growkernel(vm_offset_t addr)
2080{
2081	vm_paddr_t ptppaddr;
2082	vm_page_t nkpg;
2083	pd_entry_t newpdir;
2084
2085	mtx_assert(&kernel_map->system_mtx, MA_OWNED);
2086	addr = roundup2(addr, NBPDR);
2087	if (addr - 1 >= kernel_map->max_offset)
2088		addr = kernel_map->max_offset;
2089	while (kernel_vm_end < addr) {
2090		if (pdir_pde(PTD, kernel_vm_end)) {
2091			kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2092			if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2093				kernel_vm_end = kernel_map->max_offset;
2094				break;
2095			}
2096			continue;
2097		}
2098
2099		nkpg = vm_page_alloc(NULL, kernel_vm_end >> PDRSHIFT,
2100		    VM_ALLOC_INTERRUPT | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
2101		    VM_ALLOC_ZERO);
2102		if (nkpg == NULL)
2103			panic("pmap_growkernel: no memory to grow kernel");
2104
2105		nkpt++;
2106
2107		if ((nkpg->flags & PG_ZERO) == 0)
2108			pmap_zero_page(nkpg);
2109		ptppaddr = VM_PAGE_TO_PHYS(nkpg);
2110		newpdir = (pd_entry_t) (ptppaddr | PG_V | PG_RW | PG_A | PG_M);
2111		pdir_pde(KPTD, kernel_vm_end) = pgeflag | newpdir;
2112
2113		pmap_kenter_pde(kernel_vm_end, newpdir);
2114		kernel_vm_end = (kernel_vm_end + NBPDR) & ~PDRMASK;
2115		if (kernel_vm_end - 1 >= kernel_map->max_offset) {
2116			kernel_vm_end = kernel_map->max_offset;
2117			break;
2118		}
2119	}
2120}
2121
2122
2123/***************************************************
2124 * page management routines.
2125 ***************************************************/
2126
2127CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
2128CTASSERT(_NPCM == 11);
2129CTASSERT(_NPCPV == 336);
2130
2131static __inline struct pv_chunk *
2132pv_to_chunk(pv_entry_t pv)
2133{
2134
2135	return ((struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK));
2136}
2137
2138#define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
2139
2140#define	PC_FREE0_9	0xfffffffful	/* Free values for index 0 through 9 */
2141#define	PC_FREE10	0x0000fffful	/* Free values for index 10 */
2142
2143static const uint32_t pc_freemask[_NPCM] = {
2144	PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
2145	PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
2146	PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
2147	PC_FREE0_9, PC_FREE10
2148};
2149
2150SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
2151	"Current number of pv entries");
2152
2153#ifdef PV_STATS
2154static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
2155
2156SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
2157	"Current number of pv entry chunks");
2158SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
2159	"Current number of pv entry chunks allocated");
2160SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
2161	"Current number of pv entry chunks frees");
2162SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
2163	"Number of times tried to get a chunk page but failed.");
2164
2165static long pv_entry_frees, pv_entry_allocs;
2166static int pv_entry_spare;
2167
2168SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
2169	"Current number of pv entry frees");
2170SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
2171	"Current number of pv entry allocs");
2172SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
2173	"Current number of spare pv entries");
2174#endif
2175
2176/*
2177 * We are in a serious low memory condition.  Resort to
2178 * drastic measures to free some pages so we can allocate
2179 * another pv entry chunk.
2180 */
2181static vm_page_t
2182pmap_pv_reclaim(pmap_t locked_pmap)
2183{
2184	struct pch newtail;
2185	struct pv_chunk *pc;
2186	struct md_page *pvh;
2187	pd_entry_t *pde;
2188	pmap_t pmap;
2189	pt_entry_t *pte, tpte;
2190	pv_entry_t pv;
2191	vm_offset_t va;
2192	vm_page_t m, m_pc;
2193	struct spglist free;
2194	uint32_t inuse;
2195	int bit, field, freed;
2196
2197	PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
2198	pmap = NULL;
2199	m_pc = NULL;
2200	SLIST_INIT(&free);
2201	TAILQ_INIT(&newtail);
2202	while ((pc = TAILQ_FIRST(&pv_chunks)) != NULL && (pv_vafree == 0 ||
2203	    SLIST_EMPTY(&free))) {
2204		TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2205		if (pmap != pc->pc_pmap) {
2206			if (pmap != NULL) {
2207				pmap_invalidate_all(pmap);
2208				if (pmap != locked_pmap)
2209					PMAP_UNLOCK(pmap);
2210			}
2211			pmap = pc->pc_pmap;
2212			/* Avoid deadlock and lock recursion. */
2213			if (pmap > locked_pmap)
2214				PMAP_LOCK(pmap);
2215			else if (pmap != locked_pmap && !PMAP_TRYLOCK(pmap)) {
2216				pmap = NULL;
2217				TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
2218				continue;
2219			}
2220		}
2221
2222		/*
2223		 * Destroy every non-wired, 4 KB page mapping in the chunk.
2224		 */
2225		freed = 0;
2226		for (field = 0; field < _NPCM; field++) {
2227			for (inuse = ~pc->pc_map[field] & pc_freemask[field];
2228			    inuse != 0; inuse &= ~(1UL << bit)) {
2229				bit = bsfl(inuse);
2230				pv = &pc->pc_pventry[field * 32 + bit];
2231				va = pv->pv_va;
2232				pde = pmap_pde(pmap, va);
2233				if ((*pde & PG_PS) != 0)
2234					continue;
2235				pte = pmap_pte(pmap, va);
2236				tpte = *pte;
2237				if ((tpte & PG_W) == 0)
2238					tpte = pte_load_clear(pte);
2239				pmap_pte_release(pte);
2240				if ((tpte & PG_W) != 0)
2241					continue;
2242				KASSERT(tpte != 0,
2243				    ("pmap_pv_reclaim: pmap %p va %x zero pte",
2244				    pmap, va));
2245				if ((tpte & PG_G) != 0)
2246					pmap_invalidate_page(pmap, va);
2247				m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
2248				if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
2249					vm_page_dirty(m);
2250				if ((tpte & PG_A) != 0)
2251					vm_page_aflag_set(m, PGA_REFERENCED);
2252				TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
2253				if (TAILQ_EMPTY(&m->md.pv_list) &&
2254				    (m->flags & PG_FICTITIOUS) == 0) {
2255					pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
2256					if (TAILQ_EMPTY(&pvh->pv_list)) {
2257						vm_page_aflag_clear(m,
2258						    PGA_WRITEABLE);
2259					}
2260				}
2261				pc->pc_map[field] |= 1UL << bit;
2262				pmap_unuse_pt(pmap, va, &free);
2263				freed++;
2264			}
2265		}
2266		if (freed == 0) {
2267			TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
2268			continue;
2269		}
2270		/* Every freed mapping is for a 4 KB page. */
2271		pmap->pm_stats.resident_count -= freed;
2272		PV_STAT(pv_entry_frees += freed);
2273		PV_STAT(pv_entry_spare += freed);
2274		pv_entry_count -= freed;
2275		TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2276		for (field = 0; field < _NPCM; field++)
2277			if (pc->pc_map[field] != pc_freemask[field]) {
2278				TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc,
2279				    pc_list);
2280				TAILQ_INSERT_TAIL(&newtail, pc, pc_lru);
2281
2282				/*
2283				 * One freed pv entry in locked_pmap is
2284				 * sufficient.
2285				 */
2286				if (pmap == locked_pmap)
2287					goto out;
2288				break;
2289			}
2290		if (field == _NPCM) {
2291			PV_STAT(pv_entry_spare -= _NPCPV);
2292			PV_STAT(pc_chunk_count--);
2293			PV_STAT(pc_chunk_frees++);
2294			/* Entire chunk is free; return it. */
2295			m_pc = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)pc));
2296			pmap_qremove((vm_offset_t)pc, 1);
2297			pmap_ptelist_free(&pv_vafree, (vm_offset_t)pc);
2298			break;
2299		}
2300	}
2301out:
2302	TAILQ_CONCAT(&pv_chunks, &newtail, pc_lru);
2303	if (pmap != NULL) {
2304		pmap_invalidate_all(pmap);
2305		if (pmap != locked_pmap)
2306			PMAP_UNLOCK(pmap);
2307	}
2308	if (m_pc == NULL && pv_vafree != 0 && SLIST_EMPTY(&free)) {
2309		m_pc = SLIST_FIRST(&free);
2310		SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2311		/* Recycle a freed page table page. */
2312		m_pc->wire_count = 1;
2313		atomic_add_int(&cnt.v_wire_count, 1);
2314	}
2315	pmap_free_zero_pages(&free);
2316	return (m_pc);
2317}
2318
2319/*
2320 * free the pv_entry back to the free list
2321 */
2322static void
2323free_pv_entry(pmap_t pmap, pv_entry_t pv)
2324{
2325	struct pv_chunk *pc;
2326	int idx, field, bit;
2327
2328	rw_assert(&pvh_global_lock, RA_WLOCKED);
2329	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2330	PV_STAT(pv_entry_frees++);
2331	PV_STAT(pv_entry_spare++);
2332	pv_entry_count--;
2333	pc = pv_to_chunk(pv);
2334	idx = pv - &pc->pc_pventry[0];
2335	field = idx / 32;
2336	bit = idx % 32;
2337	pc->pc_map[field] |= 1ul << bit;
2338	for (idx = 0; idx < _NPCM; idx++)
2339		if (pc->pc_map[idx] != pc_freemask[idx]) {
2340			/*
2341			 * 98% of the time, pc is already at the head of the
2342			 * list.  If it isn't already, move it to the head.
2343			 */
2344			if (__predict_false(TAILQ_FIRST(&pmap->pm_pvchunk) !=
2345			    pc)) {
2346				TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2347				TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc,
2348				    pc_list);
2349			}
2350			return;
2351		}
2352	TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2353	free_pv_chunk(pc);
2354}
2355
2356static void
2357free_pv_chunk(struct pv_chunk *pc)
2358{
2359	vm_page_t m;
2360
2361 	TAILQ_REMOVE(&pv_chunks, pc, pc_lru);
2362	PV_STAT(pv_entry_spare -= _NPCPV);
2363	PV_STAT(pc_chunk_count--);
2364	PV_STAT(pc_chunk_frees++);
2365	/* entire chunk is free, return it */
2366	m = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)pc));
2367	pmap_qremove((vm_offset_t)pc, 1);
2368	vm_page_unwire(m, 0);
2369	vm_page_free(m);
2370	pmap_ptelist_free(&pv_vafree, (vm_offset_t)pc);
2371}
2372
2373/*
2374 * get a new pv_entry, allocating a block from the system
2375 * when needed.
2376 */
2377static pv_entry_t
2378get_pv_entry(pmap_t pmap, boolean_t try)
2379{
2380	static const struct timeval printinterval = { 60, 0 };
2381	static struct timeval lastprint;
2382	int bit, field;
2383	pv_entry_t pv;
2384	struct pv_chunk *pc;
2385	vm_page_t m;
2386
2387	rw_assert(&pvh_global_lock, RA_WLOCKED);
2388	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2389	PV_STAT(pv_entry_allocs++);
2390	pv_entry_count++;
2391	if (pv_entry_count > pv_entry_high_water)
2392		if (ratecheck(&lastprint, &printinterval))
2393			printf("Approaching the limit on PV entries, consider "
2394			    "increasing either the vm.pmap.shpgperproc or the "
2395			    "vm.pmap.pv_entry_max tunable.\n");
2396retry:
2397	pc = TAILQ_FIRST(&pmap->pm_pvchunk);
2398	if (pc != NULL) {
2399		for (field = 0; field < _NPCM; field++) {
2400			if (pc->pc_map[field]) {
2401				bit = bsfl(pc->pc_map[field]);
2402				break;
2403			}
2404		}
2405		if (field < _NPCM) {
2406			pv = &pc->pc_pventry[field * 32 + bit];
2407			pc->pc_map[field] &= ~(1ul << bit);
2408			/* If this was the last item, move it to tail */
2409			for (field = 0; field < _NPCM; field++)
2410				if (pc->pc_map[field] != 0) {
2411					PV_STAT(pv_entry_spare--);
2412					return (pv);	/* not full, return */
2413				}
2414			TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
2415			TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
2416			PV_STAT(pv_entry_spare--);
2417			return (pv);
2418		}
2419	}
2420	/*
2421	 * Access to the ptelist "pv_vafree" is synchronized by the pvh
2422	 * global lock.  If "pv_vafree" is currently non-empty, it will
2423	 * remain non-empty until pmap_ptelist_alloc() completes.
2424	 */
2425	if (pv_vafree == 0 || (m = vm_page_alloc(NULL, 0, VM_ALLOC_NORMAL |
2426	    VM_ALLOC_NOOBJ | VM_ALLOC_WIRED)) == NULL) {
2427		if (try) {
2428			pv_entry_count--;
2429			PV_STAT(pc_chunk_tryfail++);
2430			return (NULL);
2431		}
2432		m = pmap_pv_reclaim(pmap);
2433		if (m == NULL)
2434			goto retry;
2435	}
2436	PV_STAT(pc_chunk_count++);
2437	PV_STAT(pc_chunk_allocs++);
2438	pc = (struct pv_chunk *)pmap_ptelist_alloc(&pv_vafree);
2439	pmap_qenter((vm_offset_t)pc, &m, 1);
2440	pc->pc_pmap = pmap;
2441	pc->pc_map[0] = pc_freemask[0] & ~1ul;	/* preallocated bit 0 */
2442	for (field = 1; field < _NPCM; field++)
2443		pc->pc_map[field] = pc_freemask[field];
2444	TAILQ_INSERT_TAIL(&pv_chunks, pc, pc_lru);
2445	pv = &pc->pc_pventry[0];
2446	TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
2447	PV_STAT(pv_entry_spare += _NPCPV - 1);
2448	return (pv);
2449}
2450
2451static __inline pv_entry_t
2452pmap_pvh_remove(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
2453{
2454	pv_entry_t pv;
2455
2456	rw_assert(&pvh_global_lock, RA_WLOCKED);
2457	TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
2458		if (pmap == PV_PMAP(pv) && va == pv->pv_va) {
2459			TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
2460			break;
2461		}
2462	}
2463	return (pv);
2464}
2465
2466static void
2467pmap_pv_demote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa)
2468{
2469	struct md_page *pvh;
2470	pv_entry_t pv;
2471	vm_offset_t va_last;
2472	vm_page_t m;
2473
2474	rw_assert(&pvh_global_lock, RA_WLOCKED);
2475	KASSERT((pa & PDRMASK) == 0,
2476	    ("pmap_pv_demote_pde: pa is not 4mpage aligned"));
2477
2478	/*
2479	 * Transfer the 4mpage's pv entry for this mapping to the first
2480	 * page's pv list.
2481	 */
2482	pvh = pa_to_pvh(pa);
2483	va = trunc_4mpage(va);
2484	pv = pmap_pvh_remove(pvh, pmap, va);
2485	KASSERT(pv != NULL, ("pmap_pv_demote_pde: pv not found"));
2486	m = PHYS_TO_VM_PAGE(pa);
2487	TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
2488	/* Instantiate the remaining NPTEPG - 1 pv entries. */
2489	va_last = va + NBPDR - PAGE_SIZE;
2490	do {
2491		m++;
2492		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
2493		    ("pmap_pv_demote_pde: page %p is not managed", m));
2494		va += PAGE_SIZE;
2495		pmap_insert_entry(pmap, va, m);
2496	} while (va < va_last);
2497}
2498
2499static void
2500pmap_pv_promote_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa)
2501{
2502	struct md_page *pvh;
2503	pv_entry_t pv;
2504	vm_offset_t va_last;
2505	vm_page_t m;
2506
2507	rw_assert(&pvh_global_lock, RA_WLOCKED);
2508	KASSERT((pa & PDRMASK) == 0,
2509	    ("pmap_pv_promote_pde: pa is not 4mpage aligned"));
2510
2511	/*
2512	 * Transfer the first page's pv entry for this mapping to the
2513	 * 4mpage's pv list.  Aside from avoiding the cost of a call
2514	 * to get_pv_entry(), a transfer avoids the possibility that
2515	 * get_pv_entry() calls pmap_collect() and that pmap_collect()
2516	 * removes one of the mappings that is being promoted.
2517	 */
2518	m = PHYS_TO_VM_PAGE(pa);
2519	va = trunc_4mpage(va);
2520	pv = pmap_pvh_remove(&m->md, pmap, va);
2521	KASSERT(pv != NULL, ("pmap_pv_promote_pde: pv not found"));
2522	pvh = pa_to_pvh(pa);
2523	TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
2524	/* Free the remaining NPTEPG - 1 pv entries. */
2525	va_last = va + NBPDR - PAGE_SIZE;
2526	do {
2527		m++;
2528		va += PAGE_SIZE;
2529		pmap_pvh_free(&m->md, pmap, va);
2530	} while (va < va_last);
2531}
2532
2533static void
2534pmap_pvh_free(struct md_page *pvh, pmap_t pmap, vm_offset_t va)
2535{
2536	pv_entry_t pv;
2537
2538	pv = pmap_pvh_remove(pvh, pmap, va);
2539	KASSERT(pv != NULL, ("pmap_pvh_free: pv not found"));
2540	free_pv_entry(pmap, pv);
2541}
2542
2543static void
2544pmap_remove_entry(pmap_t pmap, vm_page_t m, vm_offset_t va)
2545{
2546	struct md_page *pvh;
2547
2548	rw_assert(&pvh_global_lock, RA_WLOCKED);
2549	pmap_pvh_free(&m->md, pmap, va);
2550	if (TAILQ_EMPTY(&m->md.pv_list) && (m->flags & PG_FICTITIOUS) == 0) {
2551		pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
2552		if (TAILQ_EMPTY(&pvh->pv_list))
2553			vm_page_aflag_clear(m, PGA_WRITEABLE);
2554	}
2555}
2556
2557/*
2558 * Create a pv entry for page at pa for
2559 * (pmap, va).
2560 */
2561static void
2562pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t m)
2563{
2564	pv_entry_t pv;
2565
2566	rw_assert(&pvh_global_lock, RA_WLOCKED);
2567	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2568	pv = get_pv_entry(pmap, FALSE);
2569	pv->pv_va = va;
2570	TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
2571}
2572
2573/*
2574 * Conditionally create a pv entry.
2575 */
2576static boolean_t
2577pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m)
2578{
2579	pv_entry_t pv;
2580
2581	rw_assert(&pvh_global_lock, RA_WLOCKED);
2582	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2583	if (pv_entry_count < pv_entry_high_water &&
2584	    (pv = get_pv_entry(pmap, TRUE)) != NULL) {
2585		pv->pv_va = va;
2586		TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
2587		return (TRUE);
2588	} else
2589		return (FALSE);
2590}
2591
2592/*
2593 * Create the pv entries for each of the pages within a superpage.
2594 */
2595static boolean_t
2596pmap_pv_insert_pde(pmap_t pmap, vm_offset_t va, vm_paddr_t pa)
2597{
2598	struct md_page *pvh;
2599	pv_entry_t pv;
2600
2601	rw_assert(&pvh_global_lock, RA_WLOCKED);
2602	if (pv_entry_count < pv_entry_high_water &&
2603	    (pv = get_pv_entry(pmap, TRUE)) != NULL) {
2604		pv->pv_va = va;
2605		pvh = pa_to_pvh(pa);
2606		TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
2607		return (TRUE);
2608	} else
2609		return (FALSE);
2610}
2611
2612/*
2613 * Fills a page table page with mappings to consecutive physical pages.
2614 */
2615static void
2616pmap_fill_ptp(pt_entry_t *firstpte, pt_entry_t newpte)
2617{
2618	pt_entry_t *pte;
2619
2620	for (pte = firstpte; pte < firstpte + NPTEPG; pte++) {
2621		*pte = newpte;
2622		newpte += PAGE_SIZE;
2623	}
2624}
2625
2626/*
2627 * Tries to demote a 2- or 4MB page mapping.  If demotion fails, the
2628 * 2- or 4MB page mapping is invalidated.
2629 */
2630static boolean_t
2631pmap_demote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
2632{
2633	pd_entry_t newpde, oldpde;
2634	pt_entry_t *firstpte, newpte;
2635	vm_paddr_t mptepa;
2636	vm_page_t mpte;
2637	struct spglist free;
2638
2639	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2640	oldpde = *pde;
2641	KASSERT((oldpde & (PG_PS | PG_V)) == (PG_PS | PG_V),
2642	    ("pmap_demote_pde: oldpde is missing PG_PS and/or PG_V"));
2643	if ((oldpde & PG_A) != 0 && (mpte = pmap_lookup_pt_page(pmap, va)) !=
2644	    NULL)
2645		pmap_remove_pt_page(pmap, mpte);
2646	else {
2647		KASSERT((oldpde & PG_W) == 0,
2648		    ("pmap_demote_pde: page table page for a wired mapping"
2649		    " is missing"));
2650
2651		/*
2652		 * Invalidate the 2- or 4MB page mapping and return
2653		 * "failure" if the mapping was never accessed or the
2654		 * allocation of the new page table page fails.
2655		 */
2656		if ((oldpde & PG_A) == 0 || (mpte = vm_page_alloc(NULL,
2657		    va >> PDRSHIFT, VM_ALLOC_NOOBJ | VM_ALLOC_NORMAL |
2658		    VM_ALLOC_WIRED)) == NULL) {
2659			SLIST_INIT(&free);
2660			pmap_remove_pde(pmap, pde, trunc_4mpage(va), &free);
2661			pmap_invalidate_page(pmap, trunc_4mpage(va));
2662			pmap_free_zero_pages(&free);
2663			CTR2(KTR_PMAP, "pmap_demote_pde: failure for va %#x"
2664			    " in pmap %p", va, pmap);
2665			return (FALSE);
2666		}
2667		if (va < VM_MAXUSER_ADDRESS)
2668			pmap->pm_stats.resident_count++;
2669	}
2670	mptepa = VM_PAGE_TO_PHYS(mpte);
2671
2672	/*
2673	 * If the page mapping is in the kernel's address space, then the
2674	 * KPTmap can provide access to the page table page.  Otherwise,
2675	 * temporarily map the page table page (mpte) into the kernel's
2676	 * address space at either PADDR1 or PADDR2.
2677	 */
2678	if (va >= KERNBASE)
2679		firstpte = &KPTmap[i386_btop(trunc_4mpage(va))];
2680	else if (curthread->td_pinned > 0 && rw_wowned(&pvh_global_lock)) {
2681		if ((*PMAP1 & PG_FRAME) != mptepa) {
2682			*PMAP1 = mptepa | PG_RW | PG_V | PG_A | PG_M;
2683#ifdef SMP
2684			PMAP1cpu = PCPU_GET(cpuid);
2685#endif
2686			invlcaddr(PADDR1);
2687			PMAP1changed++;
2688		} else
2689#ifdef SMP
2690		if (PMAP1cpu != PCPU_GET(cpuid)) {
2691			PMAP1cpu = PCPU_GET(cpuid);
2692			invlcaddr(PADDR1);
2693			PMAP1changedcpu++;
2694		} else
2695#endif
2696			PMAP1unchanged++;
2697		firstpte = PADDR1;
2698	} else {
2699		mtx_lock(&PMAP2mutex);
2700		if ((*PMAP2 & PG_FRAME) != mptepa) {
2701			*PMAP2 = mptepa | PG_RW | PG_V | PG_A | PG_M;
2702			pmap_invalidate_page(kernel_pmap, (vm_offset_t)PADDR2);
2703		}
2704		firstpte = PADDR2;
2705	}
2706	newpde = mptepa | PG_M | PG_A | (oldpde & PG_U) | PG_RW | PG_V;
2707	KASSERT((oldpde & PG_A) != 0,
2708	    ("pmap_demote_pde: oldpde is missing PG_A"));
2709	KASSERT((oldpde & (PG_M | PG_RW)) != PG_RW,
2710	    ("pmap_demote_pde: oldpde is missing PG_M"));
2711	newpte = oldpde & ~PG_PS;
2712	if ((newpte & PG_PDE_PAT) != 0)
2713		newpte ^= PG_PDE_PAT | PG_PTE_PAT;
2714
2715	/*
2716	 * If the page table page is new, initialize it.
2717	 */
2718	if (mpte->wire_count == 1) {
2719		mpte->wire_count = NPTEPG;
2720		pmap_fill_ptp(firstpte, newpte);
2721	}
2722	KASSERT((*firstpte & PG_FRAME) == (newpte & PG_FRAME),
2723	    ("pmap_demote_pde: firstpte and newpte map different physical"
2724	    " addresses"));
2725
2726	/*
2727	 * If the mapping has changed attributes, update the page table
2728	 * entries.
2729	 */
2730	if ((*firstpte & PG_PTE_PROMOTE) != (newpte & PG_PTE_PROMOTE))
2731		pmap_fill_ptp(firstpte, newpte);
2732
2733	/*
2734	 * Demote the mapping.  This pmap is locked.  The old PDE has
2735	 * PG_A set.  If the old PDE has PG_RW set, it also has PG_M
2736	 * set.  Thus, there is no danger of a race with another
2737	 * processor changing the setting of PG_A and/or PG_M between
2738	 * the read above and the store below.
2739	 */
2740	if (workaround_erratum383)
2741		pmap_update_pde(pmap, va, pde, newpde);
2742	else if (pmap == kernel_pmap)
2743		pmap_kenter_pde(va, newpde);
2744	else
2745		pde_store(pde, newpde);
2746	if (firstpte == PADDR2)
2747		mtx_unlock(&PMAP2mutex);
2748
2749	/*
2750	 * Invalidate the recursive mapping of the page table page.
2751	 */
2752	pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
2753
2754	/*
2755	 * Demote the pv entry.  This depends on the earlier demotion
2756	 * of the mapping.  Specifically, the (re)creation of a per-
2757	 * page pv entry might trigger the execution of pmap_collect(),
2758	 * which might reclaim a newly (re)created per-page pv entry
2759	 * and destroy the associated mapping.  In order to destroy
2760	 * the mapping, the PDE must have already changed from mapping
2761	 * the 2mpage to referencing the page table page.
2762	 */
2763	if ((oldpde & PG_MANAGED) != 0)
2764		pmap_pv_demote_pde(pmap, va, oldpde & PG_PS_FRAME);
2765
2766	pmap_pde_demotions++;
2767	CTR2(KTR_PMAP, "pmap_demote_pde: success for va %#x"
2768	    " in pmap %p", va, pmap);
2769	return (TRUE);
2770}
2771
2772/*
2773 * Removes a 2- or 4MB page mapping from the kernel pmap.
2774 */
2775static void
2776pmap_remove_kernel_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
2777{
2778	pd_entry_t newpde;
2779	vm_paddr_t mptepa;
2780	vm_page_t mpte;
2781
2782	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2783	mpte = pmap_lookup_pt_page(pmap, va);
2784	if (mpte == NULL)
2785		panic("pmap_remove_kernel_pde: Missing pt page.");
2786
2787	pmap_remove_pt_page(pmap, mpte);
2788	mptepa = VM_PAGE_TO_PHYS(mpte);
2789	newpde = mptepa | PG_M | PG_A | PG_RW | PG_V;
2790
2791	/*
2792	 * Initialize the page table page.
2793	 */
2794	pagezero((void *)&KPTmap[i386_btop(trunc_4mpage(va))]);
2795
2796	/*
2797	 * Remove the mapping.
2798	 */
2799	if (workaround_erratum383)
2800		pmap_update_pde(pmap, va, pde, newpde);
2801	else
2802		pmap_kenter_pde(va, newpde);
2803
2804	/*
2805	 * Invalidate the recursive mapping of the page table page.
2806	 */
2807	pmap_invalidate_page(pmap, (vm_offset_t)vtopte(va));
2808}
2809
2810/*
2811 * pmap_remove_pde: do the things to unmap a superpage in a process
2812 */
2813static void
2814pmap_remove_pde(pmap_t pmap, pd_entry_t *pdq, vm_offset_t sva,
2815    struct spglist *free)
2816{
2817	struct md_page *pvh;
2818	pd_entry_t oldpde;
2819	vm_offset_t eva, va;
2820	vm_page_t m, mpte;
2821
2822	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2823	KASSERT((sva & PDRMASK) == 0,
2824	    ("pmap_remove_pde: sva is not 4mpage aligned"));
2825	oldpde = pte_load_clear(pdq);
2826	if (oldpde & PG_W)
2827		pmap->pm_stats.wired_count -= NBPDR / PAGE_SIZE;
2828
2829	/*
2830	 * Machines that don't support invlpg, also don't support
2831	 * PG_G.
2832	 */
2833	if (oldpde & PG_G)
2834		pmap_invalidate_page(kernel_pmap, sva);
2835	pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
2836	if (oldpde & PG_MANAGED) {
2837		pvh = pa_to_pvh(oldpde & PG_PS_FRAME);
2838		pmap_pvh_free(pvh, pmap, sva);
2839		eva = sva + NBPDR;
2840		for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
2841		    va < eva; va += PAGE_SIZE, m++) {
2842			if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
2843				vm_page_dirty(m);
2844			if (oldpde & PG_A)
2845				vm_page_aflag_set(m, PGA_REFERENCED);
2846			if (TAILQ_EMPTY(&m->md.pv_list) &&
2847			    TAILQ_EMPTY(&pvh->pv_list))
2848				vm_page_aflag_clear(m, PGA_WRITEABLE);
2849		}
2850	}
2851	if (pmap == kernel_pmap) {
2852		pmap_remove_kernel_pde(pmap, pdq, sva);
2853	} else {
2854		mpte = pmap_lookup_pt_page(pmap, sva);
2855		if (mpte != NULL) {
2856			pmap_remove_pt_page(pmap, mpte);
2857			pmap->pm_stats.resident_count--;
2858			KASSERT(mpte->wire_count == NPTEPG,
2859			    ("pmap_remove_pde: pte page wire count error"));
2860			mpte->wire_count = 0;
2861			pmap_add_delayed_free_list(mpte, free, FALSE);
2862			atomic_subtract_int(&cnt.v_wire_count, 1);
2863		}
2864	}
2865}
2866
2867/*
2868 * pmap_remove_pte: do the things to unmap a page in a process
2869 */
2870static int
2871pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va,
2872    struct spglist *free)
2873{
2874	pt_entry_t oldpte;
2875	vm_page_t m;
2876
2877	rw_assert(&pvh_global_lock, RA_WLOCKED);
2878	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2879	oldpte = pte_load_clear(ptq);
2880	KASSERT(oldpte != 0,
2881	    ("pmap_remove_pte: pmap %p va %x zero pte", pmap, va));
2882	if (oldpte & PG_W)
2883		pmap->pm_stats.wired_count -= 1;
2884	/*
2885	 * Machines that don't support invlpg, also don't support
2886	 * PG_G.
2887	 */
2888	if (oldpte & PG_G)
2889		pmap_invalidate_page(kernel_pmap, va);
2890	pmap->pm_stats.resident_count -= 1;
2891	if (oldpte & PG_MANAGED) {
2892		m = PHYS_TO_VM_PAGE(oldpte & PG_FRAME);
2893		if ((oldpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
2894			vm_page_dirty(m);
2895		if (oldpte & PG_A)
2896			vm_page_aflag_set(m, PGA_REFERENCED);
2897		pmap_remove_entry(pmap, m, va);
2898	}
2899	return (pmap_unuse_pt(pmap, va, free));
2900}
2901
2902/*
2903 * Remove a single page from a process address space
2904 */
2905static void
2906pmap_remove_page(pmap_t pmap, vm_offset_t va, struct spglist *free)
2907{
2908	pt_entry_t *pte;
2909
2910	rw_assert(&pvh_global_lock, RA_WLOCKED);
2911	KASSERT(curthread->td_pinned > 0, ("curthread not pinned"));
2912	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2913	if ((pte = pmap_pte_quick(pmap, va)) == NULL || *pte == 0)
2914		return;
2915	pmap_remove_pte(pmap, pte, va, free);
2916	pmap_invalidate_page(pmap, va);
2917}
2918
2919/*
2920 *	Remove the given range of addresses from the specified map.
2921 *
2922 *	It is assumed that the start and end are properly
2923 *	rounded to the page size.
2924 */
2925void
2926pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
2927{
2928	vm_offset_t pdnxt;
2929	pd_entry_t ptpaddr;
2930	pt_entry_t *pte;
2931	struct spglist free;
2932	int anyvalid;
2933
2934	/*
2935	 * Perform an unsynchronized read.  This is, however, safe.
2936	 */
2937	if (pmap->pm_stats.resident_count == 0)
2938		return;
2939
2940	anyvalid = 0;
2941	SLIST_INIT(&free);
2942
2943	rw_wlock(&pvh_global_lock);
2944	sched_pin();
2945	PMAP_LOCK(pmap);
2946
2947	/*
2948	 * special handling of removing one page.  a very
2949	 * common operation and easy to short circuit some
2950	 * code.
2951	 */
2952	if ((sva + PAGE_SIZE == eva) &&
2953	    ((pmap->pm_pdir[(sva >> PDRSHIFT)] & PG_PS) == 0)) {
2954		pmap_remove_page(pmap, sva, &free);
2955		goto out;
2956	}
2957
2958	for (; sva < eva; sva = pdnxt) {
2959		u_int pdirindex;
2960
2961		/*
2962		 * Calculate index for next page table.
2963		 */
2964		pdnxt = (sva + NBPDR) & ~PDRMASK;
2965		if (pdnxt < sva)
2966			pdnxt = eva;
2967		if (pmap->pm_stats.resident_count == 0)
2968			break;
2969
2970		pdirindex = sva >> PDRSHIFT;
2971		ptpaddr = pmap->pm_pdir[pdirindex];
2972
2973		/*
2974		 * Weed out invalid mappings. Note: we assume that the page
2975		 * directory table is always allocated, and in kernel virtual.
2976		 */
2977		if (ptpaddr == 0)
2978			continue;
2979
2980		/*
2981		 * Check for large page.
2982		 */
2983		if ((ptpaddr & PG_PS) != 0) {
2984			/*
2985			 * Are we removing the entire large page?  If not,
2986			 * demote the mapping and fall through.
2987			 */
2988			if (sva + NBPDR == pdnxt && eva >= pdnxt) {
2989				/*
2990				 * The TLB entry for a PG_G mapping is
2991				 * invalidated by pmap_remove_pde().
2992				 */
2993				if ((ptpaddr & PG_G) == 0)
2994					anyvalid = 1;
2995				pmap_remove_pde(pmap,
2996				    &pmap->pm_pdir[pdirindex], sva, &free);
2997				continue;
2998			} else if (!pmap_demote_pde(pmap,
2999			    &pmap->pm_pdir[pdirindex], sva)) {
3000				/* The large page mapping was destroyed. */
3001				continue;
3002			}
3003		}
3004
3005		/*
3006		 * Limit our scan to either the end of the va represented
3007		 * by the current page table page, or to the end of the
3008		 * range being removed.
3009		 */
3010		if (pdnxt > eva)
3011			pdnxt = eva;
3012
3013		for (pte = pmap_pte_quick(pmap, sva); sva != pdnxt; pte++,
3014		    sva += PAGE_SIZE) {
3015			if (*pte == 0)
3016				continue;
3017
3018			/*
3019			 * The TLB entry for a PG_G mapping is invalidated
3020			 * by pmap_remove_pte().
3021			 */
3022			if ((*pte & PG_G) == 0)
3023				anyvalid = 1;
3024			if (pmap_remove_pte(pmap, pte, sva, &free))
3025				break;
3026		}
3027	}
3028out:
3029	sched_unpin();
3030	if (anyvalid)
3031		pmap_invalidate_all(pmap);
3032	rw_wunlock(&pvh_global_lock);
3033	PMAP_UNLOCK(pmap);
3034	pmap_free_zero_pages(&free);
3035}
3036
3037/*
3038 *	Routine:	pmap_remove_all
3039 *	Function:
3040 *		Removes this physical page from
3041 *		all physical maps in which it resides.
3042 *		Reflects back modify bits to the pager.
3043 *
3044 *	Notes:
3045 *		Original versions of this routine were very
3046 *		inefficient because they iteratively called
3047 *		pmap_remove (slow...)
3048 */
3049
3050void
3051pmap_remove_all(vm_page_t m)
3052{
3053	struct md_page *pvh;
3054	pv_entry_t pv;
3055	pmap_t pmap;
3056	pt_entry_t *pte, tpte;
3057	pd_entry_t *pde;
3058	vm_offset_t va;
3059	struct spglist free;
3060
3061	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3062	    ("pmap_remove_all: page %p is not managed", m));
3063	SLIST_INIT(&free);
3064	rw_wlock(&pvh_global_lock);
3065	sched_pin();
3066	if ((m->flags & PG_FICTITIOUS) != 0)
3067		goto small_mappings;
3068	pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
3069	while ((pv = TAILQ_FIRST(&pvh->pv_list)) != NULL) {
3070		va = pv->pv_va;
3071		pmap = PV_PMAP(pv);
3072		PMAP_LOCK(pmap);
3073		pde = pmap_pde(pmap, va);
3074		(void)pmap_demote_pde(pmap, pde, va);
3075		PMAP_UNLOCK(pmap);
3076	}
3077small_mappings:
3078	while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3079		pmap = PV_PMAP(pv);
3080		PMAP_LOCK(pmap);
3081		pmap->pm_stats.resident_count--;
3082		pde = pmap_pde(pmap, pv->pv_va);
3083		KASSERT((*pde & PG_PS) == 0, ("pmap_remove_all: found"
3084		    " a 4mpage in page %p's pv list", m));
3085		pte = pmap_pte_quick(pmap, pv->pv_va);
3086		tpte = pte_load_clear(pte);
3087		KASSERT(tpte != 0, ("pmap_remove_all: pmap %p va %x zero pte",
3088		    pmap, pv->pv_va));
3089		if (tpte & PG_W)
3090			pmap->pm_stats.wired_count--;
3091		if (tpte & PG_A)
3092			vm_page_aflag_set(m, PGA_REFERENCED);
3093
3094		/*
3095		 * Update the vm_page_t clean and reference bits.
3096		 */
3097		if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW))
3098			vm_page_dirty(m);
3099		pmap_unuse_pt(pmap, pv->pv_va, &free);
3100		pmap_invalidate_page(pmap, pv->pv_va);
3101		TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
3102		free_pv_entry(pmap, pv);
3103		PMAP_UNLOCK(pmap);
3104	}
3105	vm_page_aflag_clear(m, PGA_WRITEABLE);
3106	sched_unpin();
3107	rw_wunlock(&pvh_global_lock);
3108	pmap_free_zero_pages(&free);
3109}
3110
3111/*
3112 * pmap_protect_pde: do the things to protect a 4mpage in a process
3113 */
3114static boolean_t
3115pmap_protect_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t sva, vm_prot_t prot)
3116{
3117	pd_entry_t newpde, oldpde;
3118	vm_offset_t eva, va;
3119	vm_page_t m;
3120	boolean_t anychanged;
3121
3122	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3123	KASSERT((sva & PDRMASK) == 0,
3124	    ("pmap_protect_pde: sva is not 4mpage aligned"));
3125	anychanged = FALSE;
3126retry:
3127	oldpde = newpde = *pde;
3128	if (oldpde & PG_MANAGED) {
3129		eva = sva + NBPDR;
3130		for (va = sva, m = PHYS_TO_VM_PAGE(oldpde & PG_PS_FRAME);
3131		    va < eva; va += PAGE_SIZE, m++)
3132			if ((oldpde & (PG_M | PG_RW)) == (PG_M | PG_RW))
3133				vm_page_dirty(m);
3134	}
3135	if ((prot & VM_PROT_WRITE) == 0)
3136		newpde &= ~(PG_RW | PG_M);
3137#ifdef PAE
3138	if ((prot & VM_PROT_EXECUTE) == 0)
3139		newpde |= pg_nx;
3140#endif
3141	if (newpde != oldpde) {
3142		if (!pde_cmpset(pde, oldpde, newpde))
3143			goto retry;
3144		if (oldpde & PG_G)
3145			pmap_invalidate_page(pmap, sva);
3146		else
3147			anychanged = TRUE;
3148	}
3149	return (anychanged);
3150}
3151
3152/*
3153 *	Set the physical protection on the
3154 *	specified range of this map as requested.
3155 */
3156void
3157pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
3158{
3159	vm_offset_t pdnxt;
3160	pd_entry_t ptpaddr;
3161	pt_entry_t *pte;
3162	boolean_t anychanged, pv_lists_locked;
3163
3164	if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
3165		pmap_remove(pmap, sva, eva);
3166		return;
3167	}
3168
3169#ifdef PAE
3170	if ((prot & (VM_PROT_WRITE|VM_PROT_EXECUTE)) ==
3171	    (VM_PROT_WRITE|VM_PROT_EXECUTE))
3172		return;
3173#else
3174	if (prot & VM_PROT_WRITE)
3175		return;
3176#endif
3177
3178	if (pmap_is_current(pmap))
3179		pv_lists_locked = FALSE;
3180	else {
3181		pv_lists_locked = TRUE;
3182resume:
3183		rw_wlock(&pvh_global_lock);
3184		sched_pin();
3185	}
3186	anychanged = FALSE;
3187
3188	PMAP_LOCK(pmap);
3189	for (; sva < eva; sva = pdnxt) {
3190		pt_entry_t obits, pbits;
3191		u_int pdirindex;
3192
3193		pdnxt = (sva + NBPDR) & ~PDRMASK;
3194		if (pdnxt < sva)
3195			pdnxt = eva;
3196
3197		pdirindex = sva >> PDRSHIFT;
3198		ptpaddr = pmap->pm_pdir[pdirindex];
3199
3200		/*
3201		 * Weed out invalid mappings. Note: we assume that the page
3202		 * directory table is always allocated, and in kernel virtual.
3203		 */
3204		if (ptpaddr == 0)
3205			continue;
3206
3207		/*
3208		 * Check for large page.
3209		 */
3210		if ((ptpaddr & PG_PS) != 0) {
3211			/*
3212			 * Are we protecting the entire large page?  If not,
3213			 * demote the mapping and fall through.
3214			 */
3215			if (sva + NBPDR == pdnxt && eva >= pdnxt) {
3216				/*
3217				 * The TLB entry for a PG_G mapping is
3218				 * invalidated by pmap_protect_pde().
3219				 */
3220				if (pmap_protect_pde(pmap,
3221				    &pmap->pm_pdir[pdirindex], sva, prot))
3222					anychanged = TRUE;
3223				continue;
3224			} else {
3225				if (!pv_lists_locked) {
3226					pv_lists_locked = TRUE;
3227					if (!rw_try_wlock(&pvh_global_lock)) {
3228						if (anychanged)
3229							pmap_invalidate_all(
3230							    pmap);
3231						PMAP_UNLOCK(pmap);
3232						goto resume;
3233					}
3234					sched_pin();
3235				}
3236				if (!pmap_demote_pde(pmap,
3237				    &pmap->pm_pdir[pdirindex], sva)) {
3238					/*
3239					 * The large page mapping was
3240					 * destroyed.
3241					 */
3242					continue;
3243				}
3244			}
3245		}
3246
3247		if (pdnxt > eva)
3248			pdnxt = eva;
3249
3250		for (pte = pmap_pte_quick(pmap, sva); sva != pdnxt; pte++,
3251		    sva += PAGE_SIZE) {
3252			vm_page_t m;
3253
3254retry:
3255			/*
3256			 * Regardless of whether a pte is 32 or 64 bits in
3257			 * size, PG_RW, PG_A, and PG_M are among the least
3258			 * significant 32 bits.
3259			 */
3260			obits = pbits = *pte;
3261			if ((pbits & PG_V) == 0)
3262				continue;
3263
3264			if ((prot & VM_PROT_WRITE) == 0) {
3265				if ((pbits & (PG_MANAGED | PG_M | PG_RW)) ==
3266				    (PG_MANAGED | PG_M | PG_RW)) {
3267					m = PHYS_TO_VM_PAGE(pbits & PG_FRAME);
3268					vm_page_dirty(m);
3269				}
3270				pbits &= ~(PG_RW | PG_M);
3271			}
3272#ifdef PAE
3273			if ((prot & VM_PROT_EXECUTE) == 0)
3274				pbits |= pg_nx;
3275#endif
3276
3277			if (pbits != obits) {
3278#ifdef PAE
3279				if (!atomic_cmpset_64(pte, obits, pbits))
3280					goto retry;
3281#else
3282				if (!atomic_cmpset_int((u_int *)pte, obits,
3283				    pbits))
3284					goto retry;
3285#endif
3286				if (obits & PG_G)
3287					pmap_invalidate_page(pmap, sva);
3288				else
3289					anychanged = TRUE;
3290			}
3291		}
3292	}
3293	if (anychanged)
3294		pmap_invalidate_all(pmap);
3295	if (pv_lists_locked) {
3296		sched_unpin();
3297		rw_wunlock(&pvh_global_lock);
3298	}
3299	PMAP_UNLOCK(pmap);
3300}
3301
3302/*
3303 * Tries to promote the 512 or 1024, contiguous 4KB page mappings that are
3304 * within a single page table page (PTP) to a single 2- or 4MB page mapping.
3305 * For promotion to occur, two conditions must be met: (1) the 4KB page
3306 * mappings must map aligned, contiguous physical memory and (2) the 4KB page
3307 * mappings must have identical characteristics.
3308 *
3309 * Managed (PG_MANAGED) mappings within the kernel address space are not
3310 * promoted.  The reason is that kernel PDEs are replicated in each pmap but
3311 * pmap_clear_ptes() and pmap_ts_referenced() only read the PDE from the kernel
3312 * pmap.
3313 */
3314static void
3315pmap_promote_pde(pmap_t pmap, pd_entry_t *pde, vm_offset_t va)
3316{
3317	pd_entry_t newpde;
3318	pt_entry_t *firstpte, oldpte, pa, *pte;
3319	vm_offset_t oldpteva;
3320	vm_page_t mpte;
3321
3322	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3323
3324	/*
3325	 * Examine the first PTE in the specified PTP.  Abort if this PTE is
3326	 * either invalid, unused, or does not map the first 4KB physical page
3327	 * within a 2- or 4MB page.
3328	 */
3329	firstpte = pmap_pte_quick(pmap, trunc_4mpage(va));
3330setpde:
3331	newpde = *firstpte;
3332	if ((newpde & ((PG_FRAME & PDRMASK) | PG_A | PG_V)) != (PG_A | PG_V)) {
3333		pmap_pde_p_failures++;
3334		CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#x"
3335		    " in pmap %p", va, pmap);
3336		return;
3337	}
3338	if ((*firstpte & PG_MANAGED) != 0 && pmap == kernel_pmap) {
3339		pmap_pde_p_failures++;
3340		CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#x"
3341		    " in pmap %p", va, pmap);
3342		return;
3343	}
3344	if ((newpde & (PG_M | PG_RW)) == PG_RW) {
3345		/*
3346		 * When PG_M is already clear, PG_RW can be cleared without
3347		 * a TLB invalidation.
3348		 */
3349		if (!atomic_cmpset_int((u_int *)firstpte, newpde, newpde &
3350		    ~PG_RW))
3351			goto setpde;
3352		newpde &= ~PG_RW;
3353	}
3354
3355	/*
3356	 * Examine each of the other PTEs in the specified PTP.  Abort if this
3357	 * PTE maps an unexpected 4KB physical page or does not have identical
3358	 * characteristics to the first PTE.
3359	 */
3360	pa = (newpde & (PG_PS_FRAME | PG_A | PG_V)) + NBPDR - PAGE_SIZE;
3361	for (pte = firstpte + NPTEPG - 1; pte > firstpte; pte--) {
3362setpte:
3363		oldpte = *pte;
3364		if ((oldpte & (PG_FRAME | PG_A | PG_V)) != pa) {
3365			pmap_pde_p_failures++;
3366			CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#x"
3367			    " in pmap %p", va, pmap);
3368			return;
3369		}
3370		if ((oldpte & (PG_M | PG_RW)) == PG_RW) {
3371			/*
3372			 * When PG_M is already clear, PG_RW can be cleared
3373			 * without a TLB invalidation.
3374			 */
3375			if (!atomic_cmpset_int((u_int *)pte, oldpte,
3376			    oldpte & ~PG_RW))
3377				goto setpte;
3378			oldpte &= ~PG_RW;
3379			oldpteva = (oldpte & PG_FRAME & PDRMASK) |
3380			    (va & ~PDRMASK);
3381			CTR2(KTR_PMAP, "pmap_promote_pde: protect for va %#x"
3382			    " in pmap %p", oldpteva, pmap);
3383		}
3384		if ((oldpte & PG_PTE_PROMOTE) != (newpde & PG_PTE_PROMOTE)) {
3385			pmap_pde_p_failures++;
3386			CTR2(KTR_PMAP, "pmap_promote_pde: failure for va %#x"
3387			    " in pmap %p", va, pmap);
3388			return;
3389		}
3390		pa -= PAGE_SIZE;
3391	}
3392
3393	/*
3394	 * Save the page table page in its current state until the PDE
3395	 * mapping the superpage is demoted by pmap_demote_pde() or
3396	 * destroyed by pmap_remove_pde().
3397	 */
3398	mpte = PHYS_TO_VM_PAGE(*pde & PG_FRAME);
3399	KASSERT(mpte >= vm_page_array &&
3400	    mpte < &vm_page_array[vm_page_array_size],
3401	    ("pmap_promote_pde: page table page is out of range"));
3402	KASSERT(mpte->pindex == va >> PDRSHIFT,
3403	    ("pmap_promote_pde: page table page's pindex is wrong"));
3404	if (pmap_insert_pt_page(pmap, mpte)) {
3405		pmap_pde_p_failures++;
3406		CTR2(KTR_PMAP,
3407		    "pmap_promote_pde: failure for va %#x in pmap %p", va,
3408		    pmap);
3409		return;
3410	}
3411
3412	/*
3413	 * Promote the pv entries.
3414	 */
3415	if ((newpde & PG_MANAGED) != 0)
3416		pmap_pv_promote_pde(pmap, va, newpde & PG_PS_FRAME);
3417
3418	/*
3419	 * Propagate the PAT index to its proper position.
3420	 */
3421	if ((newpde & PG_PTE_PAT) != 0)
3422		newpde ^= PG_PDE_PAT | PG_PTE_PAT;
3423
3424	/*
3425	 * Map the superpage.
3426	 */
3427	if (workaround_erratum383)
3428		pmap_update_pde(pmap, va, pde, PG_PS | newpde);
3429	else if (pmap == kernel_pmap)
3430		pmap_kenter_pde(va, PG_PS | newpde);
3431	else
3432		pde_store(pde, PG_PS | newpde);
3433
3434	pmap_pde_promotions++;
3435	CTR2(KTR_PMAP, "pmap_promote_pde: success for va %#x"
3436	    " in pmap %p", va, pmap);
3437}
3438
3439/*
3440 *	Insert the given physical page (p) at
3441 *	the specified virtual address (v) in the
3442 *	target physical map with the protection requested.
3443 *
3444 *	If specified, the page will be wired down, meaning
3445 *	that the related pte can not be reclaimed.
3446 *
3447 *	NB:  This is the only routine which MAY NOT lazy-evaluate
3448 *	or lose information.  That is, this routine must actually
3449 *	insert this page into the given map NOW.
3450 */
3451int
3452pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
3453    u_int flags, int8_t psind)
3454{
3455	pd_entry_t *pde;
3456	pt_entry_t *pte;
3457	pt_entry_t newpte, origpte;
3458	pv_entry_t pv;
3459	vm_paddr_t opa, pa;
3460	vm_page_t mpte, om;
3461	boolean_t invlva, wired;
3462
3463	va = trunc_page(va);
3464	mpte = NULL;
3465	wired = (flags & PMAP_ENTER_WIRED) != 0;
3466
3467	KASSERT(va <= VM_MAX_KERNEL_ADDRESS, ("pmap_enter: toobig"));
3468	KASSERT(va < UPT_MIN_ADDRESS || va >= UPT_MAX_ADDRESS,
3469	    ("pmap_enter: invalid to pmap_enter page table pages (va: 0x%x)",
3470	    va));
3471	if ((m->oflags & VPO_UNMANAGED) == 0 && !vm_page_xbusied(m))
3472		VM_OBJECT_ASSERT_LOCKED(m->object);
3473
3474	rw_wlock(&pvh_global_lock);
3475	PMAP_LOCK(pmap);
3476	sched_pin();
3477
3478	/*
3479	 * In the case that a page table page is not
3480	 * resident, we are creating it here.
3481	 */
3482	if (va < VM_MAXUSER_ADDRESS) {
3483		mpte = pmap_allocpte(pmap, va, flags);
3484		if (mpte == NULL) {
3485			KASSERT((flags & PMAP_ENTER_NOSLEEP) != 0,
3486			    ("pmap_allocpte failed with sleep allowed"));
3487			sched_unpin();
3488			rw_wunlock(&pvh_global_lock);
3489			PMAP_UNLOCK(pmap);
3490			return (KERN_RESOURCE_SHORTAGE);
3491		}
3492	}
3493
3494	pde = pmap_pde(pmap, va);
3495	if ((*pde & PG_PS) != 0)
3496		panic("pmap_enter: attempted pmap_enter on 4MB page");
3497	pte = pmap_pte_quick(pmap, va);
3498
3499	/*
3500	 * Page Directory table entry not valid, we need a new PT page
3501	 */
3502	if (pte == NULL) {
3503		panic("pmap_enter: invalid page directory pdir=%#jx, va=%#x",
3504			(uintmax_t)pmap->pm_pdir[PTDPTDI], va);
3505	}
3506
3507	pa = VM_PAGE_TO_PHYS(m);
3508	om = NULL;
3509	origpte = *pte;
3510	opa = origpte & PG_FRAME;
3511
3512	/*
3513	 * Mapping has not changed, must be protection or wiring change.
3514	 */
3515	if (origpte && (opa == pa)) {
3516		/*
3517		 * Wiring change, just update stats. We don't worry about
3518		 * wiring PT pages as they remain resident as long as there
3519		 * are valid mappings in them. Hence, if a user page is wired,
3520		 * the PT page will be also.
3521		 */
3522		if (wired && ((origpte & PG_W) == 0))
3523			pmap->pm_stats.wired_count++;
3524		else if (!wired && (origpte & PG_W))
3525			pmap->pm_stats.wired_count--;
3526
3527		/*
3528		 * Remove extra pte reference
3529		 */
3530		if (mpte)
3531			mpte->wire_count--;
3532
3533		if (origpte & PG_MANAGED) {
3534			om = m;
3535			pa |= PG_MANAGED;
3536		}
3537		goto validate;
3538	}
3539
3540	pv = NULL;
3541
3542	/*
3543	 * Mapping has changed, invalidate old range and fall through to
3544	 * handle validating new mapping.
3545	 */
3546	if (opa) {
3547		if (origpte & PG_W)
3548			pmap->pm_stats.wired_count--;
3549		if (origpte & PG_MANAGED) {
3550			om = PHYS_TO_VM_PAGE(opa);
3551			pv = pmap_pvh_remove(&om->md, pmap, va);
3552		}
3553		if (mpte != NULL) {
3554			mpte->wire_count--;
3555			KASSERT(mpte->wire_count > 0,
3556			    ("pmap_enter: missing reference to page table page,"
3557			     " va: 0x%x", va));
3558		}
3559	} else
3560		pmap->pm_stats.resident_count++;
3561
3562	/*
3563	 * Enter on the PV list if part of our managed memory.
3564	 */
3565	if ((m->oflags & VPO_UNMANAGED) == 0) {
3566		KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva,
3567		    ("pmap_enter: managed mapping within the clean submap"));
3568		if (pv == NULL)
3569			pv = get_pv_entry(pmap, FALSE);
3570		pv->pv_va = va;
3571		TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
3572		pa |= PG_MANAGED;
3573	} else if (pv != NULL)
3574		free_pv_entry(pmap, pv);
3575
3576	/*
3577	 * Increment counters
3578	 */
3579	if (wired)
3580		pmap->pm_stats.wired_count++;
3581
3582validate:
3583	/*
3584	 * Now validate mapping with desired protection/wiring.
3585	 */
3586	newpte = (pt_entry_t)(pa | pmap_cache_bits(m->md.pat_mode, 0) | PG_V);
3587	if ((prot & VM_PROT_WRITE) != 0) {
3588		newpte |= PG_RW;
3589		if ((newpte & PG_MANAGED) != 0)
3590			vm_page_aflag_set(m, PGA_WRITEABLE);
3591	}
3592#ifdef PAE
3593	if ((prot & VM_PROT_EXECUTE) == 0)
3594		newpte |= pg_nx;
3595#endif
3596	if (wired)
3597		newpte |= PG_W;
3598	if (va < VM_MAXUSER_ADDRESS)
3599		newpte |= PG_U;
3600	if (pmap == kernel_pmap)
3601		newpte |= pgeflag;
3602
3603	/*
3604	 * if the mapping or permission bits are different, we need
3605	 * to update the pte.
3606	 */
3607	if ((origpte & ~(PG_M|PG_A)) != newpte) {
3608		newpte |= PG_A;
3609		if ((flags & VM_PROT_WRITE) != 0)
3610			newpte |= PG_M;
3611		if (origpte & PG_V) {
3612			invlva = FALSE;
3613			origpte = pte_load_store(pte, newpte);
3614			if (origpte & PG_A) {
3615				if (origpte & PG_MANAGED)
3616					vm_page_aflag_set(om, PGA_REFERENCED);
3617				if (opa != VM_PAGE_TO_PHYS(m))
3618					invlva = TRUE;
3619#ifdef PAE
3620				if ((origpte & PG_NX) == 0 &&
3621				    (newpte & PG_NX) != 0)
3622					invlva = TRUE;
3623#endif
3624			}
3625			if ((origpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
3626				if ((origpte & PG_MANAGED) != 0)
3627					vm_page_dirty(om);
3628				if ((prot & VM_PROT_WRITE) == 0)
3629					invlva = TRUE;
3630			}
3631			if ((origpte & PG_MANAGED) != 0 &&
3632			    TAILQ_EMPTY(&om->md.pv_list) &&
3633			    ((om->flags & PG_FICTITIOUS) != 0 ||
3634			    TAILQ_EMPTY(&pa_to_pvh(opa)->pv_list)))
3635				vm_page_aflag_clear(om, PGA_WRITEABLE);
3636			if (invlva)
3637				pmap_invalidate_page(pmap, va);
3638		} else
3639			pte_store(pte, newpte);
3640	}
3641
3642	/*
3643	 * If both the page table page and the reservation are fully
3644	 * populated, then attempt promotion.
3645	 */
3646	if ((mpte == NULL || mpte->wire_count == NPTEPG) &&
3647	    pg_ps_enabled && (m->flags & PG_FICTITIOUS) == 0 &&
3648	    vm_reserv_level_iffullpop(m) == 0)
3649		pmap_promote_pde(pmap, pde, va);
3650
3651	sched_unpin();
3652	rw_wunlock(&pvh_global_lock);
3653	PMAP_UNLOCK(pmap);
3654	return (KERN_SUCCESS);
3655}
3656
3657/*
3658 * Tries to create a 2- or 4MB page mapping.  Returns TRUE if successful and
3659 * FALSE otherwise.  Fails if (1) a page table page cannot be allocated without
3660 * blocking, (2) a mapping already exists at the specified virtual address, or
3661 * (3) a pv entry cannot be allocated without reclaiming another pv entry.
3662 */
3663static boolean_t
3664pmap_enter_pde(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
3665{
3666	pd_entry_t *pde, newpde;
3667
3668	rw_assert(&pvh_global_lock, RA_WLOCKED);
3669	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3670	pde = pmap_pde(pmap, va);
3671	if (*pde != 0) {
3672		CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
3673		    " in pmap %p", va, pmap);
3674		return (FALSE);
3675	}
3676	newpde = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(m->md.pat_mode, 1) |
3677	    PG_PS | PG_V;
3678	if ((m->oflags & VPO_UNMANAGED) == 0) {
3679		newpde |= PG_MANAGED;
3680
3681		/*
3682		 * Abort this mapping if its PV entry could not be created.
3683		 */
3684		if (!pmap_pv_insert_pde(pmap, va, VM_PAGE_TO_PHYS(m))) {
3685			CTR2(KTR_PMAP, "pmap_enter_pde: failure for va %#lx"
3686			    " in pmap %p", va, pmap);
3687			return (FALSE);
3688		}
3689	}
3690#ifdef PAE
3691	if ((prot & VM_PROT_EXECUTE) == 0)
3692		newpde |= pg_nx;
3693#endif
3694	if (va < VM_MAXUSER_ADDRESS)
3695		newpde |= PG_U;
3696
3697	/*
3698	 * Increment counters.
3699	 */
3700	pmap->pm_stats.resident_count += NBPDR / PAGE_SIZE;
3701
3702	/*
3703	 * Map the superpage.
3704	 */
3705	pde_store(pde, newpde);
3706
3707	pmap_pde_mappings++;
3708	CTR2(KTR_PMAP, "pmap_enter_pde: success for va %#lx"
3709	    " in pmap %p", va, pmap);
3710	return (TRUE);
3711}
3712
3713/*
3714 * Maps a sequence of resident pages belonging to the same object.
3715 * The sequence begins with the given page m_start.  This page is
3716 * mapped at the given virtual address start.  Each subsequent page is
3717 * mapped at a virtual address that is offset from start by the same
3718 * amount as the page is offset from m_start within the object.  The
3719 * last page in the sequence is the page with the largest offset from
3720 * m_start that can be mapped at a virtual address less than the given
3721 * virtual address end.  Not every virtual page between start and end
3722 * is mapped; only those for which a resident page exists with the
3723 * corresponding offset from m_start are mapped.
3724 */
3725void
3726pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
3727    vm_page_t m_start, vm_prot_t prot)
3728{
3729	vm_offset_t va;
3730	vm_page_t m, mpte;
3731	vm_pindex_t diff, psize;
3732
3733	VM_OBJECT_ASSERT_LOCKED(m_start->object);
3734
3735	psize = atop(end - start);
3736	mpte = NULL;
3737	m = m_start;
3738	rw_wlock(&pvh_global_lock);
3739	PMAP_LOCK(pmap);
3740	while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
3741		va = start + ptoa(diff);
3742		if ((va & PDRMASK) == 0 && va + NBPDR <= end &&
3743		    m->psind == 1 && pg_ps_enabled &&
3744		    pmap_enter_pde(pmap, va, m, prot))
3745			m = &m[NBPDR / PAGE_SIZE - 1];
3746		else
3747			mpte = pmap_enter_quick_locked(pmap, va, m, prot,
3748			    mpte);
3749		m = TAILQ_NEXT(m, listq);
3750	}
3751	rw_wunlock(&pvh_global_lock);
3752	PMAP_UNLOCK(pmap);
3753}
3754
3755/*
3756 * this code makes some *MAJOR* assumptions:
3757 * 1. Current pmap & pmap exists.
3758 * 2. Not wired.
3759 * 3. Read access.
3760 * 4. No page table pages.
3761 * but is *MUCH* faster than pmap_enter...
3762 */
3763
3764void
3765pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot)
3766{
3767
3768	rw_wlock(&pvh_global_lock);
3769	PMAP_LOCK(pmap);
3770	(void)pmap_enter_quick_locked(pmap, va, m, prot, NULL);
3771	rw_wunlock(&pvh_global_lock);
3772	PMAP_UNLOCK(pmap);
3773}
3774
3775static vm_page_t
3776pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
3777    vm_prot_t prot, vm_page_t mpte)
3778{
3779	pt_entry_t *pte;
3780	vm_paddr_t pa;
3781	struct spglist free;
3782
3783	KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
3784	    (m->oflags & VPO_UNMANAGED) != 0,
3785	    ("pmap_enter_quick_locked: managed mapping within the clean submap"));
3786	rw_assert(&pvh_global_lock, RA_WLOCKED);
3787	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
3788
3789	/*
3790	 * In the case that a page table page is not
3791	 * resident, we are creating it here.
3792	 */
3793	if (va < VM_MAXUSER_ADDRESS) {
3794		u_int ptepindex;
3795		pd_entry_t ptepa;
3796
3797		/*
3798		 * Calculate pagetable page index
3799		 */
3800		ptepindex = va >> PDRSHIFT;
3801		if (mpte && (mpte->pindex == ptepindex)) {
3802			mpte->wire_count++;
3803		} else {
3804			/*
3805			 * Get the page directory entry
3806			 */
3807			ptepa = pmap->pm_pdir[ptepindex];
3808
3809			/*
3810			 * If the page table page is mapped, we just increment
3811			 * the hold count, and activate it.
3812			 */
3813			if (ptepa) {
3814				if (ptepa & PG_PS)
3815					return (NULL);
3816				mpte = PHYS_TO_VM_PAGE(ptepa & PG_FRAME);
3817				mpte->wire_count++;
3818			} else {
3819				mpte = _pmap_allocpte(pmap, ptepindex,
3820				    PMAP_ENTER_NOSLEEP);
3821				if (mpte == NULL)
3822					return (mpte);
3823			}
3824		}
3825	} else {
3826		mpte = NULL;
3827	}
3828
3829	/*
3830	 * This call to vtopte makes the assumption that we are
3831	 * entering the page into the current pmap.  In order to support
3832	 * quick entry into any pmap, one would likely use pmap_pte_quick.
3833	 * But that isn't as quick as vtopte.
3834	 */
3835	pte = vtopte(va);
3836	if (*pte) {
3837		if (mpte != NULL) {
3838			mpte->wire_count--;
3839			mpte = NULL;
3840		}
3841		return (mpte);
3842	}
3843
3844	/*
3845	 * Enter on the PV list if part of our managed memory.
3846	 */
3847	if ((m->oflags & VPO_UNMANAGED) == 0 &&
3848	    !pmap_try_insert_pv_entry(pmap, va, m)) {
3849		if (mpte != NULL) {
3850			SLIST_INIT(&free);
3851			if (pmap_unwire_ptp(pmap, mpte, &free)) {
3852				pmap_invalidate_page(pmap, va);
3853				pmap_free_zero_pages(&free);
3854			}
3855
3856			mpte = NULL;
3857		}
3858		return (mpte);
3859	}
3860
3861	/*
3862	 * Increment counters
3863	 */
3864	pmap->pm_stats.resident_count++;
3865
3866	pa = VM_PAGE_TO_PHYS(m) | pmap_cache_bits(m->md.pat_mode, 0);
3867#ifdef PAE
3868	if ((prot & VM_PROT_EXECUTE) == 0)
3869		pa |= pg_nx;
3870#endif
3871
3872	/*
3873	 * Now validate mapping with RO protection
3874	 */
3875	if ((m->oflags & VPO_UNMANAGED) != 0)
3876		pte_store(pte, pa | PG_V | PG_U);
3877	else
3878		pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
3879	return (mpte);
3880}
3881
3882/*
3883 * Make a temporary mapping for a physical address.  This is only intended
3884 * to be used for panic dumps.
3885 */
3886void *
3887pmap_kenter_temporary(vm_paddr_t pa, int i)
3888{
3889	vm_offset_t va;
3890
3891	va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
3892	pmap_kenter(va, pa);
3893	invlpg(va);
3894	return ((void *)crashdumpmap);
3895}
3896
3897/*
3898 * This code maps large physical mmap regions into the
3899 * processor address space.  Note that some shortcuts
3900 * are taken, but the code works.
3901 */
3902void
3903pmap_object_init_pt(pmap_t pmap, vm_offset_t addr, vm_object_t object,
3904    vm_pindex_t pindex, vm_size_t size)
3905{
3906	pd_entry_t *pde;
3907	vm_paddr_t pa, ptepa;
3908	vm_page_t p;
3909	int pat_mode;
3910
3911	VM_OBJECT_ASSERT_WLOCKED(object);
3912	KASSERT(object->type == OBJT_DEVICE || object->type == OBJT_SG,
3913	    ("pmap_object_init_pt: non-device object"));
3914	if (pseflag &&
3915	    (addr & (NBPDR - 1)) == 0 && (size & (NBPDR - 1)) == 0) {
3916		if (!vm_object_populate(object, pindex, pindex + atop(size)))
3917			return;
3918		p = vm_page_lookup(object, pindex);
3919		KASSERT(p->valid == VM_PAGE_BITS_ALL,
3920		    ("pmap_object_init_pt: invalid page %p", p));
3921		pat_mode = p->md.pat_mode;
3922
3923		/*
3924		 * Abort the mapping if the first page is not physically
3925		 * aligned to a 2/4MB page boundary.
3926		 */
3927		ptepa = VM_PAGE_TO_PHYS(p);
3928		if (ptepa & (NBPDR - 1))
3929			return;
3930
3931		/*
3932		 * Skip the first page.  Abort the mapping if the rest of
3933		 * the pages are not physically contiguous or have differing
3934		 * memory attributes.
3935		 */
3936		p = TAILQ_NEXT(p, listq);
3937		for (pa = ptepa + PAGE_SIZE; pa < ptepa + size;
3938		    pa += PAGE_SIZE) {
3939			KASSERT(p->valid == VM_PAGE_BITS_ALL,
3940			    ("pmap_object_init_pt: invalid page %p", p));
3941			if (pa != VM_PAGE_TO_PHYS(p) ||
3942			    pat_mode != p->md.pat_mode)
3943				return;
3944			p = TAILQ_NEXT(p, listq);
3945		}
3946
3947		/*
3948		 * Map using 2/4MB pages.  Since "ptepa" is 2/4M aligned and
3949		 * "size" is a multiple of 2/4M, adding the PAT setting to
3950		 * "pa" will not affect the termination of this loop.
3951		 */
3952		PMAP_LOCK(pmap);
3953		for (pa = ptepa | pmap_cache_bits(pat_mode, 1); pa < ptepa +
3954		    size; pa += NBPDR) {
3955			pde = pmap_pde(pmap, addr);
3956			if (*pde == 0) {
3957				pde_store(pde, pa | PG_PS | PG_M | PG_A |
3958				    PG_U | PG_RW | PG_V);
3959				pmap->pm_stats.resident_count += NBPDR /
3960				    PAGE_SIZE;
3961				pmap_pde_mappings++;
3962			}
3963			/* Else continue on if the PDE is already valid. */
3964			addr += NBPDR;
3965		}
3966		PMAP_UNLOCK(pmap);
3967	}
3968}
3969
3970/*
3971 *	Clear the wired attribute from the mappings for the specified range of
3972 *	addresses in the given pmap.  Every valid mapping within that range
3973 *	must have the wired attribute set.  In contrast, invalid mappings
3974 *	cannot have the wired attribute set, so they are ignored.
3975 *
3976 *	The wired attribute of the page table entry is not a hardware feature,
3977 *	so there is no need to invalidate any TLB entries.
3978 */
3979void
3980pmap_unwire(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
3981{
3982	vm_offset_t pdnxt;
3983	pd_entry_t *pde;
3984	pt_entry_t *pte;
3985	boolean_t pv_lists_locked;
3986
3987	if (pmap_is_current(pmap))
3988		pv_lists_locked = FALSE;
3989	else {
3990		pv_lists_locked = TRUE;
3991resume:
3992		rw_wlock(&pvh_global_lock);
3993		sched_pin();
3994	}
3995	PMAP_LOCK(pmap);
3996	for (; sva < eva; sva = pdnxt) {
3997		pdnxt = (sva + NBPDR) & ~PDRMASK;
3998		if (pdnxt < sva)
3999			pdnxt = eva;
4000		pde = pmap_pde(pmap, sva);
4001		if ((*pde & PG_V) == 0)
4002			continue;
4003		if ((*pde & PG_PS) != 0) {
4004			if ((*pde & PG_W) == 0)
4005				panic("pmap_unwire: pde %#jx is missing PG_W",
4006				    (uintmax_t)*pde);
4007
4008			/*
4009			 * Are we unwiring the entire large page?  If not,
4010			 * demote the mapping and fall through.
4011			 */
4012			if (sva + NBPDR == pdnxt && eva >= pdnxt) {
4013				/*
4014				 * Regardless of whether a pde (or pte) is 32
4015				 * or 64 bits in size, PG_W is among the least
4016				 * significant 32 bits.
4017				 */
4018				atomic_clear_int((u_int *)pde, PG_W);
4019				pmap->pm_stats.wired_count -= NBPDR /
4020				    PAGE_SIZE;
4021				continue;
4022			} else {
4023				if (!pv_lists_locked) {
4024					pv_lists_locked = TRUE;
4025					if (!rw_try_wlock(&pvh_global_lock)) {
4026						PMAP_UNLOCK(pmap);
4027						/* Repeat sva. */
4028						goto resume;
4029					}
4030					sched_pin();
4031				}
4032				if (!pmap_demote_pde(pmap, pde, sva))
4033					panic("pmap_unwire: demotion failed");
4034			}
4035		}
4036		if (pdnxt > eva)
4037			pdnxt = eva;
4038		for (pte = pmap_pte_quick(pmap, sva); sva != pdnxt; pte++,
4039		    sva += PAGE_SIZE) {
4040			if ((*pte & PG_V) == 0)
4041				continue;
4042			if ((*pte & PG_W) == 0)
4043				panic("pmap_unwire: pte %#jx is missing PG_W",
4044				    (uintmax_t)*pte);
4045
4046			/*
4047			 * PG_W must be cleared atomically.  Although the pmap
4048			 * lock synchronizes access to PG_W, another processor
4049			 * could be setting PG_M and/or PG_A concurrently.
4050			 *
4051			 * PG_W is among the least significant 32 bits.
4052			 */
4053			atomic_clear_int((u_int *)pte, PG_W);
4054			pmap->pm_stats.wired_count--;
4055		}
4056	}
4057	if (pv_lists_locked) {
4058		sched_unpin();
4059		rw_wunlock(&pvh_global_lock);
4060	}
4061	PMAP_UNLOCK(pmap);
4062}
4063
4064
4065/*
4066 *	Copy the range specified by src_addr/len
4067 *	from the source map to the range dst_addr/len
4068 *	in the destination map.
4069 *
4070 *	This routine is only advisory and need not do anything.
4071 */
4072
4073void
4074pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
4075    vm_offset_t src_addr)
4076{
4077	struct spglist free;
4078	vm_offset_t addr;
4079	vm_offset_t end_addr = src_addr + len;
4080	vm_offset_t pdnxt;
4081
4082	if (dst_addr != src_addr)
4083		return;
4084
4085	if (!pmap_is_current(src_pmap))
4086		return;
4087
4088	rw_wlock(&pvh_global_lock);
4089	if (dst_pmap < src_pmap) {
4090		PMAP_LOCK(dst_pmap);
4091		PMAP_LOCK(src_pmap);
4092	} else {
4093		PMAP_LOCK(src_pmap);
4094		PMAP_LOCK(dst_pmap);
4095	}
4096	sched_pin();
4097	for (addr = src_addr; addr < end_addr; addr = pdnxt) {
4098		pt_entry_t *src_pte, *dst_pte;
4099		vm_page_t dstmpte, srcmpte;
4100		pd_entry_t srcptepaddr;
4101		u_int ptepindex;
4102
4103		KASSERT(addr < UPT_MIN_ADDRESS,
4104		    ("pmap_copy: invalid to pmap_copy page tables"));
4105
4106		pdnxt = (addr + NBPDR) & ~PDRMASK;
4107		if (pdnxt < addr)
4108			pdnxt = end_addr;
4109		ptepindex = addr >> PDRSHIFT;
4110
4111		srcptepaddr = src_pmap->pm_pdir[ptepindex];
4112		if (srcptepaddr == 0)
4113			continue;
4114
4115		if (srcptepaddr & PG_PS) {
4116			if ((addr & PDRMASK) != 0 || addr + NBPDR > end_addr)
4117				continue;
4118			if (dst_pmap->pm_pdir[ptepindex] == 0 &&
4119			    ((srcptepaddr & PG_MANAGED) == 0 ||
4120			    pmap_pv_insert_pde(dst_pmap, addr, srcptepaddr &
4121			    PG_PS_FRAME))) {
4122				dst_pmap->pm_pdir[ptepindex] = srcptepaddr &
4123				    ~PG_W;
4124				dst_pmap->pm_stats.resident_count +=
4125				    NBPDR / PAGE_SIZE;
4126			}
4127			continue;
4128		}
4129
4130		srcmpte = PHYS_TO_VM_PAGE(srcptepaddr & PG_FRAME);
4131		KASSERT(srcmpte->wire_count > 0,
4132		    ("pmap_copy: source page table page is unused"));
4133
4134		if (pdnxt > end_addr)
4135			pdnxt = end_addr;
4136
4137		src_pte = vtopte(addr);
4138		while (addr < pdnxt) {
4139			pt_entry_t ptetemp;
4140			ptetemp = *src_pte;
4141			/*
4142			 * we only virtual copy managed pages
4143			 */
4144			if ((ptetemp & PG_MANAGED) != 0) {
4145				dstmpte = pmap_allocpte(dst_pmap, addr,
4146				    PMAP_ENTER_NOSLEEP);
4147				if (dstmpte == NULL)
4148					goto out;
4149				dst_pte = pmap_pte_quick(dst_pmap, addr);
4150				if (*dst_pte == 0 &&
4151				    pmap_try_insert_pv_entry(dst_pmap, addr,
4152				    PHYS_TO_VM_PAGE(ptetemp & PG_FRAME))) {
4153					/*
4154					 * Clear the wired, modified, and
4155					 * accessed (referenced) bits
4156					 * during the copy.
4157					 */
4158					*dst_pte = ptetemp & ~(PG_W | PG_M |
4159					    PG_A);
4160					dst_pmap->pm_stats.resident_count++;
4161	 			} else {
4162					SLIST_INIT(&free);
4163					if (pmap_unwire_ptp(dst_pmap, dstmpte,
4164					    &free)) {
4165						pmap_invalidate_page(dst_pmap,
4166						    addr);
4167						pmap_free_zero_pages(&free);
4168					}
4169					goto out;
4170				}
4171				if (dstmpte->wire_count >= srcmpte->wire_count)
4172					break;
4173			}
4174			addr += PAGE_SIZE;
4175			src_pte++;
4176		}
4177	}
4178out:
4179	sched_unpin();
4180	rw_wunlock(&pvh_global_lock);
4181	PMAP_UNLOCK(src_pmap);
4182	PMAP_UNLOCK(dst_pmap);
4183}
4184
4185static __inline void
4186pagezero(void *page)
4187{
4188#if defined(I686_CPU)
4189	if (cpu_class == CPUCLASS_686) {
4190#if defined(CPU_ENABLE_SSE)
4191		if (cpu_feature & CPUID_SSE2)
4192			sse2_pagezero(page);
4193		else
4194#endif
4195			i686_pagezero(page);
4196	} else
4197#endif
4198		bzero(page, PAGE_SIZE);
4199}
4200
4201/*
4202 *	pmap_zero_page zeros the specified hardware page by mapping
4203 *	the page into KVM and using bzero to clear its contents.
4204 */
4205void
4206pmap_zero_page(vm_page_t m)
4207{
4208	struct sysmaps *sysmaps;
4209
4210	sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
4211	mtx_lock(&sysmaps->lock);
4212	if (*sysmaps->CMAP2)
4213		panic("pmap_zero_page: CMAP2 busy");
4214	sched_pin();
4215	*sysmaps->CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M |
4216	    pmap_cache_bits(m->md.pat_mode, 0);
4217	invlcaddr(sysmaps->CADDR2);
4218	pagezero(sysmaps->CADDR2);
4219	*sysmaps->CMAP2 = 0;
4220	sched_unpin();
4221	mtx_unlock(&sysmaps->lock);
4222}
4223
4224/*
4225 *	pmap_zero_page_area zeros the specified hardware page by mapping
4226 *	the page into KVM and using bzero to clear its contents.
4227 *
4228 *	off and size may not cover an area beyond a single hardware page.
4229 */
4230void
4231pmap_zero_page_area(vm_page_t m, int off, int size)
4232{
4233	struct sysmaps *sysmaps;
4234
4235	sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
4236	mtx_lock(&sysmaps->lock);
4237	if (*sysmaps->CMAP2)
4238		panic("pmap_zero_page_area: CMAP2 busy");
4239	sched_pin();
4240	*sysmaps->CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M |
4241	    pmap_cache_bits(m->md.pat_mode, 0);
4242	invlcaddr(sysmaps->CADDR2);
4243	if (off == 0 && size == PAGE_SIZE)
4244		pagezero(sysmaps->CADDR2);
4245	else
4246		bzero((char *)sysmaps->CADDR2 + off, size);
4247	*sysmaps->CMAP2 = 0;
4248	sched_unpin();
4249	mtx_unlock(&sysmaps->lock);
4250}
4251
4252/*
4253 *	pmap_zero_page_idle zeros the specified hardware page by mapping
4254 *	the page into KVM and using bzero to clear its contents.  This
4255 *	is intended to be called from the vm_pagezero process only and
4256 *	outside of Giant.
4257 */
4258void
4259pmap_zero_page_idle(vm_page_t m)
4260{
4261
4262	if (*CMAP3)
4263		panic("pmap_zero_page_idle: CMAP3 busy");
4264	sched_pin();
4265	*CMAP3 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M |
4266	    pmap_cache_bits(m->md.pat_mode, 0);
4267	invlcaddr(CADDR3);
4268	pagezero(CADDR3);
4269	*CMAP3 = 0;
4270	sched_unpin();
4271}
4272
4273/*
4274 *	pmap_copy_page copies the specified (machine independent)
4275 *	page by mapping the page into virtual memory and using
4276 *	bcopy to copy the page, one machine dependent page at a
4277 *	time.
4278 */
4279void
4280pmap_copy_page(vm_page_t src, vm_page_t dst)
4281{
4282	struct sysmaps *sysmaps;
4283
4284	sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
4285	mtx_lock(&sysmaps->lock);
4286	if (*sysmaps->CMAP1)
4287		panic("pmap_copy_page: CMAP1 busy");
4288	if (*sysmaps->CMAP2)
4289		panic("pmap_copy_page: CMAP2 busy");
4290	sched_pin();
4291	*sysmaps->CMAP1 = PG_V | VM_PAGE_TO_PHYS(src) | PG_A |
4292	    pmap_cache_bits(src->md.pat_mode, 0);
4293	invlcaddr(sysmaps->CADDR1);
4294	*sysmaps->CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(dst) | PG_A | PG_M |
4295	    pmap_cache_bits(dst->md.pat_mode, 0);
4296	invlcaddr(sysmaps->CADDR2);
4297	bcopy(sysmaps->CADDR1, sysmaps->CADDR2, PAGE_SIZE);
4298	*sysmaps->CMAP1 = 0;
4299	*sysmaps->CMAP2 = 0;
4300	sched_unpin();
4301	mtx_unlock(&sysmaps->lock);
4302}
4303
4304int unmapped_buf_allowed = 1;
4305
4306void
4307pmap_copy_pages(vm_page_t ma[], vm_offset_t a_offset, vm_page_t mb[],
4308    vm_offset_t b_offset, int xfersize)
4309{
4310	struct sysmaps *sysmaps;
4311	vm_page_t a_pg, b_pg;
4312	char *a_cp, *b_cp;
4313	vm_offset_t a_pg_offset, b_pg_offset;
4314	int cnt;
4315
4316	sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
4317	mtx_lock(&sysmaps->lock);
4318	if (*sysmaps->CMAP1 != 0)
4319		panic("pmap_copy_pages: CMAP1 busy");
4320	if (*sysmaps->CMAP2 != 0)
4321		panic("pmap_copy_pages: CMAP2 busy");
4322	sched_pin();
4323	while (xfersize > 0) {
4324		a_pg = ma[a_offset >> PAGE_SHIFT];
4325		a_pg_offset = a_offset & PAGE_MASK;
4326		cnt = min(xfersize, PAGE_SIZE - a_pg_offset);
4327		b_pg = mb[b_offset >> PAGE_SHIFT];
4328		b_pg_offset = b_offset & PAGE_MASK;
4329		cnt = min(cnt, PAGE_SIZE - b_pg_offset);
4330		*sysmaps->CMAP1 = PG_V | VM_PAGE_TO_PHYS(a_pg) | PG_A |
4331		    pmap_cache_bits(a_pg->md.pat_mode, 0);
4332		invlcaddr(sysmaps->CADDR1);
4333		*sysmaps->CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(b_pg) | PG_A |
4334		    PG_M | pmap_cache_bits(b_pg->md.pat_mode, 0);
4335		invlcaddr(sysmaps->CADDR2);
4336		a_cp = sysmaps->CADDR1 + a_pg_offset;
4337		b_cp = sysmaps->CADDR2 + b_pg_offset;
4338		bcopy(a_cp, b_cp, cnt);
4339		a_offset += cnt;
4340		b_offset += cnt;
4341		xfersize -= cnt;
4342	}
4343	*sysmaps->CMAP1 = 0;
4344	*sysmaps->CMAP2 = 0;
4345	sched_unpin();
4346	mtx_unlock(&sysmaps->lock);
4347}
4348
4349/*
4350 * Returns true if the pmap's pv is one of the first
4351 * 16 pvs linked to from this page.  This count may
4352 * be changed upwards or downwards in the future; it
4353 * is only necessary that true be returned for a small
4354 * subset of pmaps for proper page aging.
4355 */
4356boolean_t
4357pmap_page_exists_quick(pmap_t pmap, vm_page_t m)
4358{
4359	struct md_page *pvh;
4360	pv_entry_t pv;
4361	int loops = 0;
4362	boolean_t rv;
4363
4364	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4365	    ("pmap_page_exists_quick: page %p is not managed", m));
4366	rv = FALSE;
4367	rw_wlock(&pvh_global_lock);
4368	TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
4369		if (PV_PMAP(pv) == pmap) {
4370			rv = TRUE;
4371			break;
4372		}
4373		loops++;
4374		if (loops >= 16)
4375			break;
4376	}
4377	if (!rv && loops < 16 && (m->flags & PG_FICTITIOUS) == 0) {
4378		pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4379		TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
4380			if (PV_PMAP(pv) == pmap) {
4381				rv = TRUE;
4382				break;
4383			}
4384			loops++;
4385			if (loops >= 16)
4386				break;
4387		}
4388	}
4389	rw_wunlock(&pvh_global_lock);
4390	return (rv);
4391}
4392
4393/*
4394 *	pmap_page_wired_mappings:
4395 *
4396 *	Return the number of managed mappings to the given physical page
4397 *	that are wired.
4398 */
4399int
4400pmap_page_wired_mappings(vm_page_t m)
4401{
4402	int count;
4403
4404	count = 0;
4405	if ((m->oflags & VPO_UNMANAGED) != 0)
4406		return (count);
4407	rw_wlock(&pvh_global_lock);
4408	count = pmap_pvh_wired_mappings(&m->md, count);
4409	if ((m->flags & PG_FICTITIOUS) == 0) {
4410	    count = pmap_pvh_wired_mappings(pa_to_pvh(VM_PAGE_TO_PHYS(m)),
4411	        count);
4412	}
4413	rw_wunlock(&pvh_global_lock);
4414	return (count);
4415}
4416
4417/*
4418 *	pmap_pvh_wired_mappings:
4419 *
4420 *	Return the updated number "count" of managed mappings that are wired.
4421 */
4422static int
4423pmap_pvh_wired_mappings(struct md_page *pvh, int count)
4424{
4425	pmap_t pmap;
4426	pt_entry_t *pte;
4427	pv_entry_t pv;
4428
4429	rw_assert(&pvh_global_lock, RA_WLOCKED);
4430	sched_pin();
4431	TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
4432		pmap = PV_PMAP(pv);
4433		PMAP_LOCK(pmap);
4434		pte = pmap_pte_quick(pmap, pv->pv_va);
4435		if ((*pte & PG_W) != 0)
4436			count++;
4437		PMAP_UNLOCK(pmap);
4438	}
4439	sched_unpin();
4440	return (count);
4441}
4442
4443/*
4444 * Returns TRUE if the given page is mapped individually or as part of
4445 * a 4mpage.  Otherwise, returns FALSE.
4446 */
4447boolean_t
4448pmap_page_is_mapped(vm_page_t m)
4449{
4450	boolean_t rv;
4451
4452	if ((m->oflags & VPO_UNMANAGED) != 0)
4453		return (FALSE);
4454	rw_wlock(&pvh_global_lock);
4455	rv = !TAILQ_EMPTY(&m->md.pv_list) ||
4456	    ((m->flags & PG_FICTITIOUS) == 0 &&
4457	    !TAILQ_EMPTY(&pa_to_pvh(VM_PAGE_TO_PHYS(m))->pv_list));
4458	rw_wunlock(&pvh_global_lock);
4459	return (rv);
4460}
4461
4462/*
4463 * Remove all pages from specified address space
4464 * this aids process exit speeds.  Also, this code
4465 * is special cased for current process only, but
4466 * can have the more generic (and slightly slower)
4467 * mode enabled.  This is much faster than pmap_remove
4468 * in the case of running down an entire address space.
4469 */
4470void
4471pmap_remove_pages(pmap_t pmap)
4472{
4473	pt_entry_t *pte, tpte;
4474	vm_page_t m, mpte, mt;
4475	pv_entry_t pv;
4476	struct md_page *pvh;
4477	struct pv_chunk *pc, *npc;
4478	struct spglist free;
4479	int field, idx;
4480	int32_t bit;
4481	uint32_t inuse, bitmask;
4482	int allfree;
4483
4484	if (pmap != PCPU_GET(curpmap)) {
4485		printf("warning: pmap_remove_pages called with non-current pmap\n");
4486		return;
4487	}
4488	SLIST_INIT(&free);
4489	rw_wlock(&pvh_global_lock);
4490	PMAP_LOCK(pmap);
4491	sched_pin();
4492	TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
4493		KASSERT(pc->pc_pmap == pmap, ("Wrong pmap %p %p", pmap,
4494		    pc->pc_pmap));
4495		allfree = 1;
4496		for (field = 0; field < _NPCM; field++) {
4497			inuse = ~pc->pc_map[field] & pc_freemask[field];
4498			while (inuse != 0) {
4499				bit = bsfl(inuse);
4500				bitmask = 1UL << bit;
4501				idx = field * 32 + bit;
4502				pv = &pc->pc_pventry[idx];
4503				inuse &= ~bitmask;
4504
4505				pte = pmap_pde(pmap, pv->pv_va);
4506				tpte = *pte;
4507				if ((tpte & PG_PS) == 0) {
4508					pte = vtopte(pv->pv_va);
4509					tpte = *pte & ~PG_PTE_PAT;
4510				}
4511
4512				if (tpte == 0) {
4513					printf(
4514					    "TPTE at %p  IS ZERO @ VA %08x\n",
4515					    pte, pv->pv_va);
4516					panic("bad pte");
4517				}
4518
4519/*
4520 * We cannot remove wired pages from a process' mapping at this time
4521 */
4522				if (tpte & PG_W) {
4523					allfree = 0;
4524					continue;
4525				}
4526
4527				m = PHYS_TO_VM_PAGE(tpte & PG_FRAME);
4528				KASSERT(m->phys_addr == (tpte & PG_FRAME),
4529				    ("vm_page_t %p phys_addr mismatch %016jx %016jx",
4530				    m, (uintmax_t)m->phys_addr,
4531				    (uintmax_t)tpte));
4532
4533				KASSERT((m->flags & PG_FICTITIOUS) != 0 ||
4534				    m < &vm_page_array[vm_page_array_size],
4535				    ("pmap_remove_pages: bad tpte %#jx",
4536				    (uintmax_t)tpte));
4537
4538				pte_clear(pte);
4539
4540				/*
4541				 * Update the vm_page_t clean/reference bits.
4542				 */
4543				if ((tpte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
4544					if ((tpte & PG_PS) != 0) {
4545						for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
4546							vm_page_dirty(mt);
4547					} else
4548						vm_page_dirty(m);
4549				}
4550
4551				/* Mark free */
4552				PV_STAT(pv_entry_frees++);
4553				PV_STAT(pv_entry_spare++);
4554				pv_entry_count--;
4555				pc->pc_map[field] |= bitmask;
4556				if ((tpte & PG_PS) != 0) {
4557					pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
4558					pvh = pa_to_pvh(tpte & PG_PS_FRAME);
4559					TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
4560					if (TAILQ_EMPTY(&pvh->pv_list)) {
4561						for (mt = m; mt < &m[NBPDR / PAGE_SIZE]; mt++)
4562							if (TAILQ_EMPTY(&mt->md.pv_list))
4563								vm_page_aflag_clear(mt, PGA_WRITEABLE);
4564					}
4565					mpte = pmap_lookup_pt_page(pmap, pv->pv_va);
4566					if (mpte != NULL) {
4567						pmap_remove_pt_page(pmap, mpte);
4568						pmap->pm_stats.resident_count--;
4569						KASSERT(mpte->wire_count == NPTEPG,
4570						    ("pmap_remove_pages: pte page wire count error"));
4571						mpte->wire_count = 0;
4572						pmap_add_delayed_free_list(mpte, &free, FALSE);
4573						atomic_subtract_int(&cnt.v_wire_count, 1);
4574					}
4575				} else {
4576					pmap->pm_stats.resident_count--;
4577					TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4578					if (TAILQ_EMPTY(&m->md.pv_list) &&
4579					    (m->flags & PG_FICTITIOUS) == 0) {
4580						pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4581						if (TAILQ_EMPTY(&pvh->pv_list))
4582							vm_page_aflag_clear(m, PGA_WRITEABLE);
4583					}
4584					pmap_unuse_pt(pmap, pv->pv_va, &free);
4585				}
4586			}
4587		}
4588		if (allfree) {
4589			TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
4590			free_pv_chunk(pc);
4591		}
4592	}
4593	sched_unpin();
4594	pmap_invalidate_all(pmap);
4595	rw_wunlock(&pvh_global_lock);
4596	PMAP_UNLOCK(pmap);
4597	pmap_free_zero_pages(&free);
4598}
4599
4600/*
4601 *	pmap_is_modified:
4602 *
4603 *	Return whether or not the specified physical page was modified
4604 *	in any physical maps.
4605 */
4606boolean_t
4607pmap_is_modified(vm_page_t m)
4608{
4609	boolean_t rv;
4610
4611	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4612	    ("pmap_is_modified: page %p is not managed", m));
4613
4614	/*
4615	 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
4616	 * concurrently set while the object is locked.  Thus, if PGA_WRITEABLE
4617	 * is clear, no PTEs can have PG_M set.
4618	 */
4619	VM_OBJECT_ASSERT_WLOCKED(m->object);
4620	if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
4621		return (FALSE);
4622	rw_wlock(&pvh_global_lock);
4623	rv = pmap_is_modified_pvh(&m->md) ||
4624	    ((m->flags & PG_FICTITIOUS) == 0 &&
4625	    pmap_is_modified_pvh(pa_to_pvh(VM_PAGE_TO_PHYS(m))));
4626	rw_wunlock(&pvh_global_lock);
4627	return (rv);
4628}
4629
4630/*
4631 * Returns TRUE if any of the given mappings were used to modify
4632 * physical memory.  Otherwise, returns FALSE.  Both page and 2mpage
4633 * mappings are supported.
4634 */
4635static boolean_t
4636pmap_is_modified_pvh(struct md_page *pvh)
4637{
4638	pv_entry_t pv;
4639	pt_entry_t *pte;
4640	pmap_t pmap;
4641	boolean_t rv;
4642
4643	rw_assert(&pvh_global_lock, RA_WLOCKED);
4644	rv = FALSE;
4645	sched_pin();
4646	TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
4647		pmap = PV_PMAP(pv);
4648		PMAP_LOCK(pmap);
4649		pte = pmap_pte_quick(pmap, pv->pv_va);
4650		rv = (*pte & (PG_M | PG_RW)) == (PG_M | PG_RW);
4651		PMAP_UNLOCK(pmap);
4652		if (rv)
4653			break;
4654	}
4655	sched_unpin();
4656	return (rv);
4657}
4658
4659/*
4660 *	pmap_is_prefaultable:
4661 *
4662 *	Return whether or not the specified virtual address is elgible
4663 *	for prefault.
4664 */
4665boolean_t
4666pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
4667{
4668	pd_entry_t *pde;
4669	pt_entry_t *pte;
4670	boolean_t rv;
4671
4672	rv = FALSE;
4673	PMAP_LOCK(pmap);
4674	pde = pmap_pde(pmap, addr);
4675	if (*pde != 0 && (*pde & PG_PS) == 0) {
4676		pte = vtopte(addr);
4677		rv = *pte == 0;
4678	}
4679	PMAP_UNLOCK(pmap);
4680	return (rv);
4681}
4682
4683/*
4684 *	pmap_is_referenced:
4685 *
4686 *	Return whether or not the specified physical page was referenced
4687 *	in any physical maps.
4688 */
4689boolean_t
4690pmap_is_referenced(vm_page_t m)
4691{
4692	boolean_t rv;
4693
4694	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4695	    ("pmap_is_referenced: page %p is not managed", m));
4696	rw_wlock(&pvh_global_lock);
4697	rv = pmap_is_referenced_pvh(&m->md) ||
4698	    ((m->flags & PG_FICTITIOUS) == 0 &&
4699	    pmap_is_referenced_pvh(pa_to_pvh(VM_PAGE_TO_PHYS(m))));
4700	rw_wunlock(&pvh_global_lock);
4701	return (rv);
4702}
4703
4704/*
4705 * Returns TRUE if any of the given mappings were referenced and FALSE
4706 * otherwise.  Both page and 4mpage mappings are supported.
4707 */
4708static boolean_t
4709pmap_is_referenced_pvh(struct md_page *pvh)
4710{
4711	pv_entry_t pv;
4712	pt_entry_t *pte;
4713	pmap_t pmap;
4714	boolean_t rv;
4715
4716	rw_assert(&pvh_global_lock, RA_WLOCKED);
4717	rv = FALSE;
4718	sched_pin();
4719	TAILQ_FOREACH(pv, &pvh->pv_list, pv_next) {
4720		pmap = PV_PMAP(pv);
4721		PMAP_LOCK(pmap);
4722		pte = pmap_pte_quick(pmap, pv->pv_va);
4723		rv = (*pte & (PG_A | PG_V)) == (PG_A | PG_V);
4724		PMAP_UNLOCK(pmap);
4725		if (rv)
4726			break;
4727	}
4728	sched_unpin();
4729	return (rv);
4730}
4731
4732/*
4733 * Clear the write and modified bits in each of the given page's mappings.
4734 */
4735void
4736pmap_remove_write(vm_page_t m)
4737{
4738	struct md_page *pvh;
4739	pv_entry_t next_pv, pv;
4740	pmap_t pmap;
4741	pd_entry_t *pde;
4742	pt_entry_t oldpte, *pte;
4743	vm_offset_t va;
4744
4745	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4746	    ("pmap_remove_write: page %p is not managed", m));
4747
4748	/*
4749	 * If the page is not exclusive busied, then PGA_WRITEABLE cannot be
4750	 * set by another thread while the object is locked.  Thus,
4751	 * if PGA_WRITEABLE is clear, no page table entries need updating.
4752	 */
4753	VM_OBJECT_ASSERT_WLOCKED(m->object);
4754	if (!vm_page_xbusied(m) && (m->aflags & PGA_WRITEABLE) == 0)
4755		return;
4756	rw_wlock(&pvh_global_lock);
4757	sched_pin();
4758	if ((m->flags & PG_FICTITIOUS) != 0)
4759		goto small_mappings;
4760	pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
4761	TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
4762		va = pv->pv_va;
4763		pmap = PV_PMAP(pv);
4764		PMAP_LOCK(pmap);
4765		pde = pmap_pde(pmap, va);
4766		if ((*pde & PG_RW) != 0)
4767			(void)pmap_demote_pde(pmap, pde, va);
4768		PMAP_UNLOCK(pmap);
4769	}
4770small_mappings:
4771	TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
4772		pmap = PV_PMAP(pv);
4773		PMAP_LOCK(pmap);
4774		pde = pmap_pde(pmap, pv->pv_va);
4775		KASSERT((*pde & PG_PS) == 0, ("pmap_clear_write: found"
4776		    " a 4mpage in page %p's pv list", m));
4777		pte = pmap_pte_quick(pmap, pv->pv_va);
4778retry:
4779		oldpte = *pte;
4780		if ((oldpte & PG_RW) != 0) {
4781			/*
4782			 * Regardless of whether a pte is 32 or 64 bits
4783			 * in size, PG_RW and PG_M are among the least
4784			 * significant 32 bits.
4785			 */
4786			if (!atomic_cmpset_int((u_int *)pte, oldpte,
4787			    oldpte & ~(PG_RW | PG_M)))
4788				goto retry;
4789			if ((oldpte & PG_M) != 0)
4790				vm_page_dirty(m);
4791			pmap_invalidate_page(pmap, pv->pv_va);
4792		}
4793		PMAP_UNLOCK(pmap);
4794	}
4795	vm_page_aflag_clear(m, PGA_WRITEABLE);
4796	sched_unpin();
4797	rw_wunlock(&pvh_global_lock);
4798}
4799
4800#define	PMAP_TS_REFERENCED_MAX	5
4801
4802/*
4803 *	pmap_ts_referenced:
4804 *
4805 *	Return a count of reference bits for a page, clearing those bits.
4806 *	It is not necessary for every reference bit to be cleared, but it
4807 *	is necessary that 0 only be returned when there are truly no
4808 *	reference bits set.
4809 *
4810 *	XXX: The exact number of bits to check and clear is a matter that
4811 *	should be tested and standardized at some point in the future for
4812 *	optimal aging of shared pages.
4813 */
4814int
4815pmap_ts_referenced(vm_page_t m)
4816{
4817	struct md_page *pvh;
4818	pv_entry_t pv, pvf;
4819	pmap_t pmap;
4820	pd_entry_t *pde;
4821	pt_entry_t *pte;
4822	vm_paddr_t pa;
4823	int rtval = 0;
4824
4825	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
4826	    ("pmap_ts_referenced: page %p is not managed", m));
4827	pa = VM_PAGE_TO_PHYS(m);
4828	pvh = pa_to_pvh(pa);
4829	rw_wlock(&pvh_global_lock);
4830	sched_pin();
4831	if ((m->flags & PG_FICTITIOUS) != 0 ||
4832	    (pvf = TAILQ_FIRST(&pvh->pv_list)) == NULL)
4833		goto small_mappings;
4834	pv = pvf;
4835	do {
4836		pmap = PV_PMAP(pv);
4837		PMAP_LOCK(pmap);
4838		pde = pmap_pde(pmap, pv->pv_va);
4839		if ((*pde & PG_A) != 0) {
4840			/*
4841			 * Since this reference bit is shared by either 1024
4842			 * or 512 4KB pages, it should not be cleared every
4843			 * time it is tested.  Apply a simple "hash" function
4844			 * on the physical page number, the virtual superpage
4845			 * number, and the pmap address to select one 4KB page
4846			 * out of the 1024 or 512 on which testing the
4847			 * reference bit will result in clearing that bit.
4848			 * This function is designed to avoid the selection of
4849			 * the same 4KB page for every 2- or 4MB page mapping.
4850			 *
4851			 * On demotion, a mapping that hasn't been referenced
4852			 * is simply destroyed.  To avoid the possibility of a
4853			 * subsequent page fault on a demoted wired mapping,
4854			 * always leave its reference bit set.  Moreover,
4855			 * since the superpage is wired, the current state of
4856			 * its reference bit won't affect page replacement.
4857			 */
4858			if ((((pa >> PAGE_SHIFT) ^ (pv->pv_va >> PDRSHIFT) ^
4859			    (uintptr_t)pmap) & (NPTEPG - 1)) == 0 &&
4860			    (*pde & PG_W) == 0) {
4861				atomic_clear_int((u_int *)pde, PG_A);
4862				pmap_invalidate_page(pmap, pv->pv_va);
4863			}
4864			rtval++;
4865		}
4866		PMAP_UNLOCK(pmap);
4867		/* Rotate the PV list if it has more than one entry. */
4868		if (TAILQ_NEXT(pv, pv_next) != NULL) {
4869			TAILQ_REMOVE(&pvh->pv_list, pv, pv_next);
4870			TAILQ_INSERT_TAIL(&pvh->pv_list, pv, pv_next);
4871		}
4872		if (rtval >= PMAP_TS_REFERENCED_MAX)
4873			goto out;
4874	} while ((pv = TAILQ_FIRST(&pvh->pv_list)) != pvf);
4875small_mappings:
4876	if ((pvf = TAILQ_FIRST(&m->md.pv_list)) == NULL)
4877		goto out;
4878	pv = pvf;
4879	do {
4880		pmap = PV_PMAP(pv);
4881		PMAP_LOCK(pmap);
4882		pde = pmap_pde(pmap, pv->pv_va);
4883		KASSERT((*pde & PG_PS) == 0,
4884		    ("pmap_ts_referenced: found a 4mpage in page %p's pv list",
4885		    m));
4886		pte = pmap_pte_quick(pmap, pv->pv_va);
4887		if ((*pte & PG_A) != 0) {
4888			atomic_clear_int((u_int *)pte, PG_A);
4889			pmap_invalidate_page(pmap, pv->pv_va);
4890			rtval++;
4891		}
4892		PMAP_UNLOCK(pmap);
4893		/* Rotate the PV list if it has more than one entry. */
4894		if (TAILQ_NEXT(pv, pv_next) != NULL) {
4895			TAILQ_REMOVE(&m->md.pv_list, pv, pv_next);
4896			TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_next);
4897		}
4898	} while ((pv = TAILQ_FIRST(&m->md.pv_list)) != pvf && rtval <
4899	    PMAP_TS_REFERENCED_MAX);
4900out:
4901	sched_unpin();
4902	rw_wunlock(&pvh_global_lock);
4903	return (rtval);
4904}
4905
4906/*
4907 *	Apply the given advice to the specified range of addresses within the
4908 *	given pmap.  Depending on the advice, clear the referenced and/or
4909 *	modified flags in each mapping and set the mapped page's dirty field.
4910 */
4911void
4912pmap_advise(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, int advice)
4913{
4914	pd_entry_t oldpde, *pde;
4915	pt_entry_t *pte;
4916	vm_offset_t pdnxt;
4917	vm_page_t m;
4918	boolean_t anychanged, pv_lists_locked;
4919
4920	if (advice != MADV_DONTNEED && advice != MADV_FREE)
4921		return;
4922	if (pmap_is_current(pmap))
4923		pv_lists_locked = FALSE;
4924	else {
4925		pv_lists_locked = TRUE;
4926resume:
4927		rw_wlock(&pvh_global_lock);
4928		sched_pin();
4929	}
4930	anychanged = FALSE;
4931	PMAP_LOCK(pmap);
4932	for (; sva < eva; sva = pdnxt) {
4933		pdnxt = (sva + NBPDR) & ~PDRMASK;
4934		if (pdnxt < sva)
4935			pdnxt = eva;
4936		pde = pmap_pde(pmap, sva);
4937		oldpde = *pde;
4938		if ((oldpde & PG_V) == 0)
4939			continue;
4940		else if ((oldpde & PG_PS) != 0) {
4941			if ((oldpde & PG_MANAGED) == 0)
4942				continue;
4943			if (!pv_lists_locked) {
4944				pv_lists_locked = TRUE;
4945				if (!rw_try_wlock(&pvh_global_lock)) {
4946					if (anychanged)
4947						pmap_invalidate_all(pmap);
4948					PMAP_UNLOCK(pmap);
4949					goto resume;
4950				}
4951				sched_pin();
4952			}
4953			if (!pmap_demote_pde(pmap, pde, sva)) {
4954				/*
4955				 * The large page mapping was destroyed.
4956				 */
4957				continue;
4958			}
4959
4960			/*
4961			 * Unless the page mappings are wired, remove the
4962			 * mapping to a single page so that a subsequent
4963			 * access may repromote.  Since the underlying page
4964			 * table page is fully populated, this removal never
4965			 * frees a page table page.
4966			 */
4967			if ((oldpde & PG_W) == 0) {
4968				pte = pmap_pte_quick(pmap, sva);
4969				KASSERT((*pte & PG_V) != 0,
4970				    ("pmap_advise: invalid PTE"));
4971				pmap_remove_pte(pmap, pte, sva, NULL);
4972				anychanged = TRUE;
4973			}
4974		}
4975		if (pdnxt > eva)
4976			pdnxt = eva;
4977		for (pte = pmap_pte_quick(pmap, sva); sva != pdnxt; pte++,
4978		    sva += PAGE_SIZE) {
4979			if ((*pte & (PG_MANAGED | PG_V)) != (PG_MANAGED |
4980			    PG_V))
4981				continue;
4982			else if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
4983				if (advice == MADV_DONTNEED) {
4984					/*
4985					 * Future calls to pmap_is_modified()
4986					 * can be avoided by making the page
4987					 * dirty now.
4988					 */
4989					m = PHYS_TO_VM_PAGE(*pte & PG_FRAME);
4990					vm_page_dirty(m);
4991				}
4992				atomic_clear_int((u_int *)pte, PG_M | PG_A);
4993			} else if ((*pte & PG_A) != 0)
4994				atomic_clear_int((u_int *)pte, PG_A);
4995			else
4996				continue;
4997			if ((*pte & PG_G) != 0)
4998				pmap_invalidate_page(pmap, sva);
4999			else
5000				anychanged = TRUE;
5001		}
5002	}
5003	if (anychanged)
5004		pmap_invalidate_all(pmap);
5005	if (pv_lists_locked) {
5006		sched_unpin();
5007		rw_wunlock(&pvh_global_lock);
5008	}
5009	PMAP_UNLOCK(pmap);
5010}
5011
5012/*
5013 *	Clear the modify bits on the specified physical page.
5014 */
5015void
5016pmap_clear_modify(vm_page_t m)
5017{
5018	struct md_page *pvh;
5019	pv_entry_t next_pv, pv;
5020	pmap_t pmap;
5021	pd_entry_t oldpde, *pde;
5022	pt_entry_t oldpte, *pte;
5023	vm_offset_t va;
5024
5025	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
5026	    ("pmap_clear_modify: page %p is not managed", m));
5027	VM_OBJECT_ASSERT_WLOCKED(m->object);
5028	KASSERT(!vm_page_xbusied(m),
5029	    ("pmap_clear_modify: page %p is exclusive busied", m));
5030
5031	/*
5032	 * If the page is not PGA_WRITEABLE, then no PTEs can have PG_M set.
5033	 * If the object containing the page is locked and the page is not
5034	 * exclusive busied, then PGA_WRITEABLE cannot be concurrently set.
5035	 */
5036	if ((m->aflags & PGA_WRITEABLE) == 0)
5037		return;
5038	rw_wlock(&pvh_global_lock);
5039	sched_pin();
5040	if ((m->flags & PG_FICTITIOUS) != 0)
5041		goto small_mappings;
5042	pvh = pa_to_pvh(VM_PAGE_TO_PHYS(m));
5043	TAILQ_FOREACH_SAFE(pv, &pvh->pv_list, pv_next, next_pv) {
5044		va = pv->pv_va;
5045		pmap = PV_PMAP(pv);
5046		PMAP_LOCK(pmap);
5047		pde = pmap_pde(pmap, va);
5048		oldpde = *pde;
5049		if ((oldpde & PG_RW) != 0) {
5050			if (pmap_demote_pde(pmap, pde, va)) {
5051				if ((oldpde & PG_W) == 0) {
5052					/*
5053					 * Write protect the mapping to a
5054					 * single page so that a subsequent
5055					 * write access may repromote.
5056					 */
5057					va += VM_PAGE_TO_PHYS(m) - (oldpde &
5058					    PG_PS_FRAME);
5059					pte = pmap_pte_quick(pmap, va);
5060					oldpte = *pte;
5061					if ((oldpte & PG_V) != 0) {
5062						/*
5063						 * Regardless of whether a pte is 32 or 64 bits
5064						 * in size, PG_RW and PG_M are among the least
5065						 * significant 32 bits.
5066						 */
5067						while (!atomic_cmpset_int((u_int *)pte,
5068						    oldpte,
5069						    oldpte & ~(PG_M | PG_RW)))
5070							oldpte = *pte;
5071						vm_page_dirty(m);
5072						pmap_invalidate_page(pmap, va);
5073					}
5074				}
5075			}
5076		}
5077		PMAP_UNLOCK(pmap);
5078	}
5079small_mappings:
5080	TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5081		pmap = PV_PMAP(pv);
5082		PMAP_LOCK(pmap);
5083		pde = pmap_pde(pmap, pv->pv_va);
5084		KASSERT((*pde & PG_PS) == 0, ("pmap_clear_modify: found"
5085		    " a 4mpage in page %p's pv list", m));
5086		pte = pmap_pte_quick(pmap, pv->pv_va);
5087		if ((*pte & (PG_M | PG_RW)) == (PG_M | PG_RW)) {
5088			/*
5089			 * Regardless of whether a pte is 32 or 64 bits
5090			 * in size, PG_M is among the least significant
5091			 * 32 bits.
5092			 */
5093			atomic_clear_int((u_int *)pte, PG_M);
5094			pmap_invalidate_page(pmap, pv->pv_va);
5095		}
5096		PMAP_UNLOCK(pmap);
5097	}
5098	sched_unpin();
5099	rw_wunlock(&pvh_global_lock);
5100}
5101
5102/*
5103 * Miscellaneous support routines follow
5104 */
5105
5106/* Adjust the cache mode for a 4KB page mapped via a PTE. */
5107static __inline void
5108pmap_pte_attr(pt_entry_t *pte, int cache_bits)
5109{
5110	u_int opte, npte;
5111
5112	/*
5113	 * The cache mode bits are all in the low 32-bits of the
5114	 * PTE, so we can just spin on updating the low 32-bits.
5115	 */
5116	do {
5117		opte = *(u_int *)pte;
5118		npte = opte & ~PG_PTE_CACHE;
5119		npte |= cache_bits;
5120	} while (npte != opte && !atomic_cmpset_int((u_int *)pte, opte, npte));
5121}
5122
5123/* Adjust the cache mode for a 2/4MB page mapped via a PDE. */
5124static __inline void
5125pmap_pde_attr(pd_entry_t *pde, int cache_bits)
5126{
5127	u_int opde, npde;
5128
5129	/*
5130	 * The cache mode bits are all in the low 32-bits of the
5131	 * PDE, so we can just spin on updating the low 32-bits.
5132	 */
5133	do {
5134		opde = *(u_int *)pde;
5135		npde = opde & ~PG_PDE_CACHE;
5136		npde |= cache_bits;
5137	} while (npde != opde && !atomic_cmpset_int((u_int *)pde, opde, npde));
5138}
5139
5140/*
5141 * Map a set of physical memory pages into the kernel virtual
5142 * address space. Return a pointer to where it is mapped. This
5143 * routine is intended to be used for mapping device memory,
5144 * NOT real memory.
5145 */
5146void *
5147pmap_mapdev_attr(vm_paddr_t pa, vm_size_t size, int mode)
5148{
5149	vm_offset_t va, offset;
5150	vm_size_t tmpsize;
5151
5152	offset = pa & PAGE_MASK;
5153	size = round_page(offset + size);
5154	pa = pa & PG_FRAME;
5155
5156	if (pa < KERNLOAD && pa + size <= KERNLOAD)
5157		va = KERNBASE + pa;
5158	else
5159		va = kva_alloc(size);
5160	if (!va)
5161		panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
5162
5163	for (tmpsize = 0; tmpsize < size; tmpsize += PAGE_SIZE)
5164		pmap_kenter_attr(va + tmpsize, pa + tmpsize, mode);
5165	pmap_invalidate_range(kernel_pmap, va, va + tmpsize);
5166	pmap_invalidate_cache_range(va, va + size);
5167	return ((void *)(va + offset));
5168}
5169
5170void *
5171pmap_mapdev(vm_paddr_t pa, vm_size_t size)
5172{
5173
5174	return (pmap_mapdev_attr(pa, size, PAT_UNCACHEABLE));
5175}
5176
5177void *
5178pmap_mapbios(vm_paddr_t pa, vm_size_t size)
5179{
5180
5181	return (pmap_mapdev_attr(pa, size, PAT_WRITE_BACK));
5182}
5183
5184void
5185pmap_unmapdev(vm_offset_t va, vm_size_t size)
5186{
5187	vm_offset_t base, offset;
5188
5189	if (va >= KERNBASE && va + size <= KERNBASE + KERNLOAD)
5190		return;
5191	base = trunc_page(va);
5192	offset = va & PAGE_MASK;
5193	size = round_page(offset + size);
5194	kva_free(base, size);
5195}
5196
5197/*
5198 * Sets the memory attribute for the specified page.
5199 */
5200void
5201pmap_page_set_memattr(vm_page_t m, vm_memattr_t ma)
5202{
5203
5204	m->md.pat_mode = ma;
5205	if ((m->flags & PG_FICTITIOUS) != 0)
5206		return;
5207
5208	/*
5209	 * If "m" is a normal page, flush it from the cache.
5210	 * See pmap_invalidate_cache_range().
5211	 *
5212	 * First, try to find an existing mapping of the page by sf
5213	 * buffer. sf_buf_invalidate_cache() modifies mapping and
5214	 * flushes the cache.
5215	 */
5216	if (sf_buf_invalidate_cache(m))
5217		return;
5218
5219	/*
5220	 * If page is not mapped by sf buffer, but CPU does not
5221	 * support self snoop, map the page transient and do
5222	 * invalidation. In the worst case, whole cache is flushed by
5223	 * pmap_invalidate_cache_range().
5224	 */
5225	if ((cpu_feature & CPUID_SS) == 0)
5226		pmap_flush_page(m);
5227}
5228
5229static void
5230pmap_flush_page(vm_page_t m)
5231{
5232	struct sysmaps *sysmaps;
5233	vm_offset_t sva, eva;
5234
5235	if ((cpu_feature & CPUID_CLFSH) != 0) {
5236		sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
5237		mtx_lock(&sysmaps->lock);
5238		if (*sysmaps->CMAP2)
5239			panic("pmap_flush_page: CMAP2 busy");
5240		sched_pin();
5241		*sysmaps->CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) |
5242		    PG_A | PG_M | pmap_cache_bits(m->md.pat_mode, 0);
5243		invlcaddr(sysmaps->CADDR2);
5244		sva = (vm_offset_t)sysmaps->CADDR2;
5245		eva = sva + PAGE_SIZE;
5246
5247		/*
5248		 * Use mfence despite the ordering implied by
5249		 * mtx_{un,}lock() because clflush is not guaranteed
5250		 * to be ordered by any other instruction.
5251		 */
5252		mfence();
5253		for (; sva < eva; sva += cpu_clflush_line_size)
5254			clflush(sva);
5255		mfence();
5256		*sysmaps->CMAP2 = 0;
5257		sched_unpin();
5258		mtx_unlock(&sysmaps->lock);
5259	} else
5260		pmap_invalidate_cache();
5261}
5262
5263/*
5264 * Changes the specified virtual address range's memory type to that given by
5265 * the parameter "mode".  The specified virtual address range must be
5266 * completely contained within either the kernel map.
5267 *
5268 * Returns zero if the change completed successfully, and either EINVAL or
5269 * ENOMEM if the change failed.  Specifically, EINVAL is returned if some part
5270 * of the virtual address range was not mapped, and ENOMEM is returned if
5271 * there was insufficient memory available to complete the change.
5272 */
5273int
5274pmap_change_attr(vm_offset_t va, vm_size_t size, int mode)
5275{
5276	vm_offset_t base, offset, tmpva;
5277	pd_entry_t *pde;
5278	pt_entry_t *pte;
5279	int cache_bits_pte, cache_bits_pde;
5280	boolean_t changed;
5281
5282	base = trunc_page(va);
5283	offset = va & PAGE_MASK;
5284	size = round_page(offset + size);
5285
5286	/*
5287	 * Only supported on kernel virtual addresses above the recursive map.
5288	 */
5289	if (base < VM_MIN_KERNEL_ADDRESS)
5290		return (EINVAL);
5291
5292	cache_bits_pde = pmap_cache_bits(mode, 1);
5293	cache_bits_pte = pmap_cache_bits(mode, 0);
5294	changed = FALSE;
5295
5296	/*
5297	 * Pages that aren't mapped aren't supported.  Also break down
5298	 * 2/4MB pages into 4KB pages if required.
5299	 */
5300	PMAP_LOCK(kernel_pmap);
5301	for (tmpva = base; tmpva < base + size; ) {
5302		pde = pmap_pde(kernel_pmap, tmpva);
5303		if (*pde == 0) {
5304			PMAP_UNLOCK(kernel_pmap);
5305			return (EINVAL);
5306		}
5307		if (*pde & PG_PS) {
5308			/*
5309			 * If the current 2/4MB page already has
5310			 * the required memory type, then we need not
5311			 * demote this page.  Just increment tmpva to
5312			 * the next 2/4MB page frame.
5313			 */
5314			if ((*pde & PG_PDE_CACHE) == cache_bits_pde) {
5315				tmpva = trunc_4mpage(tmpva) + NBPDR;
5316				continue;
5317			}
5318
5319			/*
5320			 * If the current offset aligns with a 2/4MB
5321			 * page frame and there is at least 2/4MB left
5322			 * within the range, then we need not break
5323			 * down this page into 4KB pages.
5324			 */
5325			if ((tmpva & PDRMASK) == 0 &&
5326			    tmpva + PDRMASK < base + size) {
5327				tmpva += NBPDR;
5328				continue;
5329			}
5330			if (!pmap_demote_pde(kernel_pmap, pde, tmpva)) {
5331				PMAP_UNLOCK(kernel_pmap);
5332				return (ENOMEM);
5333			}
5334		}
5335		pte = vtopte(tmpva);
5336		if (*pte == 0) {
5337			PMAP_UNLOCK(kernel_pmap);
5338			return (EINVAL);
5339		}
5340		tmpva += PAGE_SIZE;
5341	}
5342	PMAP_UNLOCK(kernel_pmap);
5343
5344	/*
5345	 * Ok, all the pages exist, so run through them updating their
5346	 * cache mode if required.
5347	 */
5348	for (tmpva = base; tmpva < base + size; ) {
5349		pde = pmap_pde(kernel_pmap, tmpva);
5350		if (*pde & PG_PS) {
5351			if ((*pde & PG_PDE_CACHE) != cache_bits_pde) {
5352				pmap_pde_attr(pde, cache_bits_pde);
5353				changed = TRUE;
5354			}
5355			tmpva = trunc_4mpage(tmpva) + NBPDR;
5356		} else {
5357			pte = vtopte(tmpva);
5358			if ((*pte & PG_PTE_CACHE) != cache_bits_pte) {
5359				pmap_pte_attr(pte, cache_bits_pte);
5360				changed = TRUE;
5361			}
5362			tmpva += PAGE_SIZE;
5363		}
5364	}
5365
5366	/*
5367	 * Flush CPU caches to make sure any data isn't cached that
5368	 * shouldn't be, etc.
5369	 */
5370	if (changed) {
5371		pmap_invalidate_range(kernel_pmap, base, tmpva);
5372		pmap_invalidate_cache_range(base, tmpva);
5373	}
5374	return (0);
5375}
5376
5377/*
5378 * perform the pmap work for mincore
5379 */
5380int
5381pmap_mincore(pmap_t pmap, vm_offset_t addr, vm_paddr_t *locked_pa)
5382{
5383	pd_entry_t *pdep;
5384	pt_entry_t *ptep, pte;
5385	vm_paddr_t pa;
5386	int val;
5387
5388	PMAP_LOCK(pmap);
5389retry:
5390	pdep = pmap_pde(pmap, addr);
5391	if (*pdep != 0) {
5392		if (*pdep & PG_PS) {
5393			pte = *pdep;
5394			/* Compute the physical address of the 4KB page. */
5395			pa = ((*pdep & PG_PS_FRAME) | (addr & PDRMASK)) &
5396			    PG_FRAME;
5397			val = MINCORE_SUPER;
5398		} else {
5399			ptep = pmap_pte(pmap, addr);
5400			pte = *ptep;
5401			pmap_pte_release(ptep);
5402			pa = pte & PG_FRAME;
5403			val = 0;
5404		}
5405	} else {
5406		pte = 0;
5407		pa = 0;
5408		val = 0;
5409	}
5410	if ((pte & PG_V) != 0) {
5411		val |= MINCORE_INCORE;
5412		if ((pte & (PG_M | PG_RW)) == (PG_M | PG_RW))
5413			val |= MINCORE_MODIFIED | MINCORE_MODIFIED_OTHER;
5414		if ((pte & PG_A) != 0)
5415			val |= MINCORE_REFERENCED | MINCORE_REFERENCED_OTHER;
5416	}
5417	if ((val & (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER)) !=
5418	    (MINCORE_MODIFIED_OTHER | MINCORE_REFERENCED_OTHER) &&
5419	    (pte & (PG_MANAGED | PG_V)) == (PG_MANAGED | PG_V)) {
5420		/* Ensure that "PHYS_TO_VM_PAGE(pa)->object" doesn't change. */
5421		if (vm_page_pa_tryrelock(pmap, pa, locked_pa))
5422			goto retry;
5423	} else
5424		PA_UNLOCK_COND(*locked_pa);
5425	PMAP_UNLOCK(pmap);
5426	return (val);
5427}
5428
5429void
5430pmap_activate(struct thread *td)
5431{
5432	pmap_t	pmap, oldpmap;
5433	u_int	cpuid;
5434	u_int32_t  cr3;
5435
5436	critical_enter();
5437	pmap = vmspace_pmap(td->td_proc->p_vmspace);
5438	oldpmap = PCPU_GET(curpmap);
5439	cpuid = PCPU_GET(cpuid);
5440#if defined(SMP)
5441	CPU_CLR_ATOMIC(cpuid, &oldpmap->pm_active);
5442	CPU_SET_ATOMIC(cpuid, &pmap->pm_active);
5443#else
5444	CPU_CLR(cpuid, &oldpmap->pm_active);
5445	CPU_SET(cpuid, &pmap->pm_active);
5446#endif
5447#ifdef PAE
5448	cr3 = vtophys(pmap->pm_pdpt);
5449#else
5450	cr3 = vtophys(pmap->pm_pdir);
5451#endif
5452	/*
5453	 * pmap_activate is for the current thread on the current cpu
5454	 */
5455	td->td_pcb->pcb_cr3 = cr3;
5456	load_cr3(cr3);
5457	PCPU_SET(curpmap, pmap);
5458	critical_exit();
5459}
5460
5461void
5462pmap_sync_icache(pmap_t pm, vm_offset_t va, vm_size_t sz)
5463{
5464}
5465
5466/*
5467 *	Increase the starting virtual address of the given mapping if a
5468 *	different alignment might result in more superpage mappings.
5469 */
5470void
5471pmap_align_superpage(vm_object_t object, vm_ooffset_t offset,
5472    vm_offset_t *addr, vm_size_t size)
5473{
5474	vm_offset_t superpage_offset;
5475
5476	if (size < NBPDR)
5477		return;
5478	if (object != NULL && (object->flags & OBJ_COLORED) != 0)
5479		offset += ptoa(object->pg_color);
5480	superpage_offset = offset & PDRMASK;
5481	if (size - ((NBPDR - superpage_offset) & PDRMASK) < NBPDR ||
5482	    (*addr & PDRMASK) == superpage_offset)
5483		return;
5484	if ((*addr & PDRMASK) < superpage_offset)
5485		*addr = (*addr & ~PDRMASK) + superpage_offset;
5486	else
5487		*addr = ((*addr + PDRMASK) & ~PDRMASK) + superpage_offset;
5488}
5489
5490
5491#if defined(PMAP_DEBUG)
5492pmap_pid_dump(int pid)
5493{
5494	pmap_t pmap;
5495	struct proc *p;
5496	int npte = 0;
5497	int index;
5498
5499	sx_slock(&allproc_lock);
5500	FOREACH_PROC_IN_SYSTEM(p) {
5501		if (p->p_pid != pid)
5502			continue;
5503
5504		if (p->p_vmspace) {
5505			int i,j;
5506			index = 0;
5507			pmap = vmspace_pmap(p->p_vmspace);
5508			for (i = 0; i < NPDEPTD; i++) {
5509				pd_entry_t *pde;
5510				pt_entry_t *pte;
5511				vm_offset_t base = i << PDRSHIFT;
5512
5513				pde = &pmap->pm_pdir[i];
5514				if (pde && pmap_pde_v(pde)) {
5515					for (j = 0; j < NPTEPG; j++) {
5516						vm_offset_t va = base + (j << PAGE_SHIFT);
5517						if (va >= (vm_offset_t) VM_MIN_KERNEL_ADDRESS) {
5518							if (index) {
5519								index = 0;
5520								printf("\n");
5521							}
5522							sx_sunlock(&allproc_lock);
5523							return (npte);
5524						}
5525						pte = pmap_pte(pmap, va);
5526						if (pte && pmap_pte_v(pte)) {
5527							pt_entry_t pa;
5528							vm_page_t m;
5529							pa = *pte;
5530							m = PHYS_TO_VM_PAGE(pa & PG_FRAME);
5531							printf("va: 0x%x, pt: 0x%x, h: %d, w: %d, f: 0x%x",
5532								va, pa, m->hold_count, m->wire_count, m->flags);
5533							npte++;
5534							index++;
5535							if (index >= 2) {
5536								index = 0;
5537								printf("\n");
5538							} else {
5539								printf(" ");
5540							}
5541						}
5542					}
5543				}
5544			}
5545		}
5546	}
5547	sx_sunlock(&allproc_lock);
5548	return (npte);
5549}
5550#endif
5551
5552#if defined(DEBUG)
5553
5554static void	pads(pmap_t pm);
5555void		pmap_pvdump(vm_paddr_t pa);
5556
5557/* print address space of pmap*/
5558static void
5559pads(pmap_t pm)
5560{
5561	int i, j;
5562	vm_paddr_t va;
5563	pt_entry_t *ptep;
5564
5565	if (pm == kernel_pmap)
5566		return;
5567	for (i = 0; i < NPDEPTD; i++)
5568		if (pm->pm_pdir[i])
5569			for (j = 0; j < NPTEPG; j++) {
5570				va = (i << PDRSHIFT) + (j << PAGE_SHIFT);
5571				if (pm == kernel_pmap && va < KERNBASE)
5572					continue;
5573				if (pm != kernel_pmap && va > UPT_MAX_ADDRESS)
5574					continue;
5575				ptep = pmap_pte(pm, va);
5576				if (pmap_pte_v(ptep))
5577					printf("%x:%x ", va, *ptep);
5578			};
5579
5580}
5581
5582void
5583pmap_pvdump(vm_paddr_t pa)
5584{
5585	pv_entry_t pv;
5586	pmap_t pmap;
5587	vm_page_t m;
5588
5589	printf("pa %x", pa);
5590	m = PHYS_TO_VM_PAGE(pa);
5591	TAILQ_FOREACH(pv, &m->md.pv_list, pv_next) {
5592		pmap = PV_PMAP(pv);
5593		printf(" -> pmap %p, va %x", (void *)pmap, pv->pv_va);
5594		pads(pmap);
5595	}
5596	printf(" ");
5597}
5598#endif
5599