pmap.c revision 152219
12116Sjkh/*-
22116Sjkh * Copyright (c) 1991 Regents of the University of California.
32116Sjkh * All rights reserved.
42116Sjkh * Copyright (c) 1994 John S. Dyson
52116Sjkh * All rights reserved.
62116Sjkh * Copyright (c) 1994 David Greenman
72116Sjkh * All rights reserved.
82116Sjkh * Copyright (c) 2005 Alan L. Cox <alc@cs.rice.edu>
92116Sjkh * All rights reserved.
102116Sjkh *
118870Srgrimes * This code is derived from software contributed to Berkeley by
122116Sjkh * the Systems Programming Group of the University of Utah Computer
132116Sjkh * Science Department and William Jolitz of UUNET Technologies Inc.
142116Sjkh *
152116Sjkh * Redistribution and use in source and binary forms, with or without
162116Sjkh * modification, are permitted provided that the following conditions
1750476Speter * are met:
182116Sjkh * 1. Redistributions of source code must retain the above copyright
192116Sjkh *    notice, this list of conditions and the following disclaimer.
202116Sjkh * 2. Redistributions in binary form must reproduce the above copyright
212116Sjkh *    notice, this list of conditions and the following disclaimer in the
222116Sjkh *    documentation and/or other materials provided with the distribution.
232116Sjkh * 3. All advertising materials mentioning features or use of this software
242116Sjkh *    must display the following acknowledgement:
252116Sjkh *	This product includes software developed by the University of
262116Sjkh *	California, Berkeley and its contributors.
272116Sjkh * 4. Neither the name of the University nor the names of its contributors
282116Sjkh *    may be used to endorse or promote products derived from this software
29152947Sbde *    without specific prior written permission.
30152947Sbde *
31152947Sbde * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
32152947Sbde * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
332116Sjkh * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34176032Sbde * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
35176032Sbde * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36176032Sbde * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
37176032Sbde * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38176032Sbde * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
39176032Sbde * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
402116Sjkh * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
41175468Sdas * SUCH DAMAGE.
42175468Sdas *
4397407Salfred *	from:	@(#)pmap.c	7.7 (Berkeley)	5/12/91
44142369Sdas */
452116Sjkh/*-
46142369Sdas * Copyright (c) 2003 Networks Associates Technology, Inc.
4717141Sjkh * All rights reserved.
482116Sjkh *
492116Sjkh * This software was developed for the FreeBSD Project by Jake Burkholder,
502116Sjkh * Safeport Network Services, and Network Associates Laboratories, the
512116Sjkh * Security Research Division of Network Associates, Inc. under
52142369Sdas * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
532116Sjkh * CHATS research program.
542116Sjkh *
552116Sjkh * Redistribution and use in source and binary forms, with or without
562116Sjkh * modification, are permitted provided that the following conditions
572116Sjkh * are met:
582116Sjkh * 1. Redistributions of source code must retain the above copyright
592116Sjkh *    notice, this list of conditions and the following disclaimer.
602116Sjkh * 2. Redistributions in binary form must reproduce the above copyright
612116Sjkh *    notice, this list of conditions and the following disclaimer in the
622116Sjkh *    documentation and/or other materials provided with the distribution.
632116Sjkh *
642116Sjkh * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
658870Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
662116Sjkh * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
67142369Sdas * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
682116Sjkh * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
692116Sjkh * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
702116Sjkh * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
71142369Sdas * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
72142369Sdas * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
732116Sjkh * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
74142369Sdas * SUCH DAMAGE.
758870Srgrimes */
762116Sjkh
772116Sjkh#include <sys/cdefs.h>
782116Sjkh__FBSDID("$FreeBSD: head/sys/i386/i386/pmap.c 152219 2005-11-09 03:55:40Z imp $");
792116Sjkh
802116Sjkh/*
812116Sjkh *	Manages physical address maps.
822116Sjkh *
83176032Sbde *	In addition to hardware address maps, this
84142369Sdas *	module is called upon to provide software-use-only
85142369Sdas *	maps which may or may not be stored in the same
862116Sjkh *	form as hardware maps.  These pseudo-maps are
872116Sjkh *	used to store intermediate results from copy
882116Sjkh *	operations to and from address spaces.
892116Sjkh *
902116Sjkh *	Since the information managed by this module is
912116Sjkh *	also stored by the logical address mapping module,
922116Sjkh *	this module may throw away valid virtual-to-physical
932116Sjkh *	mappings at almost any time.  However, invalidations
942116Sjkh *	of virtual-to-physical mappings must be done as
952116Sjkh *	requested.
962116Sjkh *
972116Sjkh *	In order to cope with hardware architectures which
98 *	make virtual-to-physical map invalidates expensive,
99 *	this module may delay invalidate or reduced protection
100 *	operations until such time as they are actually
101 *	necessary.  This module is given full information as
102 *	to which processors are currently using which maps,
103 *	and to when physical maps must be made correct.
104 */
105
106#include "opt_cpu.h"
107#include "opt_pmap.h"
108#include "opt_msgbuf.h"
109#include "opt_xbox.h"
110
111#include <sys/param.h>
112#include <sys/systm.h>
113#include <sys/kernel.h>
114#include <sys/lock.h>
115#include <sys/malloc.h>
116#include <sys/mman.h>
117#include <sys/msgbuf.h>
118#include <sys/mutex.h>
119#include <sys/proc.h>
120#include <sys/sx.h>
121#include <sys/vmmeter.h>
122#include <sys/sched.h>
123#include <sys/sysctl.h>
124#ifdef SMP
125#include <sys/smp.h>
126#endif
127
128#include <vm/vm.h>
129#include <vm/vm_param.h>
130#include <vm/vm_kern.h>
131#include <vm/vm_page.h>
132#include <vm/vm_map.h>
133#include <vm/vm_object.h>
134#include <vm/vm_extern.h>
135#include <vm/vm_pageout.h>
136#include <vm/vm_pager.h>
137#include <vm/uma.h>
138
139#include <machine/cpu.h>
140#include <machine/cputypes.h>
141#include <machine/md_var.h>
142#include <machine/pcb.h>
143#include <machine/specialreg.h>
144#ifdef SMP
145#include <machine/smp.h>
146#endif
147
148#ifdef XBOX
149#include <machine/xbox.h>
150#endif
151
152#if !defined(CPU_DISABLE_SSE) && defined(I686_CPU)
153#define CPU_ENABLE_SSE
154#endif
155
156#ifndef PMAP_SHPGPERPROC
157#define PMAP_SHPGPERPROC 200
158#endif
159
160#if defined(DIAGNOSTIC)
161#define PMAP_DIAGNOSTIC
162#endif
163
164#if !defined(PMAP_DIAGNOSTIC)
165#define PMAP_INLINE __inline
166#else
167#define PMAP_INLINE
168#endif
169
170/*
171 * Get PDEs and PTEs for user/kernel address space
172 */
173#define	pmap_pde(m, v)	(&((m)->pm_pdir[(vm_offset_t)(v) >> PDRSHIFT]))
174#define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
175
176#define pmap_pde_v(pte)		((*(int *)pte & PG_V) != 0)
177#define pmap_pte_w(pte)		((*(int *)pte & PG_W) != 0)
178#define pmap_pte_m(pte)		((*(int *)pte & PG_M) != 0)
179#define pmap_pte_u(pte)		((*(int *)pte & PG_A) != 0)
180#define pmap_pte_v(pte)		((*(int *)pte & PG_V) != 0)
181
182#define pmap_pte_set_w(pte, v)	((v) ? atomic_set_int((u_int *)(pte), PG_W) : \
183    atomic_clear_int((u_int *)(pte), PG_W))
184#define pmap_pte_set_prot(pte, v) ((*(int *)pte &= ~PG_PROT), (*(int *)pte |= (v)))
185
186struct pmap kernel_pmap_store;
187LIST_HEAD(pmaplist, pmap);
188static struct pmaplist allpmaps;
189static struct mtx allpmaps_lock;
190
191vm_paddr_t avail_end;	/* PA of last available physical page */
192vm_offset_t virtual_avail;	/* VA of first avail page (after kernel bss) */
193vm_offset_t virtual_end;	/* VA of last avail page (end of kernel AS) */
194int pgeflag = 0;		/* PG_G or-in */
195int pseflag = 0;		/* PG_PS or-in */
196
197static int nkpt;
198vm_offset_t kernel_vm_end;
199extern u_int32_t KERNend;
200
201#ifdef PAE
202static uma_zone_t pdptzone;
203#endif
204
205/*
206 * Data for the pv entry allocation mechanism
207 */
208static uma_zone_t pvzone;
209static struct vm_object pvzone_obj;
210static int pv_entry_count = 0, pv_entry_max = 0, pv_entry_high_water = 0;
211int pmap_pagedaemon_waken;
212
213/*
214 * All those kernel PT submaps that BSD is so fond of
215 */
216struct sysmaps {
217	struct	mtx lock;
218	pt_entry_t *CMAP1;
219	pt_entry_t *CMAP2;
220	caddr_t	CADDR1;
221	caddr_t	CADDR2;
222};
223static struct sysmaps sysmaps_pcpu[MAXCPU];
224pt_entry_t *CMAP1 = 0;
225static pt_entry_t *CMAP3;
226caddr_t CADDR1 = 0, ptvmmap = 0;
227static caddr_t CADDR3;
228struct msgbuf *msgbufp = 0;
229
230/*
231 * Crashdump maps.
232 */
233static caddr_t crashdumpmap;
234
235#ifdef SMP
236extern pt_entry_t *SMPpt;
237#endif
238static pt_entry_t *PMAP1 = 0, *PMAP2;
239static pt_entry_t *PADDR1 = 0, *PADDR2;
240#ifdef SMP
241static int PMAP1cpu;
242static int PMAP1changedcpu;
243SYSCTL_INT(_debug, OID_AUTO, PMAP1changedcpu, CTLFLAG_RD,
244	   &PMAP1changedcpu, 0,
245	   "Number of times pmap_pte_quick changed CPU with same PMAP1");
246#endif
247static int PMAP1changed;
248SYSCTL_INT(_debug, OID_AUTO, PMAP1changed, CTLFLAG_RD,
249	   &PMAP1changed, 0,
250	   "Number of times pmap_pte_quick changed PMAP1");
251static int PMAP1unchanged;
252SYSCTL_INT(_debug, OID_AUTO, PMAP1unchanged, CTLFLAG_RD,
253	   &PMAP1unchanged, 0,
254	   "Number of times pmap_pte_quick didn't change PMAP1");
255static struct mtx PMAP2mutex;
256
257static PMAP_INLINE void	free_pv_entry(pv_entry_t pv);
258static pv_entry_t get_pv_entry(void);
259static pv_entry_t pv_entry_reclaim(pmap_t locked_pmap);
260static void	pmap_clear_ptes(vm_page_t m, int bit);
261
262static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva);
263static void pmap_remove_page(struct pmap *pmap, vm_offset_t va);
264static void pmap_remove_entry(struct pmap *pmap, vm_page_t m,
265					vm_offset_t va);
266static void pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t m);
267
268static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va, int flags);
269
270static vm_page_t _pmap_allocpte(pmap_t pmap, unsigned ptepindex, int flags);
271static int _pmap_unwire_pte_hold(pmap_t pmap, vm_page_t m);
272static pt_entry_t *pmap_pte_quick(pmap_t pmap, vm_offset_t va);
273static void pmap_pte_release(pt_entry_t *pte);
274static int pmap_unuse_pt(pmap_t, vm_offset_t);
275static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
276#ifdef PAE
277static void *pmap_pdpt_allocf(uma_zone_t zone, int bytes, u_int8_t *flags, int wait);
278#endif
279
280CTASSERT(1 << PDESHIFT == sizeof(pd_entry_t));
281CTASSERT(1 << PTESHIFT == sizeof(pt_entry_t));
282
283/*
284 * Move the kernel virtual free pointer to the next
285 * 4MB.  This is used to help improve performance
286 * by using a large (4MB) page for much of the kernel
287 * (.text, .data, .bss)
288 */
289static vm_offset_t
290pmap_kmem_choose(vm_offset_t addr)
291{
292	vm_offset_t newaddr = addr;
293
294#ifndef DISABLE_PSE
295	if (cpu_feature & CPUID_PSE)
296		newaddr = (addr + PDRMASK) & ~PDRMASK;
297#endif
298	return newaddr;
299}
300
301/*
302 *	Bootstrap the system enough to run with virtual memory.
303 *
304 *	On the i386 this is called after mapping has already been enabled
305 *	and just syncs the pmap module with what has already been done.
306 *	[We can't call it easily with mapping off since the kernel is not
307 *	mapped with PA == VA, hence we would have to relocate every address
308 *	from the linked base (virtual) address "KERNBASE" to the actual
309 *	(physical) address starting relative to 0]
310 */
311void
312pmap_bootstrap(firstaddr, loadaddr)
313	vm_paddr_t firstaddr;
314	vm_paddr_t loadaddr;
315{
316	vm_offset_t va;
317	pt_entry_t *pte, *unused;
318	struct sysmaps *sysmaps;
319	int i;
320
321	/*
322	 * XXX The calculation of virtual_avail is wrong. It's NKPT*PAGE_SIZE too
323	 * large. It should instead be correctly calculated in locore.s and
324	 * not based on 'first' (which is a physical address, not a virtual
325	 * address, for the start of unused physical memory). The kernel
326	 * page tables are NOT double mapped and thus should not be included
327	 * in this calculation.
328	 */
329	virtual_avail = (vm_offset_t) KERNBASE + firstaddr;
330	virtual_avail = pmap_kmem_choose(virtual_avail);
331
332	virtual_end = VM_MAX_KERNEL_ADDRESS;
333
334	/*
335	 * Initialize the kernel pmap (which is statically allocated).
336	 */
337	PMAP_LOCK_INIT(kernel_pmap);
338	kernel_pmap->pm_pdir = (pd_entry_t *) (KERNBASE + (u_int)IdlePTD);
339#ifdef PAE
340	kernel_pmap->pm_pdpt = (pdpt_entry_t *) (KERNBASE + (u_int)IdlePDPT);
341#endif
342	kernel_pmap->pm_active = -1;	/* don't allow deactivation */
343	TAILQ_INIT(&kernel_pmap->pm_pvlist);
344	LIST_INIT(&allpmaps);
345	mtx_init(&allpmaps_lock, "allpmaps", NULL, MTX_SPIN);
346	mtx_lock_spin(&allpmaps_lock);
347	LIST_INSERT_HEAD(&allpmaps, kernel_pmap, pm_list);
348	mtx_unlock_spin(&allpmaps_lock);
349	nkpt = NKPT;
350
351	/*
352	 * Reserve some special page table entries/VA space for temporary
353	 * mapping of pages.
354	 */
355#define	SYSMAP(c, p, v, n)	\
356	v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
357
358	va = virtual_avail;
359	pte = vtopte(va);
360
361	/*
362	 * CMAP1/CMAP2 are used for zeroing and copying pages.
363	 * CMAP3 is used for the idle process page zeroing.
364	 */
365	for (i = 0; i < MAXCPU; i++) {
366		sysmaps = &sysmaps_pcpu[i];
367		mtx_init(&sysmaps->lock, "SYSMAPS", NULL, MTX_DEF);
368		SYSMAP(caddr_t, sysmaps->CMAP1, sysmaps->CADDR1, 1)
369		SYSMAP(caddr_t, sysmaps->CMAP2, sysmaps->CADDR2, 1)
370	}
371	SYSMAP(caddr_t, CMAP1, CADDR1, 1)
372	SYSMAP(caddr_t, CMAP3, CADDR3, 1)
373	*CMAP3 = 0;
374
375	/*
376	 * Crashdump maps.
377	 */
378	SYSMAP(caddr_t, unused, crashdumpmap, MAXDUMPPGS)
379
380	/*
381	 * ptvmmap is used for reading arbitrary physical pages via /dev/mem.
382	 */
383	SYSMAP(caddr_t, unused, ptvmmap, 1)
384
385	/*
386	 * msgbufp is used to map the system message buffer.
387	 */
388	SYSMAP(struct msgbuf *, unused, msgbufp, atop(round_page(MSGBUF_SIZE)))
389
390	/*
391	 * ptemap is used for pmap_pte_quick
392	 */
393	SYSMAP(pt_entry_t *, PMAP1, PADDR1, 1);
394	SYSMAP(pt_entry_t *, PMAP2, PADDR2, 1);
395
396	mtx_init(&PMAP2mutex, "PMAP2", NULL, MTX_DEF);
397
398	virtual_avail = va;
399
400	*CMAP1 = 0;
401
402#ifdef XBOX
403	/* FIXME: This is gross, but needed for the XBOX. Since we are in such
404	 * an early stadium, we cannot yet neatly map video memory ... :-(
405	 * Better fixes are very welcome! */
406	if (!arch_i386_is_xbox)
407#endif
408	for (i = 0; i < NKPT; i++)
409		PTD[i] = 0;
410
411	/* Turn on PG_G on kernel page(s) */
412	pmap_set_pg();
413}
414
415/*
416 * Set PG_G on kernel pages.  Only the BSP calls this when SMP is turned on.
417 */
418void
419pmap_set_pg(void)
420{
421	pd_entry_t pdir;
422	pt_entry_t *pte;
423	vm_offset_t va, endva;
424	int i;
425
426	if (pgeflag == 0)
427		return;
428
429	i = KERNLOAD/NBPDR;
430	endva = KERNBASE + KERNend;
431
432	if (pseflag) {
433		va = KERNBASE + KERNLOAD;
434		while (va  < endva) {
435			pdir = kernel_pmap->pm_pdir[KPTDI+i];
436			pdir |= pgeflag;
437			kernel_pmap->pm_pdir[KPTDI+i] = PTD[KPTDI+i] = pdir;
438			invltlb();	/* Play it safe, invltlb() every time */
439			i++;
440			va += NBPDR;
441		}
442	} else {
443		va = (vm_offset_t)btext;
444		while (va < endva) {
445			pte = vtopte(va);
446			if (*pte)
447				*pte |= pgeflag;
448			invltlb();	/* Play it safe, invltlb() every time */
449			va += PAGE_SIZE;
450		}
451	}
452}
453
454/*
455 * Initialize a vm_page's machine-dependent fields.
456 */
457void
458pmap_page_init(vm_page_t m)
459{
460
461	TAILQ_INIT(&m->md.pv_list);
462	m->md.pv_list_count = 0;
463}
464
465#ifdef PAE
466
467static MALLOC_DEFINE(M_PMAPPDPT, "pmap", "pmap pdpt");
468
469static void *
470pmap_pdpt_allocf(uma_zone_t zone, int bytes, u_int8_t *flags, int wait)
471{
472	*flags = UMA_SLAB_PRIV;
473	return (contigmalloc(PAGE_SIZE, M_PMAPPDPT, 0, 0x0ULL, 0xffffffffULL,
474	    1, 0));
475}
476#endif
477
478/*
479 *	Initialize the pmap module.
480 *	Called by vm_init, to initialize any structures that the pmap
481 *	system needs to map virtual memory.
482 */
483void
484pmap_init(void)
485{
486	int shpgperproc = PMAP_SHPGPERPROC;
487
488	/*
489	 * Initialize the address space (zone) for the pv entries.  Set a
490	 * high water mark so that the system can recover from excessive
491	 * numbers of pv entries.
492	 */
493	pvzone = uma_zcreate("PV ENTRY", sizeof(struct pv_entry), NULL, NULL,
494	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_VM | UMA_ZONE_NOFREE);
495	TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
496	pv_entry_max = shpgperproc * maxproc + cnt.v_page_count;
497	TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
498	pv_entry_high_water = 9 * (pv_entry_max / 10);
499	uma_zone_set_obj(pvzone, &pvzone_obj, pv_entry_max);
500
501#ifdef PAE
502	pdptzone = uma_zcreate("PDPT", NPGPTD * sizeof(pdpt_entry_t), NULL,
503	    NULL, NULL, NULL, (NPGPTD * sizeof(pdpt_entry_t)) - 1,
504	    UMA_ZONE_VM | UMA_ZONE_NOFREE);
505	uma_zone_set_allocf(pdptzone, pmap_pdpt_allocf);
506#endif
507}
508
509void
510pmap_init2()
511{
512}
513
514
515/***************************************************
516 * Low level helper routines.....
517 ***************************************************/
518
519
520/*
521 * this routine defines the region(s) of memory that should
522 * not be tested for the modified bit.
523 */
524static PMAP_INLINE int
525pmap_track_modified(vm_offset_t va)
526{
527	if ((va < kmi.clean_sva) || (va >= kmi.clean_eva))
528		return 1;
529	else
530		return 0;
531}
532
533#ifdef SMP
534/*
535 * For SMP, these functions have to use the IPI mechanism for coherence.
536 */
537void
538pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
539{
540	u_int cpumask;
541	u_int other_cpus;
542
543	if (smp_started) {
544		if (!(read_eflags() & PSL_I))
545			panic("%s: interrupts disabled", __func__);
546		mtx_lock_spin(&smp_ipi_mtx);
547	} else
548		critical_enter();
549	/*
550	 * We need to disable interrupt preemption but MUST NOT have
551	 * interrupts disabled here.
552	 * XXX we may need to hold schedlock to get a coherent pm_active
553	 * XXX critical sections disable interrupts again
554	 */
555	if (pmap == kernel_pmap || pmap->pm_active == all_cpus) {
556		invlpg(va);
557		smp_invlpg(va);
558	} else {
559		cpumask = PCPU_GET(cpumask);
560		other_cpus = PCPU_GET(other_cpus);
561		if (pmap->pm_active & cpumask)
562			invlpg(va);
563		if (pmap->pm_active & other_cpus)
564			smp_masked_invlpg(pmap->pm_active & other_cpus, va);
565	}
566	if (smp_started)
567		mtx_unlock_spin(&smp_ipi_mtx);
568	else
569		critical_exit();
570}
571
572void
573pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
574{
575	u_int cpumask;
576	u_int other_cpus;
577	vm_offset_t addr;
578
579	if (smp_started) {
580		if (!(read_eflags() & PSL_I))
581			panic("%s: interrupts disabled", __func__);
582		mtx_lock_spin(&smp_ipi_mtx);
583	} else
584		critical_enter();
585	/*
586	 * We need to disable interrupt preemption but MUST NOT have
587	 * interrupts disabled here.
588	 * XXX we may need to hold schedlock to get a coherent pm_active
589	 * XXX critical sections disable interrupts again
590	 */
591	if (pmap == kernel_pmap || pmap->pm_active == all_cpus) {
592		for (addr = sva; addr < eva; addr += PAGE_SIZE)
593			invlpg(addr);
594		smp_invlpg_range(sva, eva);
595	} else {
596		cpumask = PCPU_GET(cpumask);
597		other_cpus = PCPU_GET(other_cpus);
598		if (pmap->pm_active & cpumask)
599			for (addr = sva; addr < eva; addr += PAGE_SIZE)
600				invlpg(addr);
601		if (pmap->pm_active & other_cpus)
602			smp_masked_invlpg_range(pmap->pm_active & other_cpus,
603			    sva, eva);
604	}
605	if (smp_started)
606		mtx_unlock_spin(&smp_ipi_mtx);
607	else
608		critical_exit();
609}
610
611void
612pmap_invalidate_all(pmap_t pmap)
613{
614	u_int cpumask;
615	u_int other_cpus;
616
617	if (smp_started) {
618		if (!(read_eflags() & PSL_I))
619			panic("%s: interrupts disabled", __func__);
620		mtx_lock_spin(&smp_ipi_mtx);
621	} else
622		critical_enter();
623	/*
624	 * We need to disable interrupt preemption but MUST NOT have
625	 * interrupts disabled here.
626	 * XXX we may need to hold schedlock to get a coherent pm_active
627	 * XXX critical sections disable interrupts again
628	 */
629	if (pmap == kernel_pmap || pmap->pm_active == all_cpus) {
630		invltlb();
631		smp_invltlb();
632	} else {
633		cpumask = PCPU_GET(cpumask);
634		other_cpus = PCPU_GET(other_cpus);
635		if (pmap->pm_active & cpumask)
636			invltlb();
637		if (pmap->pm_active & other_cpus)
638			smp_masked_invltlb(pmap->pm_active & other_cpus);
639	}
640	if (smp_started)
641		mtx_unlock_spin(&smp_ipi_mtx);
642	else
643		critical_exit();
644}
645#else /* !SMP */
646/*
647 * Normal, non-SMP, 486+ invalidation functions.
648 * We inline these within pmap.c for speed.
649 */
650PMAP_INLINE void
651pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
652{
653
654	if (pmap == kernel_pmap || pmap->pm_active)
655		invlpg(va);
656}
657
658PMAP_INLINE void
659pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
660{
661	vm_offset_t addr;
662
663	if (pmap == kernel_pmap || pmap->pm_active)
664		for (addr = sva; addr < eva; addr += PAGE_SIZE)
665			invlpg(addr);
666}
667
668PMAP_INLINE void
669pmap_invalidate_all(pmap_t pmap)
670{
671
672	if (pmap == kernel_pmap || pmap->pm_active)
673		invltlb();
674}
675#endif /* !SMP */
676
677/*
678 * Are we current address space or kernel?  N.B. We return FALSE when
679 * a pmap's page table is in use because a kernel thread is borrowing
680 * it.  The borrowed page table can change spontaneously, making any
681 * dependence on its continued use subject to a race condition.
682 */
683static __inline int
684pmap_is_current(pmap_t pmap)
685{
686
687	return (pmap == kernel_pmap ||
688		(pmap == vmspace_pmap(curthread->td_proc->p_vmspace) &&
689	    (pmap->pm_pdir[PTDPTDI] & PG_FRAME) == (PTDpde[0] & PG_FRAME)));
690}
691
692/*
693 * If the given pmap is not the current or kernel pmap, the returned pte must
694 * be released by passing it to pmap_pte_release().
695 */
696pt_entry_t *
697pmap_pte(pmap_t pmap, vm_offset_t va)
698{
699	pd_entry_t newpf;
700	pd_entry_t *pde;
701
702	pde = pmap_pde(pmap, va);
703	if (*pde & PG_PS)
704		return (pde);
705	if (*pde != 0) {
706		/* are we current address space or kernel? */
707		if (pmap_is_current(pmap))
708			return (vtopte(va));
709		mtx_lock(&PMAP2mutex);
710		newpf = *pde & PG_FRAME;
711		if ((*PMAP2 & PG_FRAME) != newpf) {
712			*PMAP2 = newpf | PG_RW | PG_V | PG_A | PG_M;
713			pmap_invalidate_page(kernel_pmap, (vm_offset_t)PADDR2);
714		}
715		return (PADDR2 + (i386_btop(va) & (NPTEPG - 1)));
716	}
717	return (0);
718}
719
720/*
721 * Releases a pte that was obtained from pmap_pte().  Be prepared for the pte
722 * being NULL.
723 */
724static __inline void
725pmap_pte_release(pt_entry_t *pte)
726{
727
728	if ((pt_entry_t *)((vm_offset_t)pte & ~PAGE_MASK) == PADDR2)
729		mtx_unlock(&PMAP2mutex);
730}
731
732static __inline void
733invlcaddr(void *caddr)
734{
735
736	invlpg((u_int)caddr);
737}
738
739/*
740 * Super fast pmap_pte routine best used when scanning
741 * the pv lists.  This eliminates many coarse-grained
742 * invltlb calls.  Note that many of the pv list
743 * scans are across different pmaps.  It is very wasteful
744 * to do an entire invltlb for checking a single mapping.
745 *
746 * If the given pmap is not the current pmap, vm_page_queue_mtx
747 * must be held and curthread pinned to a CPU.
748 */
749static pt_entry_t *
750pmap_pte_quick(pmap_t pmap, vm_offset_t va)
751{
752	pd_entry_t newpf;
753	pd_entry_t *pde;
754
755	pde = pmap_pde(pmap, va);
756	if (*pde & PG_PS)
757		return (pde);
758	if (*pde != 0) {
759		/* are we current address space or kernel? */
760		if (pmap_is_current(pmap))
761			return (vtopte(va));
762		mtx_assert(&vm_page_queue_mtx, MA_OWNED);
763		KASSERT(curthread->td_pinned > 0, ("curthread not pinned"));
764		newpf = *pde & PG_FRAME;
765		if ((*PMAP1 & PG_FRAME) != newpf) {
766			*PMAP1 = newpf | PG_RW | PG_V | PG_A | PG_M;
767#ifdef SMP
768			PMAP1cpu = PCPU_GET(cpuid);
769#endif
770			invlcaddr(PADDR1);
771			PMAP1changed++;
772		} else
773#ifdef SMP
774		if (PMAP1cpu != PCPU_GET(cpuid)) {
775			PMAP1cpu = PCPU_GET(cpuid);
776			invlcaddr(PADDR1);
777			PMAP1changedcpu++;
778		} else
779#endif
780			PMAP1unchanged++;
781		return (PADDR1 + (i386_btop(va) & (NPTEPG - 1)));
782	}
783	return (0);
784}
785
786/*
787 *	Routine:	pmap_extract
788 *	Function:
789 *		Extract the physical page address associated
790 *		with the given map/virtual_address pair.
791 */
792vm_paddr_t
793pmap_extract(pmap_t pmap, vm_offset_t va)
794{
795	vm_paddr_t rtval;
796	pt_entry_t *pte;
797	pd_entry_t pde;
798
799	rtval = 0;
800	PMAP_LOCK(pmap);
801	pde = pmap->pm_pdir[va >> PDRSHIFT];
802	if (pde != 0) {
803		if ((pde & PG_PS) != 0) {
804			rtval = (pde & ~PDRMASK) | (va & PDRMASK);
805			PMAP_UNLOCK(pmap);
806			return rtval;
807		}
808		pte = pmap_pte(pmap, va);
809		rtval = (*pte & PG_FRAME) | (va & PAGE_MASK);
810		pmap_pte_release(pte);
811	}
812	PMAP_UNLOCK(pmap);
813	return (rtval);
814}
815
816/*
817 *	Routine:	pmap_extract_and_hold
818 *	Function:
819 *		Atomically extract and hold the physical page
820 *		with the given pmap and virtual address pair
821 *		if that mapping permits the given protection.
822 */
823vm_page_t
824pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
825{
826	pd_entry_t pde;
827	pt_entry_t pte;
828	vm_page_t m;
829
830	m = NULL;
831	vm_page_lock_queues();
832	PMAP_LOCK(pmap);
833	pde = *pmap_pde(pmap, va);
834	if (pde != 0) {
835		if (pde & PG_PS) {
836			if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
837				m = PHYS_TO_VM_PAGE((pde & ~PDRMASK) |
838				    (va & PDRMASK));
839				vm_page_hold(m);
840			}
841		} else {
842			sched_pin();
843			pte = *pmap_pte_quick(pmap, va);
844			if (pte != 0 &&
845			    ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
846				m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
847				vm_page_hold(m);
848			}
849			sched_unpin();
850		}
851	}
852	vm_page_unlock_queues();
853	PMAP_UNLOCK(pmap);
854	return (m);
855}
856
857/***************************************************
858 * Low level mapping routines.....
859 ***************************************************/
860
861/*
862 * Add a wired page to the kva.
863 * Note: not SMP coherent.
864 */
865PMAP_INLINE void
866pmap_kenter(vm_offset_t va, vm_paddr_t pa)
867{
868	pt_entry_t *pte;
869
870	pte = vtopte(va);
871	pte_store(pte, pa | PG_RW | PG_V | pgeflag);
872}
873
874/*
875 * Remove a page from the kernel pagetables.
876 * Note: not SMP coherent.
877 */
878PMAP_INLINE void
879pmap_kremove(vm_offset_t va)
880{
881	pt_entry_t *pte;
882
883	pte = vtopte(va);
884	pte_clear(pte);
885}
886
887/*
888 *	Used to map a range of physical addresses into kernel
889 *	virtual address space.
890 *
891 *	The value passed in '*virt' is a suggested virtual address for
892 *	the mapping. Architectures which can support a direct-mapped
893 *	physical to virtual region can return the appropriate address
894 *	within that region, leaving '*virt' unchanged. Other
895 *	architectures should map the pages starting at '*virt' and
896 *	update '*virt' with the first usable address after the mapped
897 *	region.
898 */
899vm_offset_t
900pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
901{
902	vm_offset_t va, sva;
903
904	va = sva = *virt;
905	while (start < end) {
906		pmap_kenter(va, start);
907		va += PAGE_SIZE;
908		start += PAGE_SIZE;
909	}
910	pmap_invalidate_range(kernel_pmap, sva, va);
911	*virt = va;
912	return (sva);
913}
914
915
916/*
917 * Add a list of wired pages to the kva
918 * this routine is only used for temporary
919 * kernel mappings that do not need to have
920 * page modification or references recorded.
921 * Note that old mappings are simply written
922 * over.  The page *must* be wired.
923 * Note: SMP coherent.  Uses a ranged shootdown IPI.
924 */
925void
926pmap_qenter(vm_offset_t sva, vm_page_t *m, int count)
927{
928	vm_offset_t va;
929
930	va = sva;
931	while (count-- > 0) {
932		pmap_kenter(va, VM_PAGE_TO_PHYS(*m));
933		va += PAGE_SIZE;
934		m++;
935	}
936	pmap_invalidate_range(kernel_pmap, sva, va);
937}
938
939/*
940 * This routine tears out page mappings from the
941 * kernel -- it is meant only for temporary mappings.
942 * Note: SMP coherent.  Uses a ranged shootdown IPI.
943 */
944void
945pmap_qremove(vm_offset_t sva, int count)
946{
947	vm_offset_t va;
948
949	va = sva;
950	while (count-- > 0) {
951		pmap_kremove(va);
952		va += PAGE_SIZE;
953	}
954	pmap_invalidate_range(kernel_pmap, sva, va);
955}
956
957/***************************************************
958 * Page table page management routines.....
959 ***************************************************/
960
961/*
962 * This routine unholds page table pages, and if the hold count
963 * drops to zero, then it decrements the wire count.
964 */
965static PMAP_INLINE int
966pmap_unwire_pte_hold(pmap_t pmap, vm_page_t m)
967{
968
969	--m->wire_count;
970	if (m->wire_count == 0)
971		return _pmap_unwire_pte_hold(pmap, m);
972	else
973		return 0;
974}
975
976static int
977_pmap_unwire_pte_hold(pmap_t pmap, vm_page_t m)
978{
979	vm_offset_t pteva;
980
981	/*
982	 * unmap the page table page
983	 */
984	pmap->pm_pdir[m->pindex] = 0;
985	--pmap->pm_stats.resident_count;
986
987	/*
988	 * Do an invltlb to make the invalidated mapping
989	 * take effect immediately.
990	 */
991	pteva = VM_MAXUSER_ADDRESS + i386_ptob(m->pindex);
992	pmap_invalidate_page(pmap, pteva);
993
994	vm_page_free_zero(m);
995	atomic_subtract_int(&cnt.v_wire_count, 1);
996	return 1;
997}
998
999/*
1000 * After removing a page table entry, this routine is used to
1001 * conditionally free the page, and manage the hold/wire counts.
1002 */
1003static int
1004pmap_unuse_pt(pmap_t pmap, vm_offset_t va)
1005{
1006	pd_entry_t ptepde;
1007	vm_page_t mpte;
1008
1009	if (va >= VM_MAXUSER_ADDRESS)
1010		return 0;
1011	ptepde = *pmap_pde(pmap, va);
1012	mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
1013	return pmap_unwire_pte_hold(pmap, mpte);
1014}
1015
1016void
1017pmap_pinit0(pmap)
1018	struct pmap *pmap;
1019{
1020
1021	PMAP_LOCK_INIT(pmap);
1022	pmap->pm_pdir = (pd_entry_t *)(KERNBASE + (vm_offset_t)IdlePTD);
1023#ifdef PAE
1024	pmap->pm_pdpt = (pdpt_entry_t *)(KERNBASE + (vm_offset_t)IdlePDPT);
1025#endif
1026	pmap->pm_active = 0;
1027	PCPU_SET(curpmap, pmap);
1028	TAILQ_INIT(&pmap->pm_pvlist);
1029	bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1030	mtx_lock_spin(&allpmaps_lock);
1031	LIST_INSERT_HEAD(&allpmaps, pmap, pm_list);
1032	mtx_unlock_spin(&allpmaps_lock);
1033}
1034
1035/*
1036 * Initialize a preallocated and zeroed pmap structure,
1037 * such as one in a vmspace structure.
1038 */
1039void
1040pmap_pinit(pmap)
1041	register struct pmap *pmap;
1042{
1043	vm_page_t m, ptdpg[NPGPTD];
1044	vm_paddr_t pa;
1045	static int color;
1046	int i;
1047
1048	PMAP_LOCK_INIT(pmap);
1049
1050	/*
1051	 * No need to allocate page table space yet but we do need a valid
1052	 * page directory table.
1053	 */
1054	if (pmap->pm_pdir == NULL) {
1055		pmap->pm_pdir = (pd_entry_t *)kmem_alloc_nofault(kernel_map,
1056		    NBPTD);
1057#ifdef PAE
1058		pmap->pm_pdpt = uma_zalloc(pdptzone, M_WAITOK | M_ZERO);
1059		KASSERT(((vm_offset_t)pmap->pm_pdpt &
1060		    ((NPGPTD * sizeof(pdpt_entry_t)) - 1)) == 0,
1061		    ("pmap_pinit: pdpt misaligned"));
1062		KASSERT(pmap_kextract((vm_offset_t)pmap->pm_pdpt) < (4ULL<<30),
1063		    ("pmap_pinit: pdpt above 4g"));
1064#endif
1065	}
1066
1067	/*
1068	 * allocate the page directory page(s)
1069	 */
1070	for (i = 0; i < NPGPTD;) {
1071		m = vm_page_alloc(NULL, color++,
1072		    VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
1073		    VM_ALLOC_ZERO);
1074		if (m == NULL)
1075			VM_WAIT;
1076		else {
1077			ptdpg[i++] = m;
1078		}
1079	}
1080
1081	pmap_qenter((vm_offset_t)pmap->pm_pdir, ptdpg, NPGPTD);
1082
1083	for (i = 0; i < NPGPTD; i++) {
1084		if ((ptdpg[i]->flags & PG_ZERO) == 0)
1085			bzero(pmap->pm_pdir + (i * NPDEPG), PAGE_SIZE);
1086	}
1087
1088	mtx_lock_spin(&allpmaps_lock);
1089	LIST_INSERT_HEAD(&allpmaps, pmap, pm_list);
1090	mtx_unlock_spin(&allpmaps_lock);
1091	/* Wire in kernel global address entries. */
1092	/* XXX copies current process, does not fill in MPPTDI */
1093	bcopy(PTD + KPTDI, pmap->pm_pdir + KPTDI, nkpt * sizeof(pd_entry_t));
1094#ifdef SMP
1095	pmap->pm_pdir[MPPTDI] = PTD[MPPTDI];
1096#endif
1097
1098	/* install self-referential address mapping entry(s) */
1099	for (i = 0; i < NPGPTD; i++) {
1100		pa = VM_PAGE_TO_PHYS(ptdpg[i]);
1101		pmap->pm_pdir[PTDPTDI + i] = pa | PG_V | PG_RW | PG_A | PG_M;
1102#ifdef PAE
1103		pmap->pm_pdpt[i] = pa | PG_V;
1104#endif
1105	}
1106
1107	pmap->pm_active = 0;
1108	TAILQ_INIT(&pmap->pm_pvlist);
1109	bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1110}
1111
1112/*
1113 * this routine is called if the page table page is not
1114 * mapped correctly.
1115 */
1116static vm_page_t
1117_pmap_allocpte(pmap_t pmap, unsigned ptepindex, int flags)
1118{
1119	vm_paddr_t ptepa;
1120	vm_page_t m;
1121
1122	KASSERT((flags & (M_NOWAIT | M_WAITOK)) == M_NOWAIT ||
1123	    (flags & (M_NOWAIT | M_WAITOK)) == M_WAITOK,
1124	    ("_pmap_allocpte: flags is neither M_NOWAIT nor M_WAITOK"));
1125
1126	/*
1127	 * Allocate a page table page.
1128	 */
1129	if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
1130	    VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
1131		if (flags & M_WAITOK) {
1132			PMAP_UNLOCK(pmap);
1133			vm_page_unlock_queues();
1134			VM_WAIT;
1135			vm_page_lock_queues();
1136			PMAP_LOCK(pmap);
1137		}
1138
1139		/*
1140		 * Indicate the need to retry.  While waiting, the page table
1141		 * page may have been allocated.
1142		 */
1143		return (NULL);
1144	}
1145	if ((m->flags & PG_ZERO) == 0)
1146		pmap_zero_page(m);
1147
1148	/*
1149	 * Map the pagetable page into the process address space, if
1150	 * it isn't already there.
1151	 */
1152
1153	pmap->pm_stats.resident_count++;
1154
1155	ptepa = VM_PAGE_TO_PHYS(m);
1156	pmap->pm_pdir[ptepindex] =
1157		(pd_entry_t) (ptepa | PG_U | PG_RW | PG_V | PG_A | PG_M);
1158
1159	return m;
1160}
1161
1162static vm_page_t
1163pmap_allocpte(pmap_t pmap, vm_offset_t va, int flags)
1164{
1165	unsigned ptepindex;
1166	pd_entry_t ptepa;
1167	vm_page_t m;
1168
1169	KASSERT((flags & (M_NOWAIT | M_WAITOK)) == M_NOWAIT ||
1170	    (flags & (M_NOWAIT | M_WAITOK)) == M_WAITOK,
1171	    ("pmap_allocpte: flags is neither M_NOWAIT nor M_WAITOK"));
1172
1173	/*
1174	 * Calculate pagetable page index
1175	 */
1176	ptepindex = va >> PDRSHIFT;
1177retry:
1178	/*
1179	 * Get the page directory entry
1180	 */
1181	ptepa = pmap->pm_pdir[ptepindex];
1182
1183	/*
1184	 * This supports switching from a 4MB page to a
1185	 * normal 4K page.
1186	 */
1187	if (ptepa & PG_PS) {
1188		pmap->pm_pdir[ptepindex] = 0;
1189		ptepa = 0;
1190		pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
1191		pmap_invalidate_all(kernel_pmap);
1192	}
1193
1194	/*
1195	 * If the page table page is mapped, we just increment the
1196	 * hold count, and activate it.
1197	 */
1198	if (ptepa) {
1199		m = PHYS_TO_VM_PAGE(ptepa);
1200		m->wire_count++;
1201	} else {
1202		/*
1203		 * Here if the pte page isn't mapped, or if it has
1204		 * been deallocated.
1205		 */
1206		m = _pmap_allocpte(pmap, ptepindex, flags);
1207		if (m == NULL && (flags & M_WAITOK))
1208			goto retry;
1209	}
1210	return (m);
1211}
1212
1213
1214/***************************************************
1215* Pmap allocation/deallocation routines.
1216 ***************************************************/
1217
1218#ifdef SMP
1219/*
1220 * Deal with a SMP shootdown of other users of the pmap that we are
1221 * trying to dispose of.  This can be a bit hairy.
1222 */
1223static u_int *lazymask;
1224static u_int lazyptd;
1225static volatile u_int lazywait;
1226
1227void pmap_lazyfix_action(void);
1228
1229void
1230pmap_lazyfix_action(void)
1231{
1232	u_int mymask = PCPU_GET(cpumask);
1233
1234	if (rcr3() == lazyptd)
1235		load_cr3(PCPU_GET(curpcb)->pcb_cr3);
1236	atomic_clear_int(lazymask, mymask);
1237	atomic_store_rel_int(&lazywait, 1);
1238}
1239
1240static void
1241pmap_lazyfix_self(u_int mymask)
1242{
1243
1244	if (rcr3() == lazyptd)
1245		load_cr3(PCPU_GET(curpcb)->pcb_cr3);
1246	atomic_clear_int(lazymask, mymask);
1247}
1248
1249
1250static void
1251pmap_lazyfix(pmap_t pmap)
1252{
1253	u_int mymask;
1254	u_int mask;
1255	register u_int spins;
1256
1257	while ((mask = pmap->pm_active) != 0) {
1258		spins = 50000000;
1259		mask = mask & -mask;	/* Find least significant set bit */
1260		mtx_lock_spin(&smp_ipi_mtx);
1261#ifdef PAE
1262		lazyptd = vtophys(pmap->pm_pdpt);
1263#else
1264		lazyptd = vtophys(pmap->pm_pdir);
1265#endif
1266		mymask = PCPU_GET(cpumask);
1267		if (mask == mymask) {
1268			lazymask = &pmap->pm_active;
1269			pmap_lazyfix_self(mymask);
1270		} else {
1271			atomic_store_rel_int((u_int *)&lazymask,
1272			    (u_int)&pmap->pm_active);
1273			atomic_store_rel_int(&lazywait, 0);
1274			ipi_selected(mask, IPI_LAZYPMAP);
1275			while (lazywait == 0) {
1276				ia32_pause();
1277				if (--spins == 0)
1278					break;
1279			}
1280		}
1281		mtx_unlock_spin(&smp_ipi_mtx);
1282		if (spins == 0)
1283			printf("pmap_lazyfix: spun for 50000000\n");
1284	}
1285}
1286
1287#else	/* SMP */
1288
1289/*
1290 * Cleaning up on uniprocessor is easy.  For various reasons, we're
1291 * unlikely to have to even execute this code, including the fact
1292 * that the cleanup is deferred until the parent does a wait(2), which
1293 * means that another userland process has run.
1294 */
1295static void
1296pmap_lazyfix(pmap_t pmap)
1297{
1298	u_int cr3;
1299
1300	cr3 = vtophys(pmap->pm_pdir);
1301	if (cr3 == rcr3()) {
1302		load_cr3(PCPU_GET(curpcb)->pcb_cr3);
1303		pmap->pm_active &= ~(PCPU_GET(cpumask));
1304	}
1305}
1306#endif	/* SMP */
1307
1308/*
1309 * Release any resources held by the given physical map.
1310 * Called when a pmap initialized by pmap_pinit is being released.
1311 * Should only be called if the map contains no valid mappings.
1312 */
1313void
1314pmap_release(pmap_t pmap)
1315{
1316	vm_page_t m, ptdpg[NPGPTD];
1317	int i;
1318
1319	KASSERT(pmap->pm_stats.resident_count == 0,
1320	    ("pmap_release: pmap resident count %ld != 0",
1321	    pmap->pm_stats.resident_count));
1322
1323	pmap_lazyfix(pmap);
1324	mtx_lock_spin(&allpmaps_lock);
1325	LIST_REMOVE(pmap, pm_list);
1326	mtx_unlock_spin(&allpmaps_lock);
1327
1328	for (i = 0; i < NPGPTD; i++)
1329		ptdpg[i] = PHYS_TO_VM_PAGE(pmap->pm_pdir[PTDPTDI + i]);
1330
1331	bzero(pmap->pm_pdir + PTDPTDI, (nkpt + NPGPTD) *
1332	    sizeof(*pmap->pm_pdir));
1333#ifdef SMP
1334	pmap->pm_pdir[MPPTDI] = 0;
1335#endif
1336
1337	pmap_qremove((vm_offset_t)pmap->pm_pdir, NPGPTD);
1338
1339	vm_page_lock_queues();
1340	for (i = 0; i < NPGPTD; i++) {
1341		m = ptdpg[i];
1342#ifdef PAE
1343		KASSERT(VM_PAGE_TO_PHYS(m) == (pmap->pm_pdpt[i] & PG_FRAME),
1344		    ("pmap_release: got wrong ptd page"));
1345#endif
1346		m->wire_count--;
1347		atomic_subtract_int(&cnt.v_wire_count, 1);
1348		vm_page_free_zero(m);
1349	}
1350	vm_page_unlock_queues();
1351	PMAP_LOCK_DESTROY(pmap);
1352}
1353
1354static int
1355kvm_size(SYSCTL_HANDLER_ARGS)
1356{
1357	unsigned long ksize = VM_MAX_KERNEL_ADDRESS - KERNBASE;
1358
1359	return sysctl_handle_long(oidp, &ksize, 0, req);
1360}
1361SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
1362    0, 0, kvm_size, "IU", "Size of KVM");
1363
1364static int
1365kvm_free(SYSCTL_HANDLER_ARGS)
1366{
1367	unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
1368
1369	return sysctl_handle_long(oidp, &kfree, 0, req);
1370}
1371SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
1372    0, 0, kvm_free, "IU", "Amount of KVM free");
1373
1374/*
1375 * grow the number of kernel page table entries, if needed
1376 */
1377void
1378pmap_growkernel(vm_offset_t addr)
1379{
1380	struct pmap *pmap;
1381	vm_paddr_t ptppaddr;
1382	vm_page_t nkpg;
1383	pd_entry_t newpdir;
1384	pt_entry_t *pde;
1385
1386	mtx_assert(&kernel_map->system_mtx, MA_OWNED);
1387	if (kernel_vm_end == 0) {
1388		kernel_vm_end = KERNBASE;
1389		nkpt = 0;
1390		while (pdir_pde(PTD, kernel_vm_end)) {
1391			kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1392			nkpt++;
1393		}
1394	}
1395	addr = roundup2(addr, PAGE_SIZE * NPTEPG);
1396	while (kernel_vm_end < addr) {
1397		if (pdir_pde(PTD, kernel_vm_end)) {
1398			kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1399			continue;
1400		}
1401
1402		/*
1403		 * This index is bogus, but out of the way
1404		 */
1405		nkpg = vm_page_alloc(NULL, nkpt,
1406		    VM_ALLOC_NOOBJ | VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
1407		if (!nkpg)
1408			panic("pmap_growkernel: no memory to grow kernel");
1409
1410		nkpt++;
1411
1412		pmap_zero_page(nkpg);
1413		ptppaddr = VM_PAGE_TO_PHYS(nkpg);
1414		newpdir = (pd_entry_t) (ptppaddr | PG_V | PG_RW | PG_A | PG_M);
1415		pdir_pde(PTD, kernel_vm_end) = newpdir;
1416
1417		mtx_lock_spin(&allpmaps_lock);
1418		LIST_FOREACH(pmap, &allpmaps, pm_list) {
1419			pde = pmap_pde(pmap, kernel_vm_end);
1420			pde_store(pde, newpdir);
1421		}
1422		mtx_unlock_spin(&allpmaps_lock);
1423		kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1424	}
1425}
1426
1427
1428/***************************************************
1429 * page management routines.
1430 ***************************************************/
1431
1432/*
1433 * free the pv_entry back to the free list
1434 */
1435static PMAP_INLINE void
1436free_pv_entry(pv_entry_t pv)
1437{
1438	pv_entry_count--;
1439	uma_zfree(pvzone, pv);
1440}
1441
1442/*
1443 * get a new pv_entry, allocating a block from the system
1444 * when needed.
1445 * the memory allocation is performed bypassing the malloc code
1446 * because of the possibility of allocations at interrupt time.
1447 */
1448static pv_entry_t
1449get_pv_entry(void)
1450{
1451	pv_entry_count++;
1452	if ((pv_entry_count > pv_entry_high_water) &&
1453		(pmap_pagedaemon_waken == 0)) {
1454		pmap_pagedaemon_waken = 1;
1455		wakeup (&vm_pages_needed);
1456	}
1457	return uma_zalloc(pvzone, M_NOWAIT);
1458}
1459
1460/*
1461 * Reclaim a pv entry by removing a mapping to an inactive page.
1462 */
1463static pv_entry_t
1464pv_entry_reclaim(pmap_t locked_pmap)
1465{
1466	pmap_t pmap;
1467	pt_entry_t *pte, tpte;
1468	pv_entry_t pv;
1469	vm_offset_t va;
1470	vm_page_t m;
1471
1472	PMAP_LOCK_ASSERT(locked_pmap, MA_OWNED);
1473	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1474	sched_pin();
1475	TAILQ_FOREACH(m, &vm_page_queues[PQ_INACTIVE].pl, pageq) {
1476		if (m->hold_count || m->busy || (m->flags & PG_BUSY))
1477			continue;
1478		TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
1479			va = pv->pv_va;
1480			pmap = pv->pv_pmap;
1481			if (pmap != locked_pmap && !PMAP_TRYLOCK(pmap))
1482				continue;
1483			pmap->pm_stats.resident_count--;
1484			pte = pmap_pte_quick(pmap, va);
1485			tpte = pte_load_clear(pte);
1486			KASSERT((tpte & PG_W) == 0,
1487			    ("pv_entry_reclaim: wired pte %#jx",
1488			    (uintmax_t)tpte));
1489			if (tpte & PG_A)
1490				vm_page_flag_set(m, PG_REFERENCED);
1491			if (tpte & PG_M) {
1492				KASSERT((tpte & PG_RW),
1493	("pv_entry_reclaim: modified page not writable: va: %#x, pte: %#jx",
1494				    va, (uintmax_t)tpte));
1495				if (pmap_track_modified(va))
1496					vm_page_dirty(m);
1497			}
1498			pmap_invalidate_page(pmap, va);
1499			TAILQ_REMOVE(&pmap->pm_pvlist, pv, pv_plist);
1500			TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
1501			if (TAILQ_EMPTY(&m->md.pv_list))
1502				vm_page_flag_clear(m, PG_WRITEABLE);
1503			m->md.pv_list_count--;
1504			pmap_unuse_pt(pmap, va);
1505			if (pmap != locked_pmap)
1506				PMAP_UNLOCK(pmap);
1507			sched_unpin();
1508			return (pv);
1509		}
1510	}
1511	sched_unpin();
1512	panic("pv_entry_reclaim: increase vm.pmap.shpgperproc");
1513}
1514
1515static void
1516pmap_remove_entry(pmap_t pmap, vm_page_t m, vm_offset_t va)
1517{
1518	pv_entry_t pv;
1519
1520	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1521	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1522	if (m->md.pv_list_count < pmap->pm_stats.resident_count) {
1523		TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
1524			if (pmap == pv->pv_pmap && va == pv->pv_va)
1525				break;
1526		}
1527	} else {
1528		TAILQ_FOREACH(pv, &pmap->pm_pvlist, pv_plist) {
1529			if (va == pv->pv_va)
1530				break;
1531		}
1532	}
1533	KASSERT(pv != NULL, ("pmap_remove_entry: pv not found"));
1534	TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
1535	m->md.pv_list_count--;
1536	if (TAILQ_EMPTY(&m->md.pv_list))
1537		vm_page_flag_clear(m, PG_WRITEABLE);
1538	TAILQ_REMOVE(&pmap->pm_pvlist, pv, pv_plist);
1539	free_pv_entry(pv);
1540}
1541
1542/*
1543 * Create a pv entry for page at pa for
1544 * (pmap, va).
1545 */
1546static void
1547pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t m)
1548{
1549	pv_entry_t pv;
1550
1551	pv = get_pv_entry();
1552	if (pv == NULL) {
1553		pv_entry_count--;
1554		pv = pv_entry_reclaim(pmap);
1555	}
1556	pv->pv_va = va;
1557	pv->pv_pmap = pmap;
1558
1559	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1560	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1561	TAILQ_INSERT_TAIL(&pmap->pm_pvlist, pv, pv_plist);
1562	TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
1563	m->md.pv_list_count++;
1564}
1565
1566/*
1567 * pmap_remove_pte: do the things to unmap a page in a process
1568 */
1569static int
1570pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va)
1571{
1572	pt_entry_t oldpte;
1573	vm_page_t m;
1574
1575	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1576	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1577	oldpte = pte_load_clear(ptq);
1578	if (oldpte & PG_W)
1579		pmap->pm_stats.wired_count -= 1;
1580	/*
1581	 * Machines that don't support invlpg, also don't support
1582	 * PG_G.
1583	 */
1584	if (oldpte & PG_G)
1585		pmap_invalidate_page(kernel_pmap, va);
1586	pmap->pm_stats.resident_count -= 1;
1587	if (oldpte & PG_MANAGED) {
1588		m = PHYS_TO_VM_PAGE(oldpte);
1589		if (oldpte & PG_M) {
1590			KASSERT((oldpte & PG_RW),
1591	("pmap_remove_pte: modified page not writable: va: %#x, pte: %#jx",
1592			    va, (uintmax_t)oldpte));
1593			if (pmap_track_modified(va))
1594				vm_page_dirty(m);
1595		}
1596		if (oldpte & PG_A)
1597			vm_page_flag_set(m, PG_REFERENCED);
1598		pmap_remove_entry(pmap, m, va);
1599	}
1600	return (pmap_unuse_pt(pmap, va));
1601}
1602
1603/*
1604 * Remove a single page from a process address space
1605 */
1606static void
1607pmap_remove_page(pmap_t pmap, vm_offset_t va)
1608{
1609	pt_entry_t *pte;
1610
1611	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1612	KASSERT(curthread->td_pinned > 0, ("curthread not pinned"));
1613	PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1614	if ((pte = pmap_pte_quick(pmap, va)) == NULL || *pte == 0)
1615		return;
1616	pmap_remove_pte(pmap, pte, va);
1617	pmap_invalidate_page(pmap, va);
1618}
1619
1620/*
1621 *	Remove the given range of addresses from the specified map.
1622 *
1623 *	It is assumed that the start and end are properly
1624 *	rounded to the page size.
1625 */
1626void
1627pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1628{
1629	vm_offset_t pdnxt;
1630	pd_entry_t ptpaddr;
1631	pt_entry_t *pte;
1632	int anyvalid;
1633
1634	/*
1635	 * Perform an unsynchronized read.  This is, however, safe.
1636	 */
1637	if (pmap->pm_stats.resident_count == 0)
1638		return;
1639
1640	anyvalid = 0;
1641
1642	vm_page_lock_queues();
1643	sched_pin();
1644	PMAP_LOCK(pmap);
1645
1646	/*
1647	 * special handling of removing one page.  a very
1648	 * common operation and easy to short circuit some
1649	 * code.
1650	 */
1651	if ((sva + PAGE_SIZE == eva) &&
1652	    ((pmap->pm_pdir[(sva >> PDRSHIFT)] & PG_PS) == 0)) {
1653		pmap_remove_page(pmap, sva);
1654		goto out;
1655	}
1656
1657	for (; sva < eva; sva = pdnxt) {
1658		unsigned pdirindex;
1659
1660		/*
1661		 * Calculate index for next page table.
1662		 */
1663		pdnxt = (sva + NBPDR) & ~PDRMASK;
1664		if (pmap->pm_stats.resident_count == 0)
1665			break;
1666
1667		pdirindex = sva >> PDRSHIFT;
1668		ptpaddr = pmap->pm_pdir[pdirindex];
1669
1670		/*
1671		 * Weed out invalid mappings. Note: we assume that the page
1672		 * directory table is always allocated, and in kernel virtual.
1673		 */
1674		if (ptpaddr == 0)
1675			continue;
1676
1677		/*
1678		 * Check for large page.
1679		 */
1680		if ((ptpaddr & PG_PS) != 0) {
1681			pmap->pm_pdir[pdirindex] = 0;
1682			pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
1683			anyvalid = 1;
1684			continue;
1685		}
1686
1687		/*
1688		 * Limit our scan to either the end of the va represented
1689		 * by the current page table page, or to the end of the
1690		 * range being removed.
1691		 */
1692		if (pdnxt > eva)
1693			pdnxt = eva;
1694
1695		for (pte = pmap_pte_quick(pmap, sva); sva != pdnxt; pte++,
1696		    sva += PAGE_SIZE) {
1697			if (*pte == 0)
1698				continue;
1699			anyvalid = 1;
1700			if (pmap_remove_pte(pmap, pte, sva))
1701				break;
1702		}
1703	}
1704out:
1705	sched_unpin();
1706	vm_page_unlock_queues();
1707	if (anyvalid)
1708		pmap_invalidate_all(pmap);
1709	PMAP_UNLOCK(pmap);
1710}
1711
1712/*
1713 *	Routine:	pmap_remove_all
1714 *	Function:
1715 *		Removes this physical page from
1716 *		all physical maps in which it resides.
1717 *		Reflects back modify bits to the pager.
1718 *
1719 *	Notes:
1720 *		Original versions of this routine were very
1721 *		inefficient because they iteratively called
1722 *		pmap_remove (slow...)
1723 */
1724
1725void
1726pmap_remove_all(vm_page_t m)
1727{
1728	register pv_entry_t pv;
1729	pt_entry_t *pte, tpte;
1730
1731#if defined(PMAP_DIAGNOSTIC)
1732	/*
1733	 * XXX This makes pmap_remove_all() illegal for non-managed pages!
1734	 */
1735	if (m->flags & PG_FICTITIOUS) {
1736		panic("pmap_remove_all: illegal for unmanaged page, va: 0x%x",
1737		    VM_PAGE_TO_PHYS(m));
1738	}
1739#endif
1740	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1741	sched_pin();
1742	while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
1743		PMAP_LOCK(pv->pv_pmap);
1744		pv->pv_pmap->pm_stats.resident_count--;
1745		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
1746		tpte = pte_load_clear(pte);
1747		if (tpte & PG_W)
1748			pv->pv_pmap->pm_stats.wired_count--;
1749		if (tpte & PG_A)
1750			vm_page_flag_set(m, PG_REFERENCED);
1751
1752		/*
1753		 * Update the vm_page_t clean and reference bits.
1754		 */
1755		if (tpte & PG_M) {
1756			KASSERT((tpte & PG_RW),
1757	("pmap_remove_all: modified page not writable: va: %#x, pte: %#jx",
1758			    pv->pv_va, (uintmax_t)tpte));
1759			if (pmap_track_modified(pv->pv_va))
1760				vm_page_dirty(m);
1761		}
1762		pmap_invalidate_page(pv->pv_pmap, pv->pv_va);
1763		TAILQ_REMOVE(&pv->pv_pmap->pm_pvlist, pv, pv_plist);
1764		TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
1765		m->md.pv_list_count--;
1766		pmap_unuse_pt(pv->pv_pmap, pv->pv_va);
1767		PMAP_UNLOCK(pv->pv_pmap);
1768		free_pv_entry(pv);
1769	}
1770	vm_page_flag_clear(m, PG_WRITEABLE);
1771	sched_unpin();
1772}
1773
1774/*
1775 *	Set the physical protection on the
1776 *	specified range of this map as requested.
1777 */
1778void
1779pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
1780{
1781	vm_offset_t pdnxt;
1782	pd_entry_t ptpaddr;
1783	pt_entry_t *pte;
1784	int anychanged;
1785
1786	if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
1787		pmap_remove(pmap, sva, eva);
1788		return;
1789	}
1790
1791	if (prot & VM_PROT_WRITE)
1792		return;
1793
1794	anychanged = 0;
1795
1796	vm_page_lock_queues();
1797	sched_pin();
1798	PMAP_LOCK(pmap);
1799	for (; sva < eva; sva = pdnxt) {
1800		unsigned obits, pbits, pdirindex;
1801
1802		pdnxt = (sva + NBPDR) & ~PDRMASK;
1803
1804		pdirindex = sva >> PDRSHIFT;
1805		ptpaddr = pmap->pm_pdir[pdirindex];
1806
1807		/*
1808		 * Weed out invalid mappings. Note: we assume that the page
1809		 * directory table is always allocated, and in kernel virtual.
1810		 */
1811		if (ptpaddr == 0)
1812			continue;
1813
1814		/*
1815		 * Check for large page.
1816		 */
1817		if ((ptpaddr & PG_PS) != 0) {
1818			pmap->pm_pdir[pdirindex] &= ~(PG_M|PG_RW);
1819			anychanged = 1;
1820			continue;
1821		}
1822
1823		if (pdnxt > eva)
1824			pdnxt = eva;
1825
1826		for (pte = pmap_pte_quick(pmap, sva); sva != pdnxt; pte++,
1827		    sva += PAGE_SIZE) {
1828			vm_page_t m;
1829
1830retry:
1831			/*
1832			 * Regardless of whether a pte is 32 or 64 bits in
1833			 * size, PG_RW, PG_A, and PG_M are among the least
1834			 * significant 32 bits.
1835			 */
1836			obits = pbits = *(u_int *)pte;
1837			if (pbits & PG_MANAGED) {
1838				m = NULL;
1839				if (pbits & PG_A) {
1840					m = PHYS_TO_VM_PAGE(*pte);
1841					vm_page_flag_set(m, PG_REFERENCED);
1842					pbits &= ~PG_A;
1843				}
1844				if ((pbits & PG_M) != 0 &&
1845				    pmap_track_modified(sva)) {
1846					if (m == NULL)
1847						m = PHYS_TO_VM_PAGE(*pte);
1848					vm_page_dirty(m);
1849				}
1850			}
1851
1852			pbits &= ~(PG_RW | PG_M);
1853
1854			if (pbits != obits) {
1855				if (!atomic_cmpset_int((u_int *)pte, obits,
1856				    pbits))
1857					goto retry;
1858				if (obits & PG_G)
1859					pmap_invalidate_page(pmap, sva);
1860				else
1861					anychanged = 1;
1862			}
1863		}
1864	}
1865	sched_unpin();
1866	vm_page_unlock_queues();
1867	if (anychanged)
1868		pmap_invalidate_all(pmap);
1869	PMAP_UNLOCK(pmap);
1870}
1871
1872/*
1873 *	Insert the given physical page (p) at
1874 *	the specified virtual address (v) in the
1875 *	target physical map with the protection requested.
1876 *
1877 *	If specified, the page will be wired down, meaning
1878 *	that the related pte can not be reclaimed.
1879 *
1880 *	NB:  This is the only routine which MAY NOT lazy-evaluate
1881 *	or lose information.  That is, this routine must actually
1882 *	insert this page into the given map NOW.
1883 */
1884void
1885pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
1886	   boolean_t wired)
1887{
1888	vm_paddr_t pa;
1889	register pt_entry_t *pte;
1890	vm_paddr_t opa;
1891	pt_entry_t origpte, newpte;
1892	vm_page_t mpte, om;
1893	boolean_t invlva;
1894
1895	va &= PG_FRAME;
1896#ifdef PMAP_DIAGNOSTIC
1897	if (va > VM_MAX_KERNEL_ADDRESS)
1898		panic("pmap_enter: toobig");
1899	if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
1900		panic("pmap_enter: invalid to pmap_enter page table pages (va: 0x%x)", va);
1901#endif
1902
1903	mpte = NULL;
1904
1905	vm_page_lock_queues();
1906	PMAP_LOCK(pmap);
1907	sched_pin();
1908
1909	/*
1910	 * In the case that a page table page is not
1911	 * resident, we are creating it here.
1912	 */
1913	if (va < VM_MAXUSER_ADDRESS) {
1914		mpte = pmap_allocpte(pmap, va, M_WAITOK);
1915	}
1916#if 0 && defined(PMAP_DIAGNOSTIC)
1917	else {
1918		pd_entry_t *pdeaddr = pmap_pde(pmap, va);
1919		origpte = *pdeaddr;
1920		if ((origpte & PG_V) == 0) {
1921			panic("pmap_enter: invalid kernel page table page, pdir=%p, pde=%p, va=%p\n",
1922				pmap->pm_pdir[PTDPTDI], origpte, va);
1923		}
1924	}
1925#endif
1926
1927	pte = pmap_pte_quick(pmap, va);
1928
1929	/*
1930	 * Page Directory table entry not valid, we need a new PT page
1931	 */
1932	if (pte == NULL) {
1933		panic("pmap_enter: invalid page directory pdir=%#jx, va=%#x\n",
1934			(uintmax_t)pmap->pm_pdir[PTDPTDI], va);
1935	}
1936
1937	pa = VM_PAGE_TO_PHYS(m);
1938	om = NULL;
1939	origpte = *pte;
1940	opa = origpte & PG_FRAME;
1941
1942	if (origpte & PG_PS) {
1943		/*
1944		 * Yes, I know this will truncate upper address bits for PAE,
1945		 * but I'm actually more interested in the lower bits
1946		 */
1947		printf("pmap_enter: va %p, pte %p, origpte %p\n",
1948		    (void *)va, (void *)pte, (void *)(uintptr_t)origpte);
1949		panic("pmap_enter: attempted pmap_enter on 4MB page");
1950	}
1951
1952	/*
1953	 * Mapping has not changed, must be protection or wiring change.
1954	 */
1955	if (origpte && (opa == pa)) {
1956		/*
1957		 * Wiring change, just update stats. We don't worry about
1958		 * wiring PT pages as they remain resident as long as there
1959		 * are valid mappings in them. Hence, if a user page is wired,
1960		 * the PT page will be also.
1961		 */
1962		if (wired && ((origpte & PG_W) == 0))
1963			pmap->pm_stats.wired_count++;
1964		else if (!wired && (origpte & PG_W))
1965			pmap->pm_stats.wired_count--;
1966
1967		/*
1968		 * Remove extra pte reference
1969		 */
1970		if (mpte)
1971			mpte->wire_count--;
1972
1973		/*
1974		 * We might be turning off write access to the page,
1975		 * so we go ahead and sense modify status.
1976		 */
1977		if (origpte & PG_MANAGED) {
1978			om = m;
1979			pa |= PG_MANAGED;
1980		}
1981		goto validate;
1982	}
1983	/*
1984	 * Mapping has changed, invalidate old range and fall through to
1985	 * handle validating new mapping.
1986	 */
1987	if (opa) {
1988		if (origpte & PG_W)
1989			pmap->pm_stats.wired_count--;
1990		if (origpte & PG_MANAGED) {
1991			om = PHYS_TO_VM_PAGE(opa);
1992			pmap_remove_entry(pmap, om, va);
1993		}
1994		if (mpte != NULL) {
1995			mpte->wire_count--;
1996			KASSERT(mpte->wire_count > 0,
1997			    ("pmap_enter: missing reference to page table page,"
1998			     " va: 0x%x", va));
1999		}
2000	} else
2001		pmap->pm_stats.resident_count++;
2002
2003	/*
2004	 * Enter on the PV list if part of our managed memory.
2005	 */
2006	if ((m->flags & (PG_FICTITIOUS | PG_UNMANAGED)) == 0) {
2007		pmap_insert_entry(pmap, va, m);
2008		pa |= PG_MANAGED;
2009	}
2010
2011	/*
2012	 * Increment counters
2013	 */
2014	if (wired)
2015		pmap->pm_stats.wired_count++;
2016
2017validate:
2018	/*
2019	 * Now validate mapping with desired protection/wiring.
2020	 */
2021	newpte = (pt_entry_t)(pa | PG_V);
2022	if ((prot & VM_PROT_WRITE) != 0)
2023		newpte |= PG_RW;
2024	if (wired)
2025		newpte |= PG_W;
2026	if (va < VM_MAXUSER_ADDRESS)
2027		newpte |= PG_U;
2028	if (pmap == kernel_pmap)
2029		newpte |= pgeflag;
2030
2031	/*
2032	 * if the mapping or permission bits are different, we need
2033	 * to update the pte.
2034	 */
2035	if ((origpte & ~(PG_M|PG_A)) != newpte) {
2036		if (origpte & PG_V) {
2037			invlva = FALSE;
2038			origpte = pte_load_store(pte, newpte | PG_A);
2039			if (origpte & PG_A) {
2040				if (origpte & PG_MANAGED)
2041					vm_page_flag_set(om, PG_REFERENCED);
2042				if (opa != VM_PAGE_TO_PHYS(m))
2043					invlva = TRUE;
2044			}
2045			if (origpte & PG_M) {
2046				KASSERT((origpte & PG_RW),
2047	("pmap_enter: modified page not writable: va: %#x, pte: %#jx",
2048				    va, (uintmax_t)origpte));
2049				if ((origpte & PG_MANAGED) &&
2050				    pmap_track_modified(va))
2051					vm_page_dirty(om);
2052				if ((prot & VM_PROT_WRITE) == 0)
2053					invlva = TRUE;
2054			}
2055			if (invlva)
2056				pmap_invalidate_page(pmap, va);
2057		} else
2058			pte_store(pte, newpte | PG_A);
2059	}
2060	sched_unpin();
2061	vm_page_unlock_queues();
2062	PMAP_UNLOCK(pmap);
2063}
2064
2065/*
2066 * this code makes some *MAJOR* assumptions:
2067 * 1. Current pmap & pmap exists.
2068 * 2. Not wired.
2069 * 3. Read access.
2070 * 4. No page table pages.
2071 * but is *MUCH* faster than pmap_enter...
2072 */
2073
2074vm_page_t
2075pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
2076    vm_page_t mpte)
2077{
2078	pt_entry_t *pte;
2079	vm_paddr_t pa;
2080
2081	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2082	VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2083	PMAP_LOCK(pmap);
2084
2085	/*
2086	 * In the case that a page table page is not
2087	 * resident, we are creating it here.
2088	 */
2089	if (va < VM_MAXUSER_ADDRESS) {
2090		unsigned ptepindex;
2091		pd_entry_t ptepa;
2092
2093		/*
2094		 * Calculate pagetable page index
2095		 */
2096		ptepindex = va >> PDRSHIFT;
2097		if (mpte && (mpte->pindex == ptepindex)) {
2098			mpte->wire_count++;
2099		} else {
2100retry:
2101			/*
2102			 * Get the page directory entry
2103			 */
2104			ptepa = pmap->pm_pdir[ptepindex];
2105
2106			/*
2107			 * If the page table page is mapped, we just increment
2108			 * the hold count, and activate it.
2109			 */
2110			if (ptepa) {
2111				if (ptepa & PG_PS)
2112					panic("pmap_enter_quick: unexpected mapping into 4MB page");
2113				mpte = PHYS_TO_VM_PAGE(ptepa);
2114				mpte->wire_count++;
2115			} else {
2116				mpte = _pmap_allocpte(pmap, ptepindex,
2117				    M_NOWAIT);
2118				if (mpte == NULL) {
2119					PMAP_UNLOCK(pmap);
2120					vm_page_busy(m);
2121					vm_page_unlock_queues();
2122					VM_OBJECT_UNLOCK(m->object);
2123					VM_WAIT;
2124					VM_OBJECT_LOCK(m->object);
2125					vm_page_lock_queues();
2126					vm_page_wakeup(m);
2127					PMAP_LOCK(pmap);
2128					goto retry;
2129				}
2130			}
2131		}
2132	} else {
2133		mpte = NULL;
2134	}
2135
2136	/*
2137	 * This call to vtopte makes the assumption that we are
2138	 * entering the page into the current pmap.  In order to support
2139	 * quick entry into any pmap, one would likely use pmap_pte_quick.
2140	 * But that isn't as quick as vtopte.
2141	 */
2142	pte = vtopte(va);
2143	if (*pte) {
2144		if (mpte != NULL) {
2145			pmap_unwire_pte_hold(pmap, mpte);
2146			mpte = NULL;
2147		}
2148		goto out;
2149	}
2150
2151	/*
2152	 * Enter on the PV list if part of our managed memory. Note that we
2153	 * raise IPL while manipulating pv_table since pmap_enter can be
2154	 * called at interrupt time.
2155	 */
2156	if ((m->flags & (PG_FICTITIOUS|PG_UNMANAGED)) == 0)
2157		pmap_insert_entry(pmap, va, m);
2158
2159	/*
2160	 * Increment counters
2161	 */
2162	pmap->pm_stats.resident_count++;
2163
2164	pa = VM_PAGE_TO_PHYS(m);
2165
2166	/*
2167	 * Now validate mapping with RO protection
2168	 */
2169	if (m->flags & (PG_FICTITIOUS|PG_UNMANAGED))
2170		pte_store(pte, pa | PG_V | PG_U);
2171	else
2172		pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
2173out:
2174	PMAP_UNLOCK(pmap);
2175	return mpte;
2176}
2177
2178/*
2179 * Make a temporary mapping for a physical address.  This is only intended
2180 * to be used for panic dumps.
2181 */
2182void *
2183pmap_kenter_temporary(vm_paddr_t pa, int i)
2184{
2185	vm_offset_t va;
2186
2187	va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
2188	pmap_kenter(va, pa);
2189	invlpg(va);
2190	return ((void *)crashdumpmap);
2191}
2192
2193/*
2194 * This code maps large physical mmap regions into the
2195 * processor address space.  Note that some shortcuts
2196 * are taken, but the code works.
2197 */
2198void
2199pmap_object_init_pt(pmap_t pmap, vm_offset_t addr,
2200		    vm_object_t object, vm_pindex_t pindex,
2201		    vm_size_t size)
2202{
2203	vm_page_t p;
2204
2205	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2206	KASSERT(object->type == OBJT_DEVICE,
2207	    ("pmap_object_init_pt: non-device object"));
2208	if (pseflag &&
2209	    ((addr & (NBPDR - 1)) == 0) && ((size & (NBPDR - 1)) == 0)) {
2210		int i;
2211		vm_page_t m[1];
2212		unsigned int ptepindex;
2213		int npdes;
2214		pd_entry_t ptepa;
2215
2216		PMAP_LOCK(pmap);
2217		if (pmap->pm_pdir[ptepindex = (addr >> PDRSHIFT)])
2218			goto out;
2219		PMAP_UNLOCK(pmap);
2220retry:
2221		p = vm_page_lookup(object, pindex);
2222		if (p != NULL) {
2223			vm_page_lock_queues();
2224			if (vm_page_sleep_if_busy(p, FALSE, "init4p"))
2225				goto retry;
2226		} else {
2227			p = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL);
2228			if (p == NULL)
2229				return;
2230			m[0] = p;
2231
2232			if (vm_pager_get_pages(object, m, 1, 0) != VM_PAGER_OK) {
2233				vm_page_lock_queues();
2234				vm_page_free(p);
2235				vm_page_unlock_queues();
2236				return;
2237			}
2238
2239			p = vm_page_lookup(object, pindex);
2240			vm_page_lock_queues();
2241			vm_page_wakeup(p);
2242		}
2243		vm_page_unlock_queues();
2244
2245		ptepa = VM_PAGE_TO_PHYS(p);
2246		if (ptepa & (NBPDR - 1))
2247			return;
2248
2249		p->valid = VM_PAGE_BITS_ALL;
2250
2251		PMAP_LOCK(pmap);
2252		pmap->pm_stats.resident_count += size >> PAGE_SHIFT;
2253		npdes = size >> PDRSHIFT;
2254		for(i = 0; i < npdes; i++) {
2255			pde_store(&pmap->pm_pdir[ptepindex],
2256			    ptepa | PG_U | PG_RW | PG_V | PG_PS);
2257			ptepa += NBPDR;
2258			ptepindex += 1;
2259		}
2260		pmap_invalidate_all(pmap);
2261out:
2262		PMAP_UNLOCK(pmap);
2263	}
2264}
2265
2266/*
2267 *	Routine:	pmap_change_wiring
2268 *	Function:	Change the wiring attribute for a map/virtual-address
2269 *			pair.
2270 *	In/out conditions:
2271 *			The mapping must already exist in the pmap.
2272 */
2273void
2274pmap_change_wiring(pmap, va, wired)
2275	register pmap_t pmap;
2276	vm_offset_t va;
2277	boolean_t wired;
2278{
2279	register pt_entry_t *pte;
2280
2281	PMAP_LOCK(pmap);
2282	pte = pmap_pte(pmap, va);
2283
2284	if (wired && !pmap_pte_w(pte))
2285		pmap->pm_stats.wired_count++;
2286	else if (!wired && pmap_pte_w(pte))
2287		pmap->pm_stats.wired_count--;
2288
2289	/*
2290	 * Wiring is not a hardware characteristic so there is no need to
2291	 * invalidate TLB.
2292	 */
2293	pmap_pte_set_w(pte, wired);
2294	pmap_pte_release(pte);
2295	PMAP_UNLOCK(pmap);
2296}
2297
2298
2299
2300/*
2301 *	Copy the range specified by src_addr/len
2302 *	from the source map to the range dst_addr/len
2303 *	in the destination map.
2304 *
2305 *	This routine is only advisory and need not do anything.
2306 */
2307
2308void
2309pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
2310	  vm_offset_t src_addr)
2311{
2312	vm_offset_t addr;
2313	vm_offset_t end_addr = src_addr + len;
2314	vm_offset_t pdnxt;
2315	vm_page_t m;
2316
2317	if (dst_addr != src_addr)
2318		return;
2319
2320	if (!pmap_is_current(src_pmap))
2321		return;
2322
2323	vm_page_lock_queues();
2324	if (dst_pmap < src_pmap) {
2325		PMAP_LOCK(dst_pmap);
2326		PMAP_LOCK(src_pmap);
2327	} else {
2328		PMAP_LOCK(src_pmap);
2329		PMAP_LOCK(dst_pmap);
2330	}
2331	sched_pin();
2332	for (addr = src_addr; addr < end_addr; addr = pdnxt) {
2333		pt_entry_t *src_pte, *dst_pte;
2334		vm_page_t dstmpte, srcmpte;
2335		pd_entry_t srcptepaddr;
2336		unsigned ptepindex;
2337
2338		if (addr >= UPT_MIN_ADDRESS)
2339			panic("pmap_copy: invalid to pmap_copy page tables");
2340
2341		/*
2342		 * Don't let optional prefaulting of pages make us go
2343		 * way below the low water mark of free pages or way
2344		 * above high water mark of used pv entries.
2345		 */
2346		if (cnt.v_free_count < cnt.v_free_reserved ||
2347		    pv_entry_count > pv_entry_high_water)
2348			break;
2349
2350		pdnxt = (addr + NBPDR) & ~PDRMASK;
2351		ptepindex = addr >> PDRSHIFT;
2352
2353		srcptepaddr = src_pmap->pm_pdir[ptepindex];
2354		if (srcptepaddr == 0)
2355			continue;
2356
2357		if (srcptepaddr & PG_PS) {
2358			if (dst_pmap->pm_pdir[ptepindex] == 0) {
2359				dst_pmap->pm_pdir[ptepindex] = srcptepaddr;
2360				dst_pmap->pm_stats.resident_count +=
2361				    NBPDR / PAGE_SIZE;
2362			}
2363			continue;
2364		}
2365
2366		srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
2367		if (srcmpte->wire_count == 0)
2368			panic("pmap_copy: source page table page is unused");
2369
2370		if (pdnxt > end_addr)
2371			pdnxt = end_addr;
2372
2373		src_pte = vtopte(addr);
2374		while (addr < pdnxt) {
2375			pt_entry_t ptetemp;
2376			ptetemp = *src_pte;
2377			/*
2378			 * we only virtual copy managed pages
2379			 */
2380			if ((ptetemp & PG_MANAGED) != 0) {
2381				/*
2382				 * We have to check after allocpte for the
2383				 * pte still being around...  allocpte can
2384				 * block.
2385				 */
2386				dstmpte = pmap_allocpte(dst_pmap, addr,
2387				    M_NOWAIT);
2388				if (dstmpte == NULL)
2389					break;
2390				dst_pte = pmap_pte_quick(dst_pmap, addr);
2391				if (*dst_pte == 0) {
2392					/*
2393					 * Clear the modified and
2394					 * accessed (referenced) bits
2395					 * during the copy.
2396					 */
2397					m = PHYS_TO_VM_PAGE(ptetemp);
2398					*dst_pte = ptetemp & ~(PG_M | PG_A);
2399					dst_pmap->pm_stats.resident_count++;
2400					pmap_insert_entry(dst_pmap, addr, m);
2401	 			} else
2402					pmap_unwire_pte_hold(dst_pmap, dstmpte);
2403				if (dstmpte->wire_count >= srcmpte->wire_count)
2404					break;
2405			}
2406			addr += PAGE_SIZE;
2407			src_pte++;
2408		}
2409	}
2410	sched_unpin();
2411	vm_page_unlock_queues();
2412	PMAP_UNLOCK(src_pmap);
2413	PMAP_UNLOCK(dst_pmap);
2414}
2415
2416static __inline void
2417pagezero(void *page)
2418{
2419#if defined(I686_CPU)
2420	if (cpu_class == CPUCLASS_686) {
2421#if defined(CPU_ENABLE_SSE)
2422		if (cpu_feature & CPUID_SSE2)
2423			sse2_pagezero(page);
2424		else
2425#endif
2426			i686_pagezero(page);
2427	} else
2428#endif
2429		bzero(page, PAGE_SIZE);
2430}
2431
2432/*
2433 *	pmap_zero_page zeros the specified hardware page by mapping
2434 *	the page into KVM and using bzero to clear its contents.
2435 */
2436void
2437pmap_zero_page(vm_page_t m)
2438{
2439	struct sysmaps *sysmaps;
2440
2441	sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
2442	mtx_lock(&sysmaps->lock);
2443	if (*sysmaps->CMAP2)
2444		panic("pmap_zero_page: CMAP2 busy");
2445	sched_pin();
2446	*sysmaps->CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M;
2447	invlcaddr(sysmaps->CADDR2);
2448	pagezero(sysmaps->CADDR2);
2449	*sysmaps->CMAP2 = 0;
2450	sched_unpin();
2451	mtx_unlock(&sysmaps->lock);
2452}
2453
2454/*
2455 *	pmap_zero_page_area zeros the specified hardware page by mapping
2456 *	the page into KVM and using bzero to clear its contents.
2457 *
2458 *	off and size may not cover an area beyond a single hardware page.
2459 */
2460void
2461pmap_zero_page_area(vm_page_t m, int off, int size)
2462{
2463	struct sysmaps *sysmaps;
2464
2465	sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
2466	mtx_lock(&sysmaps->lock);
2467	if (*sysmaps->CMAP2)
2468		panic("pmap_zero_page: CMAP2 busy");
2469	sched_pin();
2470	*sysmaps->CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M;
2471	invlcaddr(sysmaps->CADDR2);
2472	if (off == 0 && size == PAGE_SIZE)
2473		pagezero(sysmaps->CADDR2);
2474	else
2475		bzero((char *)sysmaps->CADDR2 + off, size);
2476	*sysmaps->CMAP2 = 0;
2477	sched_unpin();
2478	mtx_unlock(&sysmaps->lock);
2479}
2480
2481/*
2482 *	pmap_zero_page_idle zeros the specified hardware page by mapping
2483 *	the page into KVM and using bzero to clear its contents.  This
2484 *	is intended to be called from the vm_pagezero process only and
2485 *	outside of Giant.
2486 */
2487void
2488pmap_zero_page_idle(vm_page_t m)
2489{
2490
2491	if (*CMAP3)
2492		panic("pmap_zero_page: CMAP3 busy");
2493	sched_pin();
2494	*CMAP3 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M;
2495	invlcaddr(CADDR3);
2496	pagezero(CADDR3);
2497	*CMAP3 = 0;
2498	sched_unpin();
2499}
2500
2501/*
2502 *	pmap_copy_page copies the specified (machine independent)
2503 *	page by mapping the page into virtual memory and using
2504 *	bcopy to copy the page, one machine dependent page at a
2505 *	time.
2506 */
2507void
2508pmap_copy_page(vm_page_t src, vm_page_t dst)
2509{
2510	struct sysmaps *sysmaps;
2511
2512	sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
2513	mtx_lock(&sysmaps->lock);
2514	if (*sysmaps->CMAP1)
2515		panic("pmap_copy_page: CMAP1 busy");
2516	if (*sysmaps->CMAP2)
2517		panic("pmap_copy_page: CMAP2 busy");
2518	sched_pin();
2519	invlpg((u_int)sysmaps->CADDR1);
2520	invlpg((u_int)sysmaps->CADDR2);
2521	*sysmaps->CMAP1 = PG_V | VM_PAGE_TO_PHYS(src) | PG_A;
2522	*sysmaps->CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(dst) | PG_A | PG_M;
2523	bcopy(sysmaps->CADDR1, sysmaps->CADDR2, PAGE_SIZE);
2524	*sysmaps->CMAP1 = 0;
2525	*sysmaps->CMAP2 = 0;
2526	sched_unpin();
2527	mtx_unlock(&sysmaps->lock);
2528}
2529
2530/*
2531 * Returns true if the pmap's pv is one of the first
2532 * 16 pvs linked to from this page.  This count may
2533 * be changed upwards or downwards in the future; it
2534 * is only necessary that true be returned for a small
2535 * subset of pmaps for proper page aging.
2536 */
2537boolean_t
2538pmap_page_exists_quick(pmap, m)
2539	pmap_t pmap;
2540	vm_page_t m;
2541{
2542	pv_entry_t pv;
2543	int loops = 0;
2544
2545	if (m->flags & PG_FICTITIOUS)
2546		return FALSE;
2547
2548	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2549	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2550		if (pv->pv_pmap == pmap) {
2551			return TRUE;
2552		}
2553		loops++;
2554		if (loops >= 16)
2555			break;
2556	}
2557	return (FALSE);
2558}
2559
2560#define PMAP_REMOVE_PAGES_CURPROC_ONLY
2561/*
2562 * Remove all pages from specified address space
2563 * this aids process exit speeds.  Also, this code
2564 * is special cased for current process only, but
2565 * can have the more generic (and slightly slower)
2566 * mode enabled.  This is much faster than pmap_remove
2567 * in the case of running down an entire address space.
2568 */
2569void
2570pmap_remove_pages(pmap, sva, eva)
2571	pmap_t pmap;
2572	vm_offset_t sva, eva;
2573{
2574	pt_entry_t *pte, tpte;
2575	vm_page_t m;
2576	pv_entry_t pv, npv;
2577
2578#ifdef PMAP_REMOVE_PAGES_CURPROC_ONLY
2579	if (pmap != vmspace_pmap(curthread->td_proc->p_vmspace)) {
2580		printf("warning: pmap_remove_pages called with non-current pmap\n");
2581		return;
2582	}
2583#endif
2584	vm_page_lock_queues();
2585	PMAP_LOCK(pmap);
2586	sched_pin();
2587	for (pv = TAILQ_FIRST(&pmap->pm_pvlist); pv; pv = npv) {
2588
2589		if (pv->pv_va >= eva || pv->pv_va < sva) {
2590			npv = TAILQ_NEXT(pv, pv_plist);
2591			continue;
2592		}
2593
2594#ifdef PMAP_REMOVE_PAGES_CURPROC_ONLY
2595		pte = vtopte(pv->pv_va);
2596#else
2597		pte = pmap_pte_quick(pmap, pv->pv_va);
2598#endif
2599		tpte = *pte;
2600
2601		if (tpte == 0) {
2602			printf("TPTE at %p  IS ZERO @ VA %08x\n",
2603							pte, pv->pv_va);
2604			panic("bad pte");
2605		}
2606
2607/*
2608 * We cannot remove wired pages from a process' mapping at this time
2609 */
2610		if (tpte & PG_W) {
2611			npv = TAILQ_NEXT(pv, pv_plist);
2612			continue;
2613		}
2614
2615		m = PHYS_TO_VM_PAGE(tpte);
2616		KASSERT(m->phys_addr == (tpte & PG_FRAME),
2617		    ("vm_page_t %p phys_addr mismatch %016jx %016jx",
2618		    m, (uintmax_t)m->phys_addr, (uintmax_t)tpte));
2619
2620		KASSERT(m < &vm_page_array[vm_page_array_size],
2621			("pmap_remove_pages: bad tpte %#jx", (uintmax_t)tpte));
2622
2623		pmap->pm_stats.resident_count--;
2624
2625		pte_clear(pte);
2626
2627		/*
2628		 * Update the vm_page_t clean and reference bits.
2629		 */
2630		if (tpte & PG_M) {
2631			vm_page_dirty(m);
2632		}
2633
2634		npv = TAILQ_NEXT(pv, pv_plist);
2635		TAILQ_REMOVE(&pmap->pm_pvlist, pv, pv_plist);
2636
2637		m->md.pv_list_count--;
2638		TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2639		if (TAILQ_EMPTY(&m->md.pv_list))
2640			vm_page_flag_clear(m, PG_WRITEABLE);
2641
2642		pmap_unuse_pt(pmap, pv->pv_va);
2643		free_pv_entry(pv);
2644	}
2645	sched_unpin();
2646	pmap_invalidate_all(pmap);
2647	PMAP_UNLOCK(pmap);
2648	vm_page_unlock_queues();
2649}
2650
2651/*
2652 *	pmap_is_modified:
2653 *
2654 *	Return whether or not the specified physical page was modified
2655 *	in any physical maps.
2656 */
2657boolean_t
2658pmap_is_modified(vm_page_t m)
2659{
2660	pv_entry_t pv;
2661	pt_entry_t *pte;
2662	boolean_t rv;
2663
2664	rv = FALSE;
2665	if (m->flags & PG_FICTITIOUS)
2666		return (rv);
2667
2668	sched_pin();
2669	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2670	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2671		/*
2672		 * if the bit being tested is the modified bit, then
2673		 * mark clean_map and ptes as never
2674		 * modified.
2675		 */
2676		if (!pmap_track_modified(pv->pv_va))
2677			continue;
2678		PMAP_LOCK(pv->pv_pmap);
2679		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
2680		rv = (*pte & PG_M) != 0;
2681		PMAP_UNLOCK(pv->pv_pmap);
2682		if (rv)
2683			break;
2684	}
2685	sched_unpin();
2686	return (rv);
2687}
2688
2689/*
2690 *	pmap_is_prefaultable:
2691 *
2692 *	Return whether or not the specified virtual address is elgible
2693 *	for prefault.
2694 */
2695boolean_t
2696pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
2697{
2698	pt_entry_t *pte;
2699	boolean_t rv;
2700
2701	rv = FALSE;
2702	PMAP_LOCK(pmap);
2703	if (*pmap_pde(pmap, addr)) {
2704		pte = vtopte(addr);
2705		rv = *pte == 0;
2706	}
2707	PMAP_UNLOCK(pmap);
2708	return (rv);
2709}
2710
2711/*
2712 *	Clear the given bit in each of the given page's ptes.  The bit is
2713 *	expressed as a 32-bit mask.  Consequently, if the pte is 64 bits in
2714 *	size, only a bit within the least significant 32 can be cleared.
2715 */
2716static __inline void
2717pmap_clear_ptes(vm_page_t m, int bit)
2718{
2719	register pv_entry_t pv;
2720	pt_entry_t pbits, *pte;
2721
2722	if ((m->flags & PG_FICTITIOUS) ||
2723	    (bit == PG_RW && (m->flags & PG_WRITEABLE) == 0))
2724		return;
2725
2726	sched_pin();
2727	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2728	/*
2729	 * Loop over all current mappings setting/clearing as appropos If
2730	 * setting RO do we need to clear the VAC?
2731	 */
2732	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2733		/*
2734		 * don't write protect pager mappings
2735		 */
2736		if (bit == PG_RW) {
2737			if (!pmap_track_modified(pv->pv_va))
2738				continue;
2739		}
2740
2741		PMAP_LOCK(pv->pv_pmap);
2742		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
2743retry:
2744		pbits = *pte;
2745		if (pbits & bit) {
2746			if (bit == PG_RW) {
2747				/*
2748				 * Regardless of whether a pte is 32 or 64 bits
2749				 * in size, PG_RW and PG_M are among the least
2750				 * significant 32 bits.
2751				 */
2752				if (!atomic_cmpset_int((u_int *)pte, pbits,
2753				    pbits & ~(PG_RW | PG_M)))
2754					goto retry;
2755				if (pbits & PG_M) {
2756					vm_page_dirty(m);
2757				}
2758			} else {
2759				atomic_clear_int((u_int *)pte, bit);
2760			}
2761			pmap_invalidate_page(pv->pv_pmap, pv->pv_va);
2762		}
2763		PMAP_UNLOCK(pv->pv_pmap);
2764	}
2765	if (bit == PG_RW)
2766		vm_page_flag_clear(m, PG_WRITEABLE);
2767	sched_unpin();
2768}
2769
2770/*
2771 *      pmap_page_protect:
2772 *
2773 *      Lower the permission for all mappings to a given page.
2774 */
2775void
2776pmap_page_protect(vm_page_t m, vm_prot_t prot)
2777{
2778	if ((prot & VM_PROT_WRITE) == 0) {
2779		if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
2780			pmap_clear_ptes(m, PG_RW);
2781		} else {
2782			pmap_remove_all(m);
2783		}
2784	}
2785}
2786
2787/*
2788 *	pmap_ts_referenced:
2789 *
2790 *	Return a count of reference bits for a page, clearing those bits.
2791 *	It is not necessary for every reference bit to be cleared, but it
2792 *	is necessary that 0 only be returned when there are truly no
2793 *	reference bits set.
2794 *
2795 *	XXX: The exact number of bits to check and clear is a matter that
2796 *	should be tested and standardized at some point in the future for
2797 *	optimal aging of shared pages.
2798 */
2799int
2800pmap_ts_referenced(vm_page_t m)
2801{
2802	register pv_entry_t pv, pvf, pvn;
2803	pt_entry_t *pte;
2804	pt_entry_t v;
2805	int rtval = 0;
2806
2807	if (m->flags & PG_FICTITIOUS)
2808		return (rtval);
2809
2810	sched_pin();
2811	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2812	if ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
2813
2814		pvf = pv;
2815
2816		do {
2817			pvn = TAILQ_NEXT(pv, pv_list);
2818
2819			TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2820
2821			TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
2822
2823			if (!pmap_track_modified(pv->pv_va))
2824				continue;
2825
2826			PMAP_LOCK(pv->pv_pmap);
2827			pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
2828
2829			if (pte && ((v = pte_load(pte)) & PG_A) != 0) {
2830				atomic_clear_int((u_int *)pte, PG_A);
2831				pmap_invalidate_page(pv->pv_pmap, pv->pv_va);
2832
2833				rtval++;
2834				if (rtval > 4) {
2835					PMAP_UNLOCK(pv->pv_pmap);
2836					break;
2837				}
2838			}
2839			PMAP_UNLOCK(pv->pv_pmap);
2840		} while ((pv = pvn) != NULL && pv != pvf);
2841	}
2842	sched_unpin();
2843
2844	return (rtval);
2845}
2846
2847/*
2848 *	Clear the modify bits on the specified physical page.
2849 */
2850void
2851pmap_clear_modify(vm_page_t m)
2852{
2853	pmap_clear_ptes(m, PG_M);
2854}
2855
2856/*
2857 *	pmap_clear_reference:
2858 *
2859 *	Clear the reference bit on the specified physical page.
2860 */
2861void
2862pmap_clear_reference(vm_page_t m)
2863{
2864	pmap_clear_ptes(m, PG_A);
2865}
2866
2867/*
2868 * Miscellaneous support routines follow
2869 */
2870
2871/*
2872 * Map a set of physical memory pages into the kernel virtual
2873 * address space. Return a pointer to where it is mapped. This
2874 * routine is intended to be used for mapping device memory,
2875 * NOT real memory.
2876 */
2877void *
2878pmap_mapdev(pa, size)
2879	vm_paddr_t pa;
2880	vm_size_t size;
2881{
2882	vm_offset_t va, tmpva, offset;
2883
2884	offset = pa & PAGE_MASK;
2885	size = roundup(offset + size, PAGE_SIZE);
2886	pa = pa & PG_FRAME;
2887
2888	if (pa < KERNLOAD && pa + size <= KERNLOAD)
2889		va = KERNBASE + pa;
2890	else
2891		va = kmem_alloc_nofault(kernel_map, size);
2892	if (!va)
2893		panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
2894
2895	for (tmpva = va; size > 0; ) {
2896		pmap_kenter(tmpva, pa);
2897		size -= PAGE_SIZE;
2898		tmpva += PAGE_SIZE;
2899		pa += PAGE_SIZE;
2900	}
2901	pmap_invalidate_range(kernel_pmap, va, tmpva);
2902	return ((void *)(va + offset));
2903}
2904
2905void
2906pmap_unmapdev(va, size)
2907	vm_offset_t va;
2908	vm_size_t size;
2909{
2910	vm_offset_t base, offset, tmpva;
2911
2912	if (va >= KERNBASE && va + size <= KERNBASE + KERNLOAD)
2913		return;
2914	base = va & PG_FRAME;
2915	offset = va & PAGE_MASK;
2916	size = roundup(offset + size, PAGE_SIZE);
2917	for (tmpva = base; tmpva < (base + size); tmpva += PAGE_SIZE)
2918		pmap_kremove(tmpva);
2919	pmap_invalidate_range(kernel_pmap, va, tmpva);
2920	kmem_free(kernel_map, base, size);
2921}
2922
2923/*
2924 * perform the pmap work for mincore
2925 */
2926int
2927pmap_mincore(pmap, addr)
2928	pmap_t pmap;
2929	vm_offset_t addr;
2930{
2931	pt_entry_t *ptep, pte;
2932	vm_page_t m;
2933	int val = 0;
2934
2935	PMAP_LOCK(pmap);
2936	ptep = pmap_pte(pmap, addr);
2937	pte = (ptep != NULL) ? *ptep : 0;
2938	pmap_pte_release(ptep);
2939	PMAP_UNLOCK(pmap);
2940
2941	if (pte != 0) {
2942		vm_paddr_t pa;
2943
2944		val = MINCORE_INCORE;
2945		if ((pte & PG_MANAGED) == 0)
2946			return val;
2947
2948		pa = pte & PG_FRAME;
2949
2950		m = PHYS_TO_VM_PAGE(pa);
2951
2952		/*
2953		 * Modified by us
2954		 */
2955		if (pte & PG_M)
2956			val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
2957		else {
2958			/*
2959			 * Modified by someone else
2960			 */
2961			vm_page_lock_queues();
2962			if (m->dirty || pmap_is_modified(m))
2963				val |= MINCORE_MODIFIED_OTHER;
2964			vm_page_unlock_queues();
2965		}
2966		/*
2967		 * Referenced by us
2968		 */
2969		if (pte & PG_A)
2970			val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
2971		else {
2972			/*
2973			 * Referenced by someone else
2974			 */
2975			vm_page_lock_queues();
2976			if ((m->flags & PG_REFERENCED) ||
2977			    pmap_ts_referenced(m)) {
2978				val |= MINCORE_REFERENCED_OTHER;
2979				vm_page_flag_set(m, PG_REFERENCED);
2980			}
2981			vm_page_unlock_queues();
2982		}
2983	}
2984	return val;
2985}
2986
2987void
2988pmap_activate(struct thread *td)
2989{
2990	struct proc *p = td->td_proc;
2991	pmap_t	pmap, oldpmap;
2992	u_int32_t  cr3;
2993
2994	critical_enter();
2995	pmap = vmspace_pmap(td->td_proc->p_vmspace);
2996	oldpmap = PCPU_GET(curpmap);
2997#if defined(SMP)
2998	atomic_clear_int(&oldpmap->pm_active, PCPU_GET(cpumask));
2999	atomic_set_int(&pmap->pm_active, PCPU_GET(cpumask));
3000#else
3001	oldpmap->pm_active &= ~1;
3002	pmap->pm_active |= 1;
3003#endif
3004#ifdef PAE
3005	cr3 = vtophys(pmap->pm_pdpt);
3006#else
3007	cr3 = vtophys(pmap->pm_pdir);
3008#endif
3009	/* XXXKSE this is wrong.
3010	 * pmap_activate is for the current thread on the current cpu
3011	 */
3012	if (p->p_flag & P_SA) {
3013		/* Make sure all other cr3 entries are updated. */
3014		/* what if they are running?  XXXKSE (maybe abort them) */
3015		FOREACH_THREAD_IN_PROC(p, td) {
3016			td->td_pcb->pcb_cr3 = cr3;
3017		}
3018	} else {
3019		td->td_pcb->pcb_cr3 = cr3;
3020	}
3021	load_cr3(cr3);
3022	PCPU_SET(curpmap, pmap);
3023	critical_exit();
3024}
3025
3026vm_offset_t
3027pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
3028{
3029
3030	if ((obj == NULL) || (size < NBPDR) || (obj->type != OBJT_DEVICE)) {
3031		return addr;
3032	}
3033
3034	addr = (addr + PDRMASK) & ~PDRMASK;
3035	return addr;
3036}
3037
3038
3039#if defined(PMAP_DEBUG)
3040pmap_pid_dump(int pid)
3041{
3042	pmap_t pmap;
3043	struct proc *p;
3044	int npte = 0;
3045	int index;
3046
3047	sx_slock(&allproc_lock);
3048	LIST_FOREACH(p, &allproc, p_list) {
3049		if (p->p_pid != pid)
3050			continue;
3051
3052		if (p->p_vmspace) {
3053			int i,j;
3054			index = 0;
3055			pmap = vmspace_pmap(p->p_vmspace);
3056			for (i = 0; i < NPDEPTD; i++) {
3057				pd_entry_t *pde;
3058				pt_entry_t *pte;
3059				vm_offset_t base = i << PDRSHIFT;
3060
3061				pde = &pmap->pm_pdir[i];
3062				if (pde && pmap_pde_v(pde)) {
3063					for (j = 0; j < NPTEPG; j++) {
3064						vm_offset_t va = base + (j << PAGE_SHIFT);
3065						if (va >= (vm_offset_t) VM_MIN_KERNEL_ADDRESS) {
3066							if (index) {
3067								index = 0;
3068								printf("\n");
3069							}
3070							sx_sunlock(&allproc_lock);
3071							return npte;
3072						}
3073						pte = pmap_pte(pmap, va);
3074						if (pte && pmap_pte_v(pte)) {
3075							pt_entry_t pa;
3076							vm_page_t m;
3077							pa = *pte;
3078							m = PHYS_TO_VM_PAGE(pa);
3079							printf("va: 0x%x, pt: 0x%x, h: %d, w: %d, f: 0x%x",
3080								va, pa, m->hold_count, m->wire_count, m->flags);
3081							npte++;
3082							index++;
3083							if (index >= 2) {
3084								index = 0;
3085								printf("\n");
3086							} else {
3087								printf(" ");
3088							}
3089						}
3090					}
3091				}
3092			}
3093		}
3094	}
3095	sx_sunlock(&allproc_lock);
3096	return npte;
3097}
3098#endif
3099
3100#if defined(DEBUG)
3101
3102static void	pads(pmap_t pm);
3103void		pmap_pvdump(vm_offset_t pa);
3104
3105/* print address space of pmap*/
3106static void
3107pads(pm)
3108	pmap_t pm;
3109{
3110	int i, j;
3111	vm_paddr_t va;
3112	pt_entry_t *ptep;
3113
3114	if (pm == kernel_pmap)
3115		return;
3116	for (i = 0; i < NPDEPTD; i++)
3117		if (pm->pm_pdir[i])
3118			for (j = 0; j < NPTEPG; j++) {
3119				va = (i << PDRSHIFT) + (j << PAGE_SHIFT);
3120				if (pm == kernel_pmap && va < KERNBASE)
3121					continue;
3122				if (pm != kernel_pmap && va > UPT_MAX_ADDRESS)
3123					continue;
3124				ptep = pmap_pte(pm, va);
3125				if (pmap_pte_v(ptep))
3126					printf("%x:%x ", va, *ptep);
3127			};
3128
3129}
3130
3131void
3132pmap_pvdump(pa)
3133	vm_paddr_t pa;
3134{
3135	pv_entry_t pv;
3136	vm_page_t m;
3137
3138	printf("pa %x", pa);
3139	m = PHYS_TO_VM_PAGE(pa);
3140	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3141		printf(" -> pmap %p, va %x", (void *)pv->pv_pmap, pv->pv_va);
3142		pads(pv->pv_pmap);
3143	}
3144	printf(" ");
3145}
3146#endif
3147