pmap.c revision 121823
162587Sitojun/*-
278064Sume * Copyright (c) 1991 Regents of the University of California.
362587Sitojun * All rights reserved.
4139826Simp * Copyright (c) 1994 John S. Dyson
552904Sshin * All rights reserved.
652904Sshin * Copyright (c) 1994 David Greenman
753541Sshin * All rights reserved.
852904Sshin *
952904Sshin * This code is derived from software contributed to Berkeley by
1052904Sshin * the Systems Programming Group of the University of Utah Computer
1152904Sshin * Science Department and William Jolitz of UUNET Technologies Inc.
1252904Sshin *
1352904Sshin * Redistribution and use in source and binary forms, with or without
1452904Sshin * modification, are permitted provided that the following conditions
1552904Sshin * are met:
1652904Sshin * 1. Redistributions of source code must retain the above copyright
1752904Sshin *    notice, this list of conditions and the following disclaimer.
1852904Sshin * 2. Redistributions in binary form must reproduce the above copyright
1953541Sshin *    notice, this list of conditions and the following disclaimer in the
2052904Sshin *    documentation and/or other materials provided with the distribution.
2152904Sshin * 3. All advertising materials mentioning features or use of this software
2252904Sshin *    must display the following acknowledgement:
2352904Sshin *	This product includes software developed by the University of
2452904Sshin *	California, Berkeley and its contributors.
2552904Sshin * 4. Neither the name of the University nor the names of its contributors
2652904Sshin *    may be used to endorse or promote products derived from this software
2752904Sshin *    without specific prior written permission.
2852904Sshin *
2952904Sshin * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3052904Sshin * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3152904Sshin * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3252904Sshin * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33139826Simp * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3452904Sshin * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3552904Sshin * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3652904Sshin * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3752904Sshin * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3852904Sshin * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3952904Sshin * SUCH DAMAGE.
4052904Sshin *
4152904Sshin *	from:	@(#)pmap.c	7.7 (Berkeley)	5/12/91
4252904Sshin */
4352904Sshin/*-
4452904Sshin * Copyright (c) 2003 Networks Associates Technology, Inc.
4552904Sshin * All rights reserved.
4652904Sshin *
4752904Sshin * This software was developed for the FreeBSD Project by Jake Burkholder,
4852904Sshin * Safeport Network Services, and Network Associates Laboratories, the
4952904Sshin * Security Research Division of Network Associates, Inc. under
5052904Sshin * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
5152904Sshin * CHATS research program.
5252904Sshin *
5352904Sshin * Redistribution and use in source and binary forms, with or without
5452904Sshin * modification, are permitted provided that the following conditions
5552904Sshin * are met:
5652904Sshin * 1. Redistributions of source code must retain the above copyright
5752904Sshin *    notice, this list of conditions and the following disclaimer.
5852904Sshin * 2. Redistributions in binary form must reproduce the above copyright
5952904Sshin *    notice, this list of conditions and the following disclaimer in the
6052904Sshin *    documentation and/or other materials provided with the distribution.
6152904Sshin *
6252904Sshin * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
6352904Sshin * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
6462587Sitojun * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
6578064Sume * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
6657120Sshin * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
6757120Sshin * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
6862587Sitojun * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
6962587Sitojun * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
7062587Sitojun * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
7152904Sshin * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
7252904Sshin * SUCH DAMAGE.
7378064Sume */
7478064Sume
7552904Sshin#include <sys/cdefs.h>
7662587Sitojun__FBSDID("$FreeBSD: head/sys/i386/i386/pmap.c 121823 2003-10-31 21:02:04Z jhb $");
7778064Sume
7852904Sshin/*
7952904Sshin *	Manages physical address maps.
8052904Sshin *
8152904Sshin *	In addition to hardware address maps, this
8252904Sshin *	module is called upon to provide software-use-only
8352904Sshin *	maps which may or may not be stored in the same
8452904Sshin *	form as hardware maps.  These pseudo-maps are
8552904Sshin *	used to store intermediate results from copy
8652904Sshin *	operations to and from address spaces.
8752904Sshin *
8862587Sitojun *	Since the information managed by this module is
8952904Sshin *	also stored by the logical address mapping module,
9052904Sshin *	this module may throw away valid virtual-to-physical
9152904Sshin *	mappings at almost any time.  However, invalidations
9252904Sshin *	of virtual-to-physical mappings must be done as
9352904Sshin *	requested.
9452904Sshin *
9552904Sshin *	In order to cope with hardware architectures which
9652904Sshin *	make virtual-to-physical map invalidates expensive,
9752904Sshin *	this module may delay invalidate or reduced protection
9852904Sshin *	operations until such time as they are actually
9952904Sshin *	necessary.  This module is given full information as
10052904Sshin *	to which processors are currently using which maps,
10152904Sshin *	and to when physical maps must be made correct.
10252904Sshin */
10352904Sshin
10452904Sshin#include "opt_pmap.h"
10552904Sshin#include "opt_msgbuf.h"
10697181Smike#include "opt_kstack_pages.h"
10752904Sshin
10852904Sshin#include <sys/param.h>
10952904Sshin#include <sys/systm.h>
11052904Sshin#include <sys/kernel.h>
11152904Sshin#include <sys/lock.h>
11297181Smike#include <sys/mman.h>
11352904Sshin#include <sys/msgbuf.h>
11452904Sshin#include <sys/mutex.h>
11552904Sshin#include <sys/proc.h>
11652904Sshin#include <sys/sx.h>
11752904Sshin#include <sys/user.h>
11852904Sshin#include <sys/vmmeter.h>
11997181Smike#include <sys/sysctl.h>
12097181Smike#ifdef SMP
12197181Smike#include <sys/smp.h>
12252904Sshin#endif
12352904Sshin
12452904Sshin#include <vm/vm.h>
12562587Sitojun#include <vm/vm_param.h>
12695023Ssuz#include <vm/vm_kern.h>
12762587Sitojun#include <vm/vm_page.h>
12862587Sitojun#include <vm/vm_map.h>
12962587Sitojun#include <vm/vm_object.h>
13052904Sshin#include <vm/vm_extern.h>
13152904Sshin#include <vm/vm_pageout.h>
13262587Sitojun#include <vm/vm_pager.h>
13352904Sshin#include <vm/uma.h>
13452904Sshin
13597181Smike#include <machine/cpu.h>
13697181Smike#include <machine/cputypes.h>
13797181Smike#include <machine/md_var.h>
13897181Smike#include <machine/specialreg.h>
13952904Sshin#if defined(SMP) || defined(APIC_IO)
14052904Sshin#include <machine/smp.h>
14197181Smike#include <machine/apic.h>
14262587Sitojun#include <machine/segments.h>
14352904Sshin#include <machine/tss.h>
14497181Smike#endif /* SMP || APIC_IO */
14552904Sshin
146100503Sume#define PMAP_KEEP_PDIRS
14797181Smike#ifndef PMAP_SHPGPERPROC
14897181Smike#define PMAP_SHPGPERPROC 200
14997181Smike#endif
15062587Sitojun
15197181Smike#if defined(DIAGNOSTIC)
15252904Sshin#define PMAP_DIAGNOSTIC
15352904Sshin#endif
15452904Sshin
15552904Sshin#define MINPV 2048
15652904Sshin
15795023Ssuz#if !defined(PMAP_DIAGNOSTIC)
15862587Sitojun#define PMAP_INLINE __inline
15962587Sitojun#else
16052904Sshin#define PMAP_INLINE
16162587Sitojun#endif
16252904Sshin
16362587Sitojun/*
16452904Sshin * Get PDEs and PTEs for user/kernel address space
16562587Sitojun */
16652904Sshin#define	pmap_pde(m, v)	(&((m)->pm_pdir[(vm_offset_t)(v) >> PDRSHIFT]))
16752904Sshin#define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
16852904Sshin
16952904Sshin#define pmap_pde_v(pte)		((*(int *)pte & PG_V) != 0)
17078064Sume#define pmap_pte_w(pte)		((*(int *)pte & PG_W) != 0)
17178064Sume#define pmap_pte_m(pte)		((*(int *)pte & PG_M) != 0)
17252904Sshin#define pmap_pte_u(pte)		((*(int *)pte & PG_A) != 0)
17352904Sshin#define pmap_pte_v(pte)		((*(int *)pte & PG_V) != 0)
17452904Sshin
17552904Sshin#define pmap_pte_set_w(pte, v) ((v)?(*(int *)pte |= PG_W):(*(int *)pte &= ~PG_W))
17652904Sshin#define pmap_pte_set_prot(pte, v) ((*(int *)pte &= ~PG_PROT), (*(int *)pte |= (v)))
17752904Sshin
17852904Sshin/*
17952904Sshin * Given a map and a machine independent protection code,
18052904Sshin * convert to a vax protection code.
18152904Sshin */
18295023Ssuz#define pte_prot(m, p)	(protection_codes[p])
18397181Smikestatic int protection_codes[8];
18462587Sitojun
18562587Sitojunstruct pmap kernel_pmap_store;
18662587SitojunLIST_HEAD(pmaplist, pmap);
18762587Sitojunstatic struct pmaplist allpmaps;
18862587Sitojunstatic struct mtx allpmaps_lock;
18962587Sitojun#ifdef SMP
19062587Sitojunstatic struct mtx lazypmap_lock;
19162587Sitojun#endif
19297181Smike
19362587Sitojunvm_paddr_t avail_start;	/* PA of first available physical page */
19462587Sitojunvm_paddr_t avail_end;	/* PA of last available physical page */
19562587Sitojunvm_offset_t virtual_avail;	/* VA of first avail page (after kernel bss) */
19662587Sitojunvm_offset_t virtual_end;	/* VA of last avail page (end of kernel AS) */
19762587Sitojunstatic boolean_t pmap_initialized = FALSE;	/* Has pmap_init completed? */
19862587Sitojunint pgeflag = 0;		/* PG_G or-in */
19962587Sitojunint pseflag = 0;		/* PG_PS or-in */
20062587Sitojun
20152904Sshinstatic int nkpt;
20252904Sshinvm_offset_t kernel_vm_end;
20352904Sshinextern u_int32_t KERNend;
20452904Sshin
20552904Sshin#ifdef PAE
20652904Sshinstatic uma_zone_t pdptzone;
20797181Smike#endif
20862587Sitojun
20952904Sshin/*
21052904Sshin * Data for the pv entry allocation mechanism
21162587Sitojun */
21252904Sshinstatic uma_zone_t pvzone;
21352904Sshinstatic struct vm_object pvzone_obj;
21462587Sitojunstatic int pv_entry_count = 0, pv_entry_max = 0, pv_entry_high_water = 0;
21552904Sshinint pmap_pagedaemon_waken;
21652904Sshin
217121315Sume/*
218121315Sume * All those kernel PT submaps that BSD is so fond of
219121315Sume */
22062587Sitojunpt_entry_t *CMAP1 = 0;
22152904Sshinstatic pt_entry_t *CMAP2, *CMAP3, *ptmmap;
22252904Sshincaddr_t CADDR1 = 0, ptvmmap = 0;
22362587Sitojunstatic caddr_t CADDR2, CADDR3;
22452904Sshinstatic struct mtx CMAPCADDR12_lock;
22552904Sshinstatic pt_entry_t *msgbufmap;
22697181Smikestruct msgbuf *msgbufp = 0;
22752904Sshin
22852904Sshin/*
22952904Sshin * Crashdump maps.
23097181Smike */
23152904Sshinstatic pt_entry_t *pt_crashdumpmap;
23252904Sshinstatic caddr_t crashdumpmap;
23352904Sshin
23497181Smike#ifdef SMP
23552904Sshinextern pt_entry_t *SMPpt;
23652904Sshin#endif
23752904Sshinstatic pt_entry_t *PMAP1 = 0;
23853877Sitojunstatic pt_entry_t *PADDR1 = 0;
23953877Sitojun
24053877Sitojunstatic PMAP_INLINE void	free_pv_entry(pv_entry_t pv);
24152904Sshinstatic pv_entry_t get_pv_entry(void);
24253877Sitojunstatic void	i386_protection_init(void);
24362587Sitojunstatic void	pmap_clear_ptes(vm_page_t m, int bit)
24462587Sitojun    __always_inline;
24553877Sitojun
24697181Smikestatic int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva);
24762587Sitojunstatic void pmap_remove_page(struct pmap *pmap, vm_offset_t va);
24862587Sitojunstatic int pmap_remove_entry(struct pmap *pmap, vm_page_t m,
24953877Sitojun					vm_offset_t va);
25097181Smikestatic void pmap_insert_entry(pmap_t pmap, vm_offset_t va,
25152904Sshin		vm_page_t mpte, vm_page_t m);
25278064Sume
25378064Sumestatic vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va);
25478064Sume
25578064Sumestatic vm_page_t _pmap_allocpte(pmap_t pmap, unsigned ptepindex);
25678064Sumestatic int pmap_unuse_pt(pmap_t, vm_offset_t, vm_page_t);
25778064Sumestatic vm_offset_t pmap_kmem_choose(vm_offset_t addr);
25878064Sumestatic void *pmap_pv_allocf(uma_zone_t zone, int bytes, u_int8_t *flags, int wait);
25978064Sume#ifdef PAE
26052904Sshinstatic void *pmap_pdpt_allocf(uma_zone_t zone, int bytes, u_int8_t *flags, int wait);
26152904Sshin#endif
26252904Sshin
26362587SitojunCTASSERT(1 << PDESHIFT == sizeof(pd_entry_t));
26478064SumeCTASSERT(1 << PTESHIFT == sizeof(pt_entry_t));
26578064Sume
26678064Sume/*
26778064Sume * Move the kernel virtual free pointer to the next
26852904Sshin * 4MB.  This is used to help improve performance
26952904Sshin * by using a large (4MB) page for much of the kernel
27052904Sshin * (.text, .data, .bss)
27152904Sshin */
27262587Sitojunstatic vm_offset_t
27378064Sumepmap_kmem_choose(vm_offset_t addr)
27478064Sume{
27578064Sume	vm_offset_t newaddr = addr;
27678064Sume
27752904Sshin#ifndef DISABLE_PSE
27852904Sshin	if (cpu_feature & CPUID_PSE)
27952904Sshin		newaddr = (addr + PDRMASK) & ~PDRMASK;
28052904Sshin#endif
28162587Sitojun	return newaddr;
28278064Sume}
28378064Sume
28478064Sume/*
28578064Sume *	Bootstrap the system enough to run with virtual memory.
28678064Sume *
28752904Sshin *	On the i386 this is called after mapping has already been enabled
28852904Sshin *	and just syncs the pmap module with what has already been done.
28952904Sshin *	[We can't call it easily with mapping off since the kernel is not
29052904Sshin *	mapped with PA == VA, hence we would have to relocate every address
29162587Sitojun *	from the linked base (virtual) address "KERNBASE" to the actual
29278064Sume *	(physical) address starting relative to 0]
29378064Sume */
29478064Sumevoid
29552904Sshinpmap_bootstrap(firstaddr, loadaddr)
29652904Sshin	vm_paddr_t firstaddr;
29752904Sshin	vm_paddr_t loadaddr;
29852904Sshin{
29952904Sshin	vm_offset_t va;
30095023Ssuz	pt_entry_t *pte;
30162587Sitojun	int i;
302121315Sume
30362587Sitojun	avail_start = firstaddr;
30462587Sitojun
30562587Sitojun	/*
30662587Sitojun	 * XXX The calculation of virtual_avail is wrong. It's NKPT*PAGE_SIZE too
30752904Sshin	 * large. It should instead be correctly calculated in locore.s and
30862587Sitojun	 * not based on 'first' (which is a physical address, not a virtual
309121315Sume	 * address, for the start of unused physical memory). The kernel
31062587Sitojun	 * page tables are NOT double mapped and thus should not be included
31162587Sitojun	 * in this calculation.
31262587Sitojun	 */
31362587Sitojun	virtual_avail = (vm_offset_t) KERNBASE + firstaddr;
31452904Sshin	virtual_avail = pmap_kmem_choose(virtual_avail);
31552904Sshin
31652904Sshin	virtual_end = VM_MAX_KERNEL_ADDRESS;
31752904Sshin
31852904Sshin	/*
31952904Sshin	 * Initialize protection array.
32062587Sitojun	 */
32152904Sshin	i386_protection_init();
32262587Sitojun
32352904Sshin	/*
32452904Sshin	 * Initialize the kernel pmap (which is statically allocated).
32552904Sshin	 */
32652904Sshin	kernel_pmap->pm_pdir = (pd_entry_t *) (KERNBASE + (u_int)IdlePTD);
32752904Sshin#ifdef PAE
32852904Sshin	kernel_pmap->pm_pdpt = (pdpt_entry_t *) (KERNBASE + (u_int)IdlePDPT);
32952904Sshin#endif
33095023Ssuz	kernel_pmap->pm_active = -1;	/* don't allow deactivation */
33162587Sitojun	TAILQ_INIT(&kernel_pmap->pm_pvlist);
33252904Sshin	LIST_INIT(&allpmaps);
33362587Sitojun#ifdef SMP
33452904Sshin	mtx_init(&lazypmap_lock, "lazypmap", NULL, MTX_SPIN);
33552904Sshin#endif
33652904Sshin	mtx_init(&allpmaps_lock, "allpmaps", NULL, MTX_SPIN);
33752904Sshin	mtx_lock_spin(&allpmaps_lock);
33852904Sshin	LIST_INSERT_HEAD(&allpmaps, kernel_pmap, pm_list);
33995023Ssuz	mtx_unlock_spin(&allpmaps_lock);
34062587Sitojun	nkpt = NKPT;
34152904Sshin
34252904Sshin	/*
343121315Sume	 * Reserve some special page table entries/VA space for temporary
344121315Sume	 * mapping of pages.
345121315Sume	 */
34662587Sitojun#define	SYSMAP(c, p, v, n)	\
34752904Sshin	v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
34852904Sshin
34962587Sitojun	va = virtual_avail;
35052904Sshin	pte = vtopte(va);
35152904Sshin
35262587Sitojun	/*
35352904Sshin	 * CMAP1/CMAP2 are used for zeroing and copying pages.
35452904Sshin	 * CMAP3 is used for the idle process page zeroing.
35562587Sitojun	 */
35652904Sshin	SYSMAP(caddr_t, CMAP1, CADDR1, 1)
35752904Sshin	SYSMAP(caddr_t, CMAP2, CADDR2, 1)
35852904Sshin	SYSMAP(caddr_t, CMAP3, CADDR3, 1)
35962587Sitojun	*CMAP3 = 0;
36052904Sshin
36152904Sshin	mtx_init(&CMAPCADDR12_lock, "CMAPCADDR12", NULL, MTX_DEF);
36262587Sitojun
36352904Sshin	/*
36452904Sshin	 * Crashdump maps.
36562587Sitojun	 */
36652904Sshin	SYSMAP(caddr_t, pt_crashdumpmap, crashdumpmap, MAXDUMPPGS);
36752904Sshin
36862587Sitojun	/*
36952904Sshin	 * ptvmmap is used for reading arbitrary physical pages via /dev/mem.
37052904Sshin	 * XXX ptmmap is not used.
37162587Sitojun	 */
37252904Sshin	SYSMAP(caddr_t, ptmmap, ptvmmap, 1)
37352904Sshin
37452904Sshin	/*
37552904Sshin	 * msgbufp is used to map the system message buffer.
37695023Ssuz	 * XXX msgbufmap is not used.
37778064Sume	 */
37852904Sshin	SYSMAP(struct msgbuf *, msgbufmap, msgbufp,
37952904Sshin	       atop(round_page(MSGBUF_SIZE)))
38062587Sitojun
38152904Sshin	/*
38252904Sshin	 * ptemap is used for pmap_pte_quick
38352904Sshin	 */
38478064Sume	SYSMAP(pt_entry_t *, PMAP1, PADDR1, 1);
38578064Sume
38678064Sume	virtual_avail = va;
38778064Sume
38878064Sume	*CMAP1 = *CMAP2 = 0;
38978064Sume	for (i = 0; i < NKPT; i++)
39078064Sume		PTD[i] = 0;
39178064Sume
39252904Sshin	/* Turn on PG_G on kernel page(s) */
39352904Sshin	pmap_set_pg();
39452904Sshin
39597181Smike#ifdef SMP
39652904Sshin	if (cpu_apic_address == 0)
39752904Sshin		panic("pmap_bootstrap: no local apic! (non-SMP hardware?)");
39852904Sshin
39952904Sshin	/* local apic is mapped on last page */
40052904Sshin	SMPpt[NPTEPG - 1] = (pt_entry_t)(PG_V | PG_RW | PG_N | pgeflag |
40152904Sshin	    (cpu_apic_address & PG_FRAME));
40252904Sshin#endif
40352904Sshin	invltlb();
40452904Sshin}
40552904Sshin
40652904Sshin/*
40762587Sitojun * Set PG_G on kernel pages.  Only the BSP calls this when SMP is turned on.
40862587Sitojun */
40962587Sitojunvoid
41062587Sitojunpmap_set_pg(void)
41162587Sitojun{
41262587Sitojun	pd_entry_t pdir;
41362587Sitojun	pt_entry_t *pte;
41462587Sitojun	vm_offset_t va, endva;
415121472Sume	int i;
416121472Sume
417121472Sume	if (pgeflag == 0)
418121472Sume		return;
419121472Sume
420121472Sume	i = KERNLOAD/NBPDR;
42162587Sitojun	endva = KERNBASE + KERNend;
42262587Sitojun
42378064Sume	if (pseflag) {
424121472Sume		va = KERNBASE + KERNLOAD;
425121472Sume		while (va  < endva) {
426121472Sume			pdir = kernel_pmap->pm_pdir[KPTDI+i];
427121472Sume			pdir |= pgeflag;
428121472Sume			kernel_pmap->pm_pdir[KPTDI+i] = PTD[KPTDI+i] = pdir;
429121472Sume			invltlb();	/* Play it safe, invltlb() every time */
430121472Sume			i++;
431121472Sume			va += NBPDR;
432121472Sume		}
43378064Sume	} else {
43462587Sitojun		va = (vm_offset_t)btext;
435121472Sume		while (va < endva) {
43678064Sume			pte = vtopte(va);
43778064Sume			if (*pte)
43878064Sume				*pte |= pgeflag;
43952904Sshin			invltlb();	/* Play it safe, invltlb() every time */
44095023Ssuz			va += PAGE_SIZE;
44162587Sitojun		}
44278064Sume	}
44362587Sitojun}
44452904Sshin
44595023Ssuzstatic void *
44662587Sitojunpmap_pv_allocf(uma_zone_t zone, int bytes, u_int8_t *flags, int wait)
44762587Sitojun{
44862587Sitojun	*flags = UMA_SLAB_PRIV;
44962587Sitojun	return (void *)kmem_alloc(kernel_map, bytes);
45062587Sitojun}
45178064Sume
45278064Sume#ifdef PAE
453121472Sumestatic void *
454121472Sumepmap_pdpt_allocf(uma_zone_t zone, int bytes, u_int8_t *flags, int wait)
455121472Sume{
456121472Sume	*flags = UMA_SLAB_PRIV;
457121472Sume	return (contigmalloc(PAGE_SIZE, NULL, 0, 0x0ULL, 0xffffffffULL, 1, 0));
458121472Sume}
459121472Sume#endif
460121472Sume
461121472Sume/*
462121472Sume *	Initialize the pmap module.
463121472Sume *	Called by vm_init, to initialize any structures that the pmap
464121472Sume *	system needs to map virtual memory.
465121472Sume *	pmap_init has been enhanced to support in a fairly consistant
466121472Sume *	way, discontiguous physical memory.
467121472Sume */
468121472Sumevoid
469121472Sumepmap_init(phys_start, phys_end)
470121472Sume	vm_paddr_t phys_start, phys_end;
471121472Sume{
472121472Sume	int i;
473121472Sume	int initial_pvs;
474121472Sume
475121472Sume	/*
476121472Sume	 * Allocate memory for random pmap data structures.  Includes the
477121472Sume	 * pv_head_table.
478121472Sume	 */
479121472Sume
480121472Sume	for(i = 0; i < vm_page_array_size; i++) {
481121472Sume		vm_page_t m;
482121472Sume
483121472Sume		m = &vm_page_array[i];
484121472Sume		TAILQ_INIT(&m->md.pv_list);
485121472Sume		m->md.pv_list_count = 0;
486121472Sume	}
487121472Sume
488121472Sume	/*
489121472Sume	 * init the pv free list
490121472Sume	 */
491121472Sume	initial_pvs = vm_page_array_size;
492121472Sume	if (initial_pvs < MINPV)
493121472Sume		initial_pvs = MINPV;
494121472Sume	pvzone = uma_zcreate("PV ENTRY", sizeof (struct pv_entry), NULL, NULL,
495121472Sume	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_VM | UMA_ZONE_NOFREE);
496121472Sume	uma_zone_set_allocf(pvzone, pmap_pv_allocf);
497121472Sume	uma_prealloc(pvzone, initial_pvs);
49865124Sitojun
49952904Sshin#ifdef PAE
50062587Sitojun	pdptzone = uma_zcreate("PDPT", NPGPTD * sizeof(pdpt_entry_t), NULL,
50162587Sitojun	    NULL, NULL, NULL, (NPGPTD * sizeof(pdpt_entry_t)) - 1,
50262587Sitojun	    UMA_ZONE_VM | UMA_ZONE_NOFREE);
50352904Sshin	uma_zone_set_allocf(pdptzone, pmap_pdpt_allocf);
50452904Sshin#endif
50552904Sshin
50652904Sshin	/*
50795023Ssuz	 * Now it is safe to enable pv_table recording.
50895023Ssuz	 */
50952904Sshin	pmap_initialized = TRUE;
51052904Sshin}
51152904Sshin
51252904Sshin/*
51352904Sshin * Initialize the address space (zone) for the pv_entries.  Set a
51462587Sitojun * high water mark so that the system can recover from excessive
51562587Sitojun * numbers of pv entries.
51652904Sshin */
51752904Sshinvoid
51852904Sshinpmap_init2()
51952904Sshin{
52052904Sshin	int shpgperproc = PMAP_SHPGPERPROC;
52152904Sshin
52262587Sitojun	TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
52362587Sitojun	pv_entry_max = shpgperproc * maxproc + vm_page_array_size;
52452904Sshin	TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
52552904Sshin	pv_entry_high_water = 9 * (pv_entry_max / 10);
52652904Sshin	uma_zone_set_obj(pvzone, &pvzone_obj, pv_entry_max);
527121472Sume}
528121472Sume
529121472Sume
530121472Sume/***************************************************
531121569Sume * Low level helper routines.....
532121472Sume ***************************************************/
533121472Sume
534121472Sume#if defined(PMAP_DIAGNOSTIC)
53552904Sshin
53652904Sshin/*
53752904Sshin * This code checks for non-writeable/modified pages.
53852904Sshin * This should be an invalid condition.
53952904Sshin */
54052904Sshinstatic int
54152904Sshinpmap_nw_modified(pt_entry_t ptea)
542121472Sume{
54352904Sshin	int pte;
54452904Sshin
54552904Sshin	pte = (int) ptea;
54652904Sshin
54752904Sshin	if ((pte & (PG_M|PG_RW)) == PG_M)
54852904Sshin		return 1;
54962587Sitojun	else
55052904Sshin		return 0;
55152904Sshin}
55252904Sshin#endif
55352904Sshin
55462587Sitojun
55562587Sitojun/*
55662587Sitojun * this routine defines the region(s) of memory that should
55752904Sshin * not be tested for the modified bit.
55862587Sitojun */
55952904Sshinstatic PMAP_INLINE int
56062587Sitojunpmap_track_modified(vm_offset_t va)
56162587Sitojun{
56262587Sitojun	if ((va < kmi.clean_sva) || (va >= kmi.clean_eva))
56362587Sitojun		return 1;
56462587Sitojun	else
56562587Sitojun		return 0;
56662587Sitojun}
56762587Sitojun
56862587Sitojun#ifdef I386_CPU
56962587Sitojun/*
57062587Sitojun * i386 only has "invalidate everything" and no SMP to worry about.
57162587Sitojun */
57262587SitojunPMAP_INLINE void
57362587Sitojunpmap_invalidate_page(pmap_t pmap, vm_offset_t va)
57462587Sitojun{
57562587Sitojun
57662587Sitojun	if (pmap == kernel_pmap || pmap->pm_active)
57762587Sitojun		invltlb();
57895023Ssuz}
57962587Sitojun
58062604SitojunPMAP_INLINE void
58178064Sumepmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
58262604Sitojun{
58362604Sitojun
58462604Sitojun	if (pmap == kernel_pmap || pmap->pm_active)
58578064Sume		invltlb();
58678064Sume}
58778064Sume
58878064SumePMAP_INLINE void
58978064Sumepmap_invalidate_all(pmap_t pmap)
59078064Sume{
591122077Sume
592121742Sume	if (pmap == kernel_pmap || pmap->pm_active)
593121742Sume		invltlb();
594121345Sume}
595121345Sume#else /* !I386_CPU */
59652904Sshin#ifdef SMP
59765124Sitojun/*
598121345Sume * For SMP, these functions have to use the IPI mechanism for coherence.
599121472Sume */
60078064Sumevoid
60153541Sshinpmap_invalidate_page(pmap_t pmap, vm_offset_t va)
60253541Sshin{
60353541Sshin	u_int cpumask;
60478064Sume	u_int other_cpus;
60578064Sume
60678064Sume	critical_enter();
60778064Sume	/*
60853541Sshin	 * We need to disable interrupt preemption but MUST NOT have
60952904Sshin	 * interrupts disabled here.
61078064Sume	 * XXX we may need to hold schedlock to get a coherent pm_active
61152904Sshin	 */
61262587Sitojun	if (pmap == kernel_pmap || pmap->pm_active == all_cpus) {
61352904Sshin		invlpg(va);
61452904Sshin		smp_invlpg(va);
61552904Sshin	} else {
61678064Sume		cpumask = PCPU_GET(cpumask);
61778064Sume		other_cpus = PCPU_GET(other_cpus);
61892700Sdarrenr		if (pmap->pm_active & cpumask)
61952904Sshin			invlpg(va);
62052904Sshin		if (pmap->pm_active & other_cpus)
62152904Sshin			smp_masked_invlpg(pmap->pm_active & other_cpus, va);
62252904Sshin	}
62352904Sshin	critical_exit();
62452904Sshin}
62552904Sshin
626121742Sumevoid
62752904Sshinpmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
62878064Sume{
62978064Sume	u_int cpumask;
63078064Sume	u_int other_cpus;
63183934Sbrooks	vm_offset_t addr;
63283934Sbrooks
63352904Sshin	critical_enter();
63452904Sshin	/*
635102227Smike	 * We need to disable interrupt preemption but MUST NOT have
636102227Smike	 * interrupts disabled here.
637102227Smike	 * XXX we may need to hold schedlock to get a coherent pm_active
63897181Smike	 */
63997181Smike	if (pmap == kernel_pmap || pmap->pm_active == all_cpus) {
640121498Sume		for (addr = sva; addr < eva; addr += PAGE_SIZE)
641121498Sume			invlpg(addr);
642121498Sume		smp_invlpg_range(sva, eva);
643121498Sume	} else {
644121498Sume		cpumask = PCPU_GET(cpumask);
645121472Sume		other_cpus = PCPU_GET(other_cpus);
646121472Sume		if (pmap->pm_active & cpumask)
64752904Sshin			for (addr = sva; addr < eva; addr += PAGE_SIZE)
64852904Sshin				invlpg(addr);
64952904Sshin		if (pmap->pm_active & other_cpus)
65078064Sume			smp_masked_invlpg_range(pmap->pm_active & other_cpus,
65178064Sume			    sva, eva);
65297181Smike	}
65378064Sume	critical_exit();
654121499Sume}
655121499Sume
656121499Sumevoid
65752904Sshinpmap_invalidate_all(pmap_t pmap)
65878064Sume{
65978064Sume	u_int cpumask;
66078064Sume	u_int other_cpus;
661121472Sume
66278064Sume	critical_enter();
66378064Sume	/*
66478064Sume	 * We need to disable interrupt preemption but MUST NOT have
66578064Sume	 * interrupts disabled here.
66678064Sume	 * XXX we may need to hold schedlock to get a coherent pm_active
66778064Sume	 */
66878064Sume	if (pmap == kernel_pmap || pmap->pm_active == all_cpus) {
66978064Sume		invltlb();
670121472Sume		smp_invltlb();
671121499Sume	} else {
672121499Sume		cpumask = PCPU_GET(cpumask);
673121472Sume		other_cpus = PCPU_GET(other_cpus);
674121472Sume		if (pmap->pm_active & cpumask)
67578064Sume			invltlb();
676121499Sume		if (pmap->pm_active & other_cpus)
677121472Sume			smp_masked_invltlb(pmap->pm_active & other_cpus);
678121499Sume	}
679121472Sume	critical_exit();
680121472Sume}
681121472Sume#else /* !SMP */
682121472Sume/*
68378064Sume * Normal, non-SMP, 486+ invalidation functions.
68478064Sume * We inline these within pmap.c for speed.
68578064Sume */
68678064SumePMAP_INLINE void
68752904Sshinpmap_invalidate_page(pmap_t pmap, vm_offset_t va)
68852904Sshin{
68997181Smike
69097181Smike	if (pmap == kernel_pmap || pmap->pm_active)
69152904Sshin		invlpg(va);
692}
693
694PMAP_INLINE void
695pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
696{
697	vm_offset_t addr;
698
699	if (pmap == kernel_pmap || pmap->pm_active)
700		for (addr = sva; addr < eva; addr += PAGE_SIZE)
701			invlpg(addr);
702}
703
704PMAP_INLINE void
705pmap_invalidate_all(pmap_t pmap)
706{
707
708	if (pmap == kernel_pmap || pmap->pm_active)
709		invltlb();
710}
711#endif /* !SMP */
712#endif /* !I386_CPU */
713
714/*
715 * Are we current address space or kernel?  N.B. We return FALSE when
716 * a pmap's page table is in use because a kernel thread is borrowing
717 * it.  The borrowed page table can change spontaneously, making any
718 * dependence on its continued use subject to a race condition.
719 */
720static int
721pmap_is_current(pmap_t pmap)
722{
723	return (pmap == kernel_pmap ||
724		(pmap == vmspace_pmap(curthread->td_proc->p_vmspace) &&
725	    (pmap->pm_pdir[PTDPTDI] & PG_FRAME) == (PTDpde[0] & PG_FRAME)));
726}
727
728/*
729 * Super fast pmap_pte routine best used when scanning
730 * the pv lists.  This eliminates many coarse-grained
731 * invltlb calls.  Note that many of the pv list
732 * scans are across different pmaps.  It is very wasteful
733 * to do an entire invltlb for checking a single mapping.
734 */
735pt_entry_t *
736pmap_pte_quick(pmap, va)
737	register pmap_t pmap;
738	vm_offset_t va;
739{
740	pd_entry_t newpf;
741	pd_entry_t *pde;
742
743	pde = pmap_pde(pmap, va);
744	if (*pde & PG_PS)
745		return (pde);
746	if (*pde != 0) {
747		/* are we current address space or kernel? */
748		if (pmap_is_current(pmap))
749			return vtopte(va);
750		newpf = *pde & PG_FRAME;
751		if (((*PMAP1) & PG_FRAME) != newpf) {
752			*PMAP1 = newpf | PG_RW | PG_V;
753			pmap_invalidate_page(kernel_pmap, (vm_offset_t)PADDR1);
754		}
755		return PADDR1 + (i386_btop(va) & (NPTEPG - 1));
756	}
757	return (0);
758}
759
760/*
761 *	Routine:	pmap_extract
762 *	Function:
763 *		Extract the physical page address associated
764 *		with the given map/virtual_address pair.
765 */
766vm_paddr_t
767pmap_extract(pmap, va)
768	register pmap_t pmap;
769	vm_offset_t va;
770{
771	vm_paddr_t rtval;
772	pt_entry_t *pte;
773	pd_entry_t pde;
774
775	if (pmap == 0)
776		return 0;
777	pde = pmap->pm_pdir[va >> PDRSHIFT];
778	if (pde != 0) {
779		if ((pde & PG_PS) != 0) {
780			rtval = (pde & ~PDRMASK) | (va & PDRMASK);
781			return rtval;
782		}
783		pte = pmap_pte_quick(pmap, va);
784		rtval = ((*pte & PG_FRAME) | (va & PAGE_MASK));
785		return rtval;
786	}
787	return 0;
788
789}
790
791/*
792 *	Routine:	pmap_extract_and_hold
793 *	Function:
794 *		Atomically extract and hold the physical page
795 *		with the given pmap and virtual address pair
796 *		if that mapping permits the given protection.
797 */
798vm_page_t
799pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
800{
801	vm_paddr_t pa;
802	vm_page_t m;
803
804	m = NULL;
805	mtx_lock(&Giant);
806	if ((pa = pmap_extract(pmap, va)) != 0) {
807		m = PHYS_TO_VM_PAGE(pa);
808		vm_page_lock_queues();
809		vm_page_hold(m);
810		vm_page_unlock_queues();
811	}
812	mtx_unlock(&Giant);
813	return (m);
814}
815
816/***************************************************
817 * Low level mapping routines.....
818 ***************************************************/
819
820/*
821 * Add a wired page to the kva.
822 * Note: not SMP coherent.
823 */
824PMAP_INLINE void
825pmap_kenter(vm_offset_t va, vm_paddr_t pa)
826{
827	pt_entry_t *pte;
828
829	pte = vtopte(va);
830	pte_store(pte, pa | PG_RW | PG_V | pgeflag);
831}
832
833/*
834 * Remove a page from the kernel pagetables.
835 * Note: not SMP coherent.
836 */
837PMAP_INLINE void
838pmap_kremove(vm_offset_t va)
839{
840	pt_entry_t *pte;
841
842	pte = vtopte(va);
843	pte_clear(pte);
844}
845
846/*
847 *	Used to map a range of physical addresses into kernel
848 *	virtual address space.
849 *
850 *	The value passed in '*virt' is a suggested virtual address for
851 *	the mapping. Architectures which can support a direct-mapped
852 *	physical to virtual region can return the appropriate address
853 *	within that region, leaving '*virt' unchanged. Other
854 *	architectures should map the pages starting at '*virt' and
855 *	update '*virt' with the first usable address after the mapped
856 *	region.
857 */
858vm_offset_t
859pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
860{
861	vm_offset_t va, sva;
862
863	va = sva = *virt;
864	while (start < end) {
865		pmap_kenter(va, start);
866		va += PAGE_SIZE;
867		start += PAGE_SIZE;
868	}
869	pmap_invalidate_range(kernel_pmap, sva, va);
870	*virt = va;
871	return (sva);
872}
873
874
875/*
876 * Add a list of wired pages to the kva
877 * this routine is only used for temporary
878 * kernel mappings that do not need to have
879 * page modification or references recorded.
880 * Note that old mappings are simply written
881 * over.  The page *must* be wired.
882 * Note: SMP coherent.  Uses a ranged shootdown IPI.
883 */
884void
885pmap_qenter(vm_offset_t sva, vm_page_t *m, int count)
886{
887	vm_offset_t va;
888
889	va = sva;
890	while (count-- > 0) {
891		pmap_kenter(va, VM_PAGE_TO_PHYS(*m));
892		va += PAGE_SIZE;
893		m++;
894	}
895	pmap_invalidate_range(kernel_pmap, sva, va);
896}
897
898/*
899 * This routine tears out page mappings from the
900 * kernel -- it is meant only for temporary mappings.
901 * Note: SMP coherent.  Uses a ranged shootdown IPI.
902 */
903void
904pmap_qremove(vm_offset_t sva, int count)
905{
906	vm_offset_t va;
907
908	va = sva;
909	while (count-- > 0) {
910		pmap_kremove(va);
911		va += PAGE_SIZE;
912	}
913	pmap_invalidate_range(kernel_pmap, sva, va);
914}
915
916/***************************************************
917 * Page table page management routines.....
918 ***************************************************/
919
920/*
921 * This routine unholds page table pages, and if the hold count
922 * drops to zero, then it decrements the wire count.
923 */
924static int
925_pmap_unwire_pte_hold(pmap_t pmap, vm_page_t m)
926{
927
928	while (vm_page_sleep_if_busy(m, FALSE, "pmuwpt"))
929		vm_page_lock_queues();
930
931	if (m->hold_count == 0) {
932		vm_offset_t pteva;
933		/*
934		 * unmap the page table page
935		 */
936		pmap->pm_pdir[m->pindex] = 0;
937		--pmap->pm_stats.resident_count;
938		/*
939		 * We never unwire a kernel page table page, making a
940		 * check for the kernel_pmap unnecessary.
941		 */
942		if ((pmap->pm_pdir[PTDPTDI] & PG_FRAME) == (PTDpde[0] & PG_FRAME)) {
943			/*
944			 * Do an invltlb to make the invalidated mapping
945			 * take effect immediately.
946			 */
947			pteva = VM_MAXUSER_ADDRESS + i386_ptob(m->pindex);
948			pmap_invalidate_page(pmap, pteva);
949		}
950
951		/*
952		 * If the page is finally unwired, simply free it.
953		 */
954		--m->wire_count;
955		if (m->wire_count == 0) {
956			vm_page_busy(m);
957			vm_page_free_zero(m);
958			atomic_subtract_int(&cnt.v_wire_count, 1);
959		}
960		return 1;
961	}
962	return 0;
963}
964
965static PMAP_INLINE int
966pmap_unwire_pte_hold(pmap_t pmap, vm_page_t m)
967{
968	vm_page_unhold(m);
969	if (m->hold_count == 0)
970		return _pmap_unwire_pte_hold(pmap, m);
971	else
972		return 0;
973}
974
975/*
976 * After removing a page table entry, this routine is used to
977 * conditionally free the page, and manage the hold/wire counts.
978 */
979static int
980pmap_unuse_pt(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
981{
982
983	if (va >= VM_MAXUSER_ADDRESS)
984		return 0;
985
986	return pmap_unwire_pte_hold(pmap, mpte);
987}
988
989void
990pmap_pinit0(pmap)
991	struct pmap *pmap;
992{
993
994	pmap->pm_pdir = (pd_entry_t *)(KERNBASE + (vm_offset_t)IdlePTD);
995#ifdef PAE
996	pmap->pm_pdpt = (pdpt_entry_t *)(KERNBASE + (vm_offset_t)IdlePDPT);
997#endif
998	pmap->pm_active = 0;
999	PCPU_SET(curpmap, pmap);
1000	TAILQ_INIT(&pmap->pm_pvlist);
1001	bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1002	mtx_lock_spin(&allpmaps_lock);
1003	LIST_INSERT_HEAD(&allpmaps, pmap, pm_list);
1004	mtx_unlock_spin(&allpmaps_lock);
1005}
1006
1007/*
1008 * Initialize a preallocated and zeroed pmap structure,
1009 * such as one in a vmspace structure.
1010 */
1011void
1012pmap_pinit(pmap)
1013	register struct pmap *pmap;
1014{
1015	vm_page_t m, ptdpg[NPGPTD];
1016	vm_paddr_t pa;
1017	static int color;
1018	int i;
1019
1020	/*
1021	 * No need to allocate page table space yet but we do need a valid
1022	 * page directory table.
1023	 */
1024	if (pmap->pm_pdir == NULL) {
1025		pmap->pm_pdir = (pd_entry_t *)kmem_alloc_nofault(kernel_map,
1026		    NBPTD);
1027#ifdef PAE
1028		pmap->pm_pdpt = uma_zalloc(pdptzone, M_WAITOK | M_ZERO);
1029		KASSERT(((vm_offset_t)pmap->pm_pdpt &
1030		    ((NPGPTD * sizeof(pdpt_entry_t)) - 1)) == 0,
1031		    ("pmap_pinit: pdpt misaligned"));
1032		KASSERT(pmap_kextract((vm_offset_t)pmap->pm_pdpt) < (4ULL<<30),
1033		    ("pmap_pinit: pdpt above 4g"));
1034#endif
1035	}
1036
1037	/*
1038	 * allocate the page directory page(s)
1039	 */
1040	for (i = 0; i < NPGPTD;) {
1041		m = vm_page_alloc(NULL, color++,
1042		    VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
1043		    VM_ALLOC_ZERO);
1044		if (m == NULL)
1045			VM_WAIT;
1046		else {
1047			vm_page_lock_queues();
1048			vm_page_flag_clear(m, PG_BUSY);
1049			vm_page_unlock_queues();
1050			ptdpg[i++] = m;
1051		}
1052	}
1053
1054	pmap_qenter((vm_offset_t)pmap->pm_pdir, ptdpg, NPGPTD);
1055
1056	for (i = 0; i < NPGPTD; i++) {
1057		if ((ptdpg[i]->flags & PG_ZERO) == 0)
1058			bzero(pmap->pm_pdir + (i * NPDEPG), PAGE_SIZE);
1059	}
1060
1061	mtx_lock_spin(&allpmaps_lock);
1062	LIST_INSERT_HEAD(&allpmaps, pmap, pm_list);
1063	mtx_unlock_spin(&allpmaps_lock);
1064	/* Wire in kernel global address entries. */
1065	/* XXX copies current process, does not fill in MPPTDI */
1066	bcopy(PTD + KPTDI, pmap->pm_pdir + KPTDI, nkpt * sizeof(pd_entry_t));
1067#ifdef SMP
1068	pmap->pm_pdir[MPPTDI] = PTD[MPPTDI];
1069#endif
1070
1071	/* install self-referential address mapping entry(s) */
1072	for (i = 0; i < NPGPTD; i++) {
1073		pa = VM_PAGE_TO_PHYS(ptdpg[i]);
1074		pmap->pm_pdir[PTDPTDI + i] = pa | PG_V | PG_RW | PG_A | PG_M;
1075#ifdef PAE
1076		pmap->pm_pdpt[i] = pa | PG_V;
1077#endif
1078	}
1079
1080	pmap->pm_active = 0;
1081	TAILQ_INIT(&pmap->pm_pvlist);
1082	bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1083}
1084
1085/*
1086 * Wire in kernel global address entries.  To avoid a race condition
1087 * between pmap initialization and pmap_growkernel, this procedure
1088 * should be called after the vmspace is attached to the process
1089 * but before this pmap is activated.
1090 */
1091void
1092pmap_pinit2(pmap)
1093	struct pmap *pmap;
1094{
1095	/* XXX: Remove this stub when no longer called */
1096}
1097
1098/*
1099 * this routine is called if the page table page is not
1100 * mapped correctly.
1101 */
1102static vm_page_t
1103_pmap_allocpte(pmap, ptepindex)
1104	pmap_t	pmap;
1105	unsigned ptepindex;
1106{
1107	vm_paddr_t ptepa;
1108	vm_page_t m;
1109
1110	/*
1111	 * Allocate a page table page.
1112	 */
1113	if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
1114	    VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
1115		VM_WAIT;
1116		/*
1117		 * Indicate the need to retry.  While waiting, the page table
1118		 * page may have been allocated.
1119		 */
1120		return (NULL);
1121	}
1122	if ((m->flags & PG_ZERO) == 0)
1123		pmap_zero_page(m);
1124
1125	KASSERT(m->queue == PQ_NONE,
1126		("_pmap_allocpte: %p->queue != PQ_NONE", m));
1127
1128	/*
1129	 * Increment the hold count for the page table page
1130	 * (denoting a new mapping.)
1131	 */
1132	m->hold_count++;
1133
1134	/*
1135	 * Map the pagetable page into the process address space, if
1136	 * it isn't already there.
1137	 */
1138
1139	pmap->pm_stats.resident_count++;
1140
1141	ptepa = VM_PAGE_TO_PHYS(m);
1142	pmap->pm_pdir[ptepindex] =
1143		(pd_entry_t) (ptepa | PG_U | PG_RW | PG_V | PG_A | PG_M);
1144
1145	vm_page_lock_queues();
1146	vm_page_flag_clear(m, PG_ZERO);
1147	vm_page_wakeup(m);
1148	vm_page_unlock_queues();
1149
1150	return m;
1151}
1152
1153static vm_page_t
1154pmap_allocpte(pmap_t pmap, vm_offset_t va)
1155{
1156	unsigned ptepindex;
1157	pd_entry_t ptepa;
1158	vm_page_t m;
1159
1160	/*
1161	 * Calculate pagetable page index
1162	 */
1163	ptepindex = va >> PDRSHIFT;
1164retry:
1165	/*
1166	 * Get the page directory entry
1167	 */
1168	ptepa = pmap->pm_pdir[ptepindex];
1169
1170	/*
1171	 * This supports switching from a 4MB page to a
1172	 * normal 4K page.
1173	 */
1174	if (ptepa & PG_PS) {
1175		pmap->pm_pdir[ptepindex] = 0;
1176		ptepa = 0;
1177		pmap_invalidate_all(kernel_pmap);
1178	}
1179
1180	/*
1181	 * If the page table page is mapped, we just increment the
1182	 * hold count, and activate it.
1183	 */
1184	if (ptepa) {
1185		m = PHYS_TO_VM_PAGE(ptepa);
1186		m->hold_count++;
1187	} else {
1188		/*
1189		 * Here if the pte page isn't mapped, or if it has
1190		 * been deallocated.
1191		 */
1192		m = _pmap_allocpte(pmap, ptepindex);
1193		if (m == NULL)
1194			goto retry;
1195	}
1196	return (m);
1197}
1198
1199
1200/***************************************************
1201* Pmap allocation/deallocation routines.
1202 ***************************************************/
1203
1204#ifdef SMP
1205/*
1206 * Deal with a SMP shootdown of other users of the pmap that we are
1207 * trying to dispose of.  This can be a bit hairy.
1208 */
1209static u_int *lazymask;
1210static u_int lazyptd;
1211static volatile u_int lazywait;
1212
1213void pmap_lazyfix_action(void);
1214
1215void
1216pmap_lazyfix_action(void)
1217{
1218	u_int mymask = PCPU_GET(cpumask);
1219
1220	if (rcr3() == lazyptd)
1221		load_cr3(PCPU_GET(curpcb)->pcb_cr3);
1222	atomic_clear_int(lazymask, mymask);
1223	atomic_store_rel_int(&lazywait, 1);
1224}
1225
1226static void
1227pmap_lazyfix_self(u_int mymask)
1228{
1229
1230	if (rcr3() == lazyptd)
1231		load_cr3(PCPU_GET(curpcb)->pcb_cr3);
1232	atomic_clear_int(lazymask, mymask);
1233}
1234
1235
1236static void
1237pmap_lazyfix(pmap_t pmap)
1238{
1239	u_int mymask = PCPU_GET(cpumask);
1240	u_int mask;
1241	register u_int spins;
1242
1243	while ((mask = pmap->pm_active) != 0) {
1244		spins = 50000000;
1245		mask = mask & -mask;	/* Find least significant set bit */
1246		mtx_lock_spin(&lazypmap_lock);
1247#ifdef PAE
1248		lazyptd = vtophys(pmap->pm_pdpt);
1249#else
1250		lazyptd = vtophys(pmap->pm_pdir);
1251#endif
1252		if (mask == mymask) {
1253			lazymask = &pmap->pm_active;
1254			pmap_lazyfix_self(mymask);
1255		} else {
1256			atomic_store_rel_int((u_int *)&lazymask,
1257			    (u_int)&pmap->pm_active);
1258			atomic_store_rel_int(&lazywait, 0);
1259			ipi_selected(mask, IPI_LAZYPMAP);
1260			while (lazywait == 0) {
1261				ia32_pause();
1262				if (--spins == 0)
1263					break;
1264			}
1265		}
1266		mtx_unlock_spin(&lazypmap_lock);
1267		if (spins == 0)
1268			printf("pmap_lazyfix: spun for 50000000\n");
1269	}
1270}
1271
1272#else	/* SMP */
1273
1274/*
1275 * Cleaning up on uniprocessor is easy.  For various reasons, we're
1276 * unlikely to have to even execute this code, including the fact
1277 * that the cleanup is deferred until the parent does a wait(2), which
1278 * means that another userland process has run.
1279 */
1280static void
1281pmap_lazyfix(pmap_t pmap)
1282{
1283	u_int cr3;
1284
1285	cr3 = vtophys(pmap->pm_pdir);
1286	if (cr3 == rcr3()) {
1287		load_cr3(PCPU_GET(curpcb)->pcb_cr3);
1288		pmap->pm_active &= ~(PCPU_GET(cpumask));
1289	}
1290}
1291#endif	/* SMP */
1292
1293/*
1294 * Release any resources held by the given physical map.
1295 * Called when a pmap initialized by pmap_pinit is being released.
1296 * Should only be called if the map contains no valid mappings.
1297 */
1298void
1299pmap_release(pmap_t pmap)
1300{
1301	vm_page_t m, ptdpg[NPGPTD];
1302	int i;
1303
1304	KASSERT(pmap->pm_stats.resident_count == 0,
1305	    ("pmap_release: pmap resident count %ld != 0",
1306	    pmap->pm_stats.resident_count));
1307
1308	pmap_lazyfix(pmap);
1309	mtx_lock_spin(&allpmaps_lock);
1310	LIST_REMOVE(pmap, pm_list);
1311	mtx_unlock_spin(&allpmaps_lock);
1312
1313	for (i = 0; i < NPGPTD; i++)
1314		ptdpg[i] = PHYS_TO_VM_PAGE(pmap->pm_pdir[PTDPTDI + i]);
1315
1316	bzero(pmap->pm_pdir + PTDPTDI, (nkpt + NPGPTD) *
1317	    sizeof(*pmap->pm_pdir));
1318#ifdef SMP
1319	pmap->pm_pdir[MPPTDI] = 0;
1320#endif
1321
1322	pmap_qremove((vm_offset_t)pmap->pm_pdir, NPGPTD);
1323
1324	vm_page_lock_queues();
1325	for (i = 0; i < NPGPTD; i++) {
1326		m = ptdpg[i];
1327#ifdef PAE
1328		KASSERT(VM_PAGE_TO_PHYS(m) == (pmap->pm_pdpt[i] & PG_FRAME),
1329		    ("pmap_release: got wrong ptd page"));
1330#endif
1331		m->wire_count--;
1332		atomic_subtract_int(&cnt.v_wire_count, 1);
1333		vm_page_busy(m);
1334		vm_page_free_zero(m);
1335	}
1336	vm_page_unlock_queues();
1337}
1338
1339static int
1340kvm_size(SYSCTL_HANDLER_ARGS)
1341{
1342	unsigned long ksize = VM_MAX_KERNEL_ADDRESS - KERNBASE;
1343
1344	return sysctl_handle_long(oidp, &ksize, 0, req);
1345}
1346SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
1347    0, 0, kvm_size, "IU", "Size of KVM");
1348
1349static int
1350kvm_free(SYSCTL_HANDLER_ARGS)
1351{
1352	unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
1353
1354	return sysctl_handle_long(oidp, &kfree, 0, req);
1355}
1356SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
1357    0, 0, kvm_free, "IU", "Amount of KVM free");
1358
1359/*
1360 * grow the number of kernel page table entries, if needed
1361 */
1362void
1363pmap_growkernel(vm_offset_t addr)
1364{
1365	struct pmap *pmap;
1366	int s;
1367	vm_paddr_t ptppaddr;
1368	vm_page_t nkpg;
1369	pd_entry_t newpdir;
1370	pt_entry_t *pde;
1371
1372	s = splhigh();
1373	mtx_assert(&kernel_map->system_mtx, MA_OWNED);
1374	if (kernel_vm_end == 0) {
1375		kernel_vm_end = KERNBASE;
1376		nkpt = 0;
1377		while (pdir_pde(PTD, kernel_vm_end)) {
1378			kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1379			nkpt++;
1380		}
1381	}
1382	addr = roundup2(addr, PAGE_SIZE * NPTEPG);
1383	while (kernel_vm_end < addr) {
1384		if (pdir_pde(PTD, kernel_vm_end)) {
1385			kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1386			continue;
1387		}
1388
1389		/*
1390		 * This index is bogus, but out of the way
1391		 */
1392		nkpg = vm_page_alloc(NULL, nkpt,
1393		    VM_ALLOC_NOOBJ | VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
1394		if (!nkpg)
1395			panic("pmap_growkernel: no memory to grow kernel");
1396
1397		nkpt++;
1398
1399		pmap_zero_page(nkpg);
1400		ptppaddr = VM_PAGE_TO_PHYS(nkpg);
1401		newpdir = (pd_entry_t) (ptppaddr | PG_V | PG_RW | PG_A | PG_M);
1402		pdir_pde(PTD, kernel_vm_end) = newpdir;
1403
1404		mtx_lock_spin(&allpmaps_lock);
1405		LIST_FOREACH(pmap, &allpmaps, pm_list) {
1406			pde = pmap_pde(pmap, kernel_vm_end);
1407			pde_store(pde, newpdir);
1408		}
1409		mtx_unlock_spin(&allpmaps_lock);
1410		kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1411	}
1412	splx(s);
1413}
1414
1415
1416/***************************************************
1417 * page management routines.
1418 ***************************************************/
1419
1420/*
1421 * free the pv_entry back to the free list
1422 */
1423static PMAP_INLINE void
1424free_pv_entry(pv_entry_t pv)
1425{
1426	pv_entry_count--;
1427	uma_zfree(pvzone, pv);
1428}
1429
1430/*
1431 * get a new pv_entry, allocating a block from the system
1432 * when needed.
1433 * the memory allocation is performed bypassing the malloc code
1434 * because of the possibility of allocations at interrupt time.
1435 */
1436static pv_entry_t
1437get_pv_entry(void)
1438{
1439	pv_entry_count++;
1440	if (pv_entry_high_water &&
1441		(pv_entry_count > pv_entry_high_water) &&
1442		(pmap_pagedaemon_waken == 0)) {
1443		pmap_pagedaemon_waken = 1;
1444		wakeup (&vm_pages_needed);
1445	}
1446	return uma_zalloc(pvzone, M_NOWAIT);
1447}
1448
1449/*
1450 * If it is the first entry on the list, it is actually
1451 * in the header and we must copy the following entry up
1452 * to the header.  Otherwise we must search the list for
1453 * the entry.  In either case we free the now unused entry.
1454 */
1455
1456static int
1457pmap_remove_entry(pmap_t pmap, vm_page_t m, vm_offset_t va)
1458{
1459	pv_entry_t pv;
1460	int rtval;
1461	int s;
1462
1463	s = splvm();
1464	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1465	if (m->md.pv_list_count < pmap->pm_stats.resident_count) {
1466		TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
1467			if (pmap == pv->pv_pmap && va == pv->pv_va)
1468				break;
1469		}
1470	} else {
1471		TAILQ_FOREACH(pv, &pmap->pm_pvlist, pv_plist) {
1472			if (va == pv->pv_va)
1473				break;
1474		}
1475	}
1476
1477	rtval = 0;
1478	if (pv) {
1479		rtval = pmap_unuse_pt(pmap, va, pv->pv_ptem);
1480		TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
1481		m->md.pv_list_count--;
1482		if (TAILQ_FIRST(&m->md.pv_list) == NULL)
1483			vm_page_flag_clear(m, PG_WRITEABLE);
1484
1485		TAILQ_REMOVE(&pmap->pm_pvlist, pv, pv_plist);
1486		free_pv_entry(pv);
1487	}
1488
1489	splx(s);
1490	return rtval;
1491}
1492
1493/*
1494 * Create a pv entry for page at pa for
1495 * (pmap, va).
1496 */
1497static void
1498pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t mpte, vm_page_t m)
1499{
1500
1501	int s;
1502	pv_entry_t pv;
1503
1504	s = splvm();
1505	pv = get_pv_entry();
1506	pv->pv_va = va;
1507	pv->pv_pmap = pmap;
1508	pv->pv_ptem = mpte;
1509
1510	vm_page_lock_queues();
1511	TAILQ_INSERT_TAIL(&pmap->pm_pvlist, pv, pv_plist);
1512	TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
1513	m->md.pv_list_count++;
1514
1515	vm_page_unlock_queues();
1516	splx(s);
1517}
1518
1519/*
1520 * pmap_remove_pte: do the things to unmap a page in a process
1521 */
1522static int
1523pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va)
1524{
1525	pt_entry_t oldpte;
1526	vm_page_t m, mpte;
1527
1528	oldpte = pte_load_clear(ptq);
1529	if (oldpte & PG_W)
1530		pmap->pm_stats.wired_count -= 1;
1531	/*
1532	 * Machines that don't support invlpg, also don't support
1533	 * PG_G.
1534	 */
1535	if (oldpte & PG_G)
1536		pmap_invalidate_page(kernel_pmap, va);
1537	pmap->pm_stats.resident_count -= 1;
1538	if (oldpte & PG_MANAGED) {
1539		m = PHYS_TO_VM_PAGE(oldpte);
1540		if (oldpte & PG_M) {
1541#if defined(PMAP_DIAGNOSTIC)
1542			if (pmap_nw_modified((pt_entry_t) oldpte)) {
1543				printf(
1544	"pmap_remove: modified page not writable: va: 0x%x, pte: 0x%x\n",
1545				    va, oldpte);
1546			}
1547#endif
1548			if (pmap_track_modified(va))
1549				vm_page_dirty(m);
1550		}
1551		if (oldpte & PG_A)
1552			vm_page_flag_set(m, PG_REFERENCED);
1553		return pmap_remove_entry(pmap, m, va);
1554	} else {
1555		mpte = PHYS_TO_VM_PAGE(*pmap_pde(pmap, va));
1556		return pmap_unuse_pt(pmap, va, mpte);
1557	}
1558}
1559
1560/*
1561 * Remove a single page from a process address space
1562 */
1563static void
1564pmap_remove_page(pmap_t pmap, vm_offset_t va)
1565{
1566	pt_entry_t *pte;
1567
1568	if ((pte = pmap_pte_quick(pmap, va)) == NULL || *pte == 0)
1569		return;
1570	pmap_remove_pte(pmap, pte, va);
1571	pmap_invalidate_page(pmap, va);
1572}
1573
1574/*
1575 *	Remove the given range of addresses from the specified map.
1576 *
1577 *	It is assumed that the start and end are properly
1578 *	rounded to the page size.
1579 */
1580void
1581pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1582{
1583	vm_offset_t pdnxt;
1584	pd_entry_t ptpaddr;
1585	pt_entry_t *pte;
1586	int anyvalid;
1587
1588	if (pmap == NULL)
1589		return;
1590
1591	if (pmap->pm_stats.resident_count == 0)
1592		return;
1593
1594	/*
1595	 * special handling of removing one page.  a very
1596	 * common operation and easy to short circuit some
1597	 * code.
1598	 */
1599	if ((sva + PAGE_SIZE == eva) &&
1600	    ((pmap->pm_pdir[(sva >> PDRSHIFT)] & PG_PS) == 0)) {
1601		pmap_remove_page(pmap, sva);
1602		return;
1603	}
1604
1605	anyvalid = 0;
1606
1607	for (; sva < eva; sva = pdnxt) {
1608		unsigned pdirindex;
1609
1610		/*
1611		 * Calculate index for next page table.
1612		 */
1613		pdnxt = (sva + NBPDR) & ~PDRMASK;
1614		if (pmap->pm_stats.resident_count == 0)
1615			break;
1616
1617		pdirindex = sva >> PDRSHIFT;
1618		ptpaddr = pmap->pm_pdir[pdirindex];
1619
1620		/*
1621		 * Weed out invalid mappings. Note: we assume that the page
1622		 * directory table is always allocated, and in kernel virtual.
1623		 */
1624		if (ptpaddr == 0)
1625			continue;
1626
1627		/*
1628		 * Check for large page.
1629		 */
1630		if ((ptpaddr & PG_PS) != 0) {
1631			pmap->pm_pdir[pdirindex] = 0;
1632			pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
1633			anyvalid = 1;
1634			continue;
1635		}
1636
1637		/*
1638		 * Limit our scan to either the end of the va represented
1639		 * by the current page table page, or to the end of the
1640		 * range being removed.
1641		 */
1642		if (pdnxt > eva)
1643			pdnxt = eva;
1644
1645		for (; sva != pdnxt; sva += PAGE_SIZE) {
1646			if ((pte = pmap_pte_quick(pmap, sva)) == NULL ||
1647			    *pte == 0)
1648				continue;
1649			anyvalid = 1;
1650			if (pmap_remove_pte(pmap, pte, sva))
1651				break;
1652		}
1653	}
1654
1655	if (anyvalid)
1656		pmap_invalidate_all(pmap);
1657}
1658
1659/*
1660 *	Routine:	pmap_remove_all
1661 *	Function:
1662 *		Removes this physical page from
1663 *		all physical maps in which it resides.
1664 *		Reflects back modify bits to the pager.
1665 *
1666 *	Notes:
1667 *		Original versions of this routine were very
1668 *		inefficient because they iteratively called
1669 *		pmap_remove (slow...)
1670 */
1671
1672void
1673pmap_remove_all(vm_page_t m)
1674{
1675	register pv_entry_t pv;
1676	pt_entry_t *pte, tpte;
1677	int s;
1678
1679#if defined(PMAP_DIAGNOSTIC)
1680	/*
1681	 * XXX This makes pmap_remove_all() illegal for non-managed pages!
1682	 */
1683	if (!pmap_initialized || (m->flags & PG_FICTITIOUS)) {
1684		panic("pmap_remove_all: illegal for unmanaged page, va: 0x%x",
1685		    VM_PAGE_TO_PHYS(m));
1686	}
1687#endif
1688	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1689	s = splvm();
1690	while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
1691		pv->pv_pmap->pm_stats.resident_count--;
1692		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
1693		tpte = pte_load_clear(pte);
1694		if (tpte & PG_W)
1695			pv->pv_pmap->pm_stats.wired_count--;
1696		if (tpte & PG_A)
1697			vm_page_flag_set(m, PG_REFERENCED);
1698
1699		/*
1700		 * Update the vm_page_t clean and reference bits.
1701		 */
1702		if (tpte & PG_M) {
1703#if defined(PMAP_DIAGNOSTIC)
1704			if (pmap_nw_modified((pt_entry_t) tpte)) {
1705				printf(
1706	"pmap_remove_all: modified page not writable: va: 0x%x, pte: 0x%x\n",
1707				    pv->pv_va, tpte);
1708			}
1709#endif
1710			if (pmap_track_modified(pv->pv_va))
1711				vm_page_dirty(m);
1712		}
1713		pmap_invalidate_page(pv->pv_pmap, pv->pv_va);
1714		TAILQ_REMOVE(&pv->pv_pmap->pm_pvlist, pv, pv_plist);
1715		TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
1716		m->md.pv_list_count--;
1717		pmap_unuse_pt(pv->pv_pmap, pv->pv_va, pv->pv_ptem);
1718		free_pv_entry(pv);
1719	}
1720	vm_page_flag_clear(m, PG_WRITEABLE);
1721	splx(s);
1722}
1723
1724/*
1725 *	Set the physical protection on the
1726 *	specified range of this map as requested.
1727 */
1728void
1729pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
1730{
1731	vm_offset_t pdnxt;
1732	pd_entry_t ptpaddr;
1733	int anychanged;
1734
1735	if (pmap == NULL)
1736		return;
1737
1738	if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
1739		pmap_remove(pmap, sva, eva);
1740		return;
1741	}
1742
1743	if (prot & VM_PROT_WRITE)
1744		return;
1745
1746	anychanged = 0;
1747
1748	for (; sva < eva; sva = pdnxt) {
1749		unsigned pdirindex;
1750
1751		pdnxt = (sva + NBPDR) & ~PDRMASK;
1752
1753		pdirindex = sva >> PDRSHIFT;
1754		ptpaddr = pmap->pm_pdir[pdirindex];
1755
1756		/*
1757		 * Weed out invalid mappings. Note: we assume that the page
1758		 * directory table is always allocated, and in kernel virtual.
1759		 */
1760		if (ptpaddr == 0)
1761			continue;
1762
1763		/*
1764		 * Check for large page.
1765		 */
1766		if ((ptpaddr & PG_PS) != 0) {
1767			pmap->pm_pdir[pdirindex] &= ~(PG_M|PG_RW);
1768			pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
1769			anychanged = 1;
1770			continue;
1771		}
1772
1773		if (pdnxt > eva)
1774			pdnxt = eva;
1775
1776		for (; sva != pdnxt; sva += PAGE_SIZE) {
1777			pt_entry_t pbits;
1778			pt_entry_t *pte;
1779			vm_page_t m;
1780
1781			if ((pte = pmap_pte_quick(pmap, sva)) == NULL)
1782				continue;
1783			pbits = *pte;
1784			if (pbits & PG_MANAGED) {
1785				m = NULL;
1786				if (pbits & PG_A) {
1787					m = PHYS_TO_VM_PAGE(pbits);
1788					vm_page_flag_set(m, PG_REFERENCED);
1789					pbits &= ~PG_A;
1790				}
1791				if ((pbits & PG_M) != 0 &&
1792				    pmap_track_modified(sva)) {
1793					if (m == NULL)
1794						m = PHYS_TO_VM_PAGE(pbits);
1795					vm_page_dirty(m);
1796					pbits &= ~PG_M;
1797				}
1798			}
1799
1800			pbits &= ~PG_RW;
1801
1802			if (pbits != *pte) {
1803				pte_store(pte, pbits);
1804				anychanged = 1;
1805			}
1806		}
1807	}
1808	if (anychanged)
1809		pmap_invalidate_all(pmap);
1810}
1811
1812/*
1813 *	Insert the given physical page (p) at
1814 *	the specified virtual address (v) in the
1815 *	target physical map with the protection requested.
1816 *
1817 *	If specified, the page will be wired down, meaning
1818 *	that the related pte can not be reclaimed.
1819 *
1820 *	NB:  This is the only routine which MAY NOT lazy-evaluate
1821 *	or lose information.  That is, this routine must actually
1822 *	insert this page into the given map NOW.
1823 */
1824void
1825pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
1826	   boolean_t wired)
1827{
1828	vm_paddr_t pa;
1829	register pt_entry_t *pte;
1830	vm_paddr_t opa;
1831	pt_entry_t origpte, newpte;
1832	vm_page_t mpte;
1833
1834	if (pmap == NULL)
1835		return;
1836
1837	va &= PG_FRAME;
1838#ifdef PMAP_DIAGNOSTIC
1839	if (va > VM_MAX_KERNEL_ADDRESS)
1840		panic("pmap_enter: toobig");
1841	if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
1842		panic("pmap_enter: invalid to pmap_enter page table pages (va: 0x%x)", va);
1843#endif
1844
1845	mpte = NULL;
1846	/*
1847	 * In the case that a page table page is not
1848	 * resident, we are creating it here.
1849	 */
1850	if (va < VM_MAXUSER_ADDRESS) {
1851		mpte = pmap_allocpte(pmap, va);
1852	}
1853#if 0 && defined(PMAP_DIAGNOSTIC)
1854	else {
1855		pd_entry_t *pdeaddr = pmap_pde(pmap, va);
1856		origpte = *pdeaddr;
1857		if ((origpte & PG_V) == 0) {
1858			panic("pmap_enter: invalid kernel page table page, pdir=%p, pde=%p, va=%p\n",
1859				pmap->pm_pdir[PTDPTDI], origpte, va);
1860		}
1861	}
1862#endif
1863
1864	pte = pmap_pte_quick(pmap, va);
1865
1866	/*
1867	 * Page Directory table entry not valid, we need a new PT page
1868	 */
1869	if (pte == NULL) {
1870		panic("pmap_enter: invalid page directory pdir=%#jx, va=%#x\n",
1871			(uintmax_t)pmap->pm_pdir[PTDPTDI], va);
1872	}
1873
1874	pa = VM_PAGE_TO_PHYS(m) & PG_FRAME;
1875	origpte = *pte;
1876	opa = origpte & PG_FRAME;
1877
1878	if (origpte & PG_PS) {
1879		/*
1880		 * Yes, I know this will truncate upper address bits for PAE,
1881		 * but I'm actually more interested in the lower bits
1882		 */
1883		printf("pmap_enter: va %p, pte %p, origpte %p\n",
1884		    (void *)va, (void *)pte, (void *)(uintptr_t)origpte);
1885		panic("pmap_enter: attempted pmap_enter on 4MB page");
1886	}
1887
1888	/*
1889	 * Mapping has not changed, must be protection or wiring change.
1890	 */
1891	if (origpte && (opa == pa)) {
1892		/*
1893		 * Wiring change, just update stats. We don't worry about
1894		 * wiring PT pages as they remain resident as long as there
1895		 * are valid mappings in them. Hence, if a user page is wired,
1896		 * the PT page will be also.
1897		 */
1898		if (wired && ((origpte & PG_W) == 0))
1899			pmap->pm_stats.wired_count++;
1900		else if (!wired && (origpte & PG_W))
1901			pmap->pm_stats.wired_count--;
1902
1903#if defined(PMAP_DIAGNOSTIC)
1904		if (pmap_nw_modified((pt_entry_t) origpte)) {
1905			printf(
1906	"pmap_enter: modified page not writable: va: 0x%x, pte: 0x%x\n",
1907			    va, origpte);
1908		}
1909#endif
1910
1911		/*
1912		 * Remove extra pte reference
1913		 */
1914		if (mpte)
1915			mpte->hold_count--;
1916
1917		if ((prot & VM_PROT_WRITE) && (origpte & PG_V)) {
1918			if ((origpte & PG_RW) == 0) {
1919				pte_store(pte, origpte | PG_RW);
1920				pmap_invalidate_page(pmap, va);
1921			}
1922			return;
1923		}
1924
1925		/*
1926		 * We might be turning off write access to the page,
1927		 * so we go ahead and sense modify status.
1928		 */
1929		if (origpte & PG_MANAGED) {
1930			if ((origpte & PG_M) && pmap_track_modified(va)) {
1931				vm_page_t om;
1932				om = PHYS_TO_VM_PAGE(opa);
1933				vm_page_dirty(om);
1934			}
1935			pa |= PG_MANAGED;
1936		}
1937		goto validate;
1938	}
1939	/*
1940	 * Mapping has changed, invalidate old range and fall through to
1941	 * handle validating new mapping.
1942	 */
1943	if (opa) {
1944		int err;
1945		vm_page_lock_queues();
1946		err = pmap_remove_pte(pmap, pte, va);
1947		vm_page_unlock_queues();
1948		if (err)
1949			panic("pmap_enter: pte vanished, va: 0x%x", va);
1950	}
1951
1952	/*
1953	 * Enter on the PV list if part of our managed memory. Note that we
1954	 * raise IPL while manipulating pv_table since pmap_enter can be
1955	 * called at interrupt time.
1956	 */
1957	if (pmap_initialized &&
1958	    (m->flags & (PG_FICTITIOUS|PG_UNMANAGED)) == 0) {
1959		pmap_insert_entry(pmap, va, mpte, m);
1960		pa |= PG_MANAGED;
1961	}
1962
1963	/*
1964	 * Increment counters
1965	 */
1966	pmap->pm_stats.resident_count++;
1967	if (wired)
1968		pmap->pm_stats.wired_count++;
1969
1970validate:
1971	/*
1972	 * Now validate mapping with desired protection/wiring.
1973	 */
1974	newpte = (pt_entry_t)(pa | pte_prot(pmap, prot) | PG_V);
1975
1976	if (wired)
1977		newpte |= PG_W;
1978	if (va < VM_MAXUSER_ADDRESS)
1979		newpte |= PG_U;
1980	if (pmap == kernel_pmap)
1981		newpte |= pgeflag;
1982
1983	/*
1984	 * if the mapping or permission bits are different, we need
1985	 * to update the pte.
1986	 */
1987	if ((origpte & ~(PG_M|PG_A)) != newpte) {
1988		pte_store(pte, newpte | PG_A);
1989		/*if (origpte)*/ {
1990			pmap_invalidate_page(pmap, va);
1991		}
1992	}
1993}
1994
1995/*
1996 * this code makes some *MAJOR* assumptions:
1997 * 1. Current pmap & pmap exists.
1998 * 2. Not wired.
1999 * 3. Read access.
2000 * 4. No page table pages.
2001 * 5. Tlbflush is deferred to calling procedure.
2002 * 6. Page IS managed.
2003 * but is *MUCH* faster than pmap_enter...
2004 */
2005
2006vm_page_t
2007pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_page_t mpte)
2008{
2009	pt_entry_t *pte;
2010	vm_paddr_t pa;
2011
2012	/*
2013	 * In the case that a page table page is not
2014	 * resident, we are creating it here.
2015	 */
2016	if (va < VM_MAXUSER_ADDRESS) {
2017		unsigned ptepindex;
2018		pd_entry_t ptepa;
2019
2020		/*
2021		 * Calculate pagetable page index
2022		 */
2023		ptepindex = va >> PDRSHIFT;
2024		if (mpte && (mpte->pindex == ptepindex)) {
2025			mpte->hold_count++;
2026		} else {
2027retry:
2028			/*
2029			 * Get the page directory entry
2030			 */
2031			ptepa = pmap->pm_pdir[ptepindex];
2032
2033			/*
2034			 * If the page table page is mapped, we just increment
2035			 * the hold count, and activate it.
2036			 */
2037			if (ptepa) {
2038				if (ptepa & PG_PS)
2039					panic("pmap_enter_quick: unexpected mapping into 4MB page");
2040				mpte = PHYS_TO_VM_PAGE(ptepa);
2041				mpte->hold_count++;
2042			} else {
2043				mpte = _pmap_allocpte(pmap, ptepindex);
2044				if (mpte == NULL)
2045					goto retry;
2046			}
2047		}
2048	} else {
2049		mpte = NULL;
2050	}
2051
2052	/*
2053	 * This call to vtopte makes the assumption that we are
2054	 * entering the page into the current pmap.  In order to support
2055	 * quick entry into any pmap, one would likely use pmap_pte_quick.
2056	 * But that isn't as quick as vtopte.
2057	 */
2058	pte = vtopte(va);
2059	if (*pte) {
2060		if (mpte != NULL) {
2061			vm_page_lock_queues();
2062			pmap_unwire_pte_hold(pmap, mpte);
2063			vm_page_unlock_queues();
2064		}
2065		return 0;
2066	}
2067
2068	/*
2069	 * Enter on the PV list if part of our managed memory. Note that we
2070	 * raise IPL while manipulating pv_table since pmap_enter can be
2071	 * called at interrupt time.
2072	 */
2073	if ((m->flags & (PG_FICTITIOUS|PG_UNMANAGED)) == 0)
2074		pmap_insert_entry(pmap, va, mpte, m);
2075
2076	/*
2077	 * Increment counters
2078	 */
2079	pmap->pm_stats.resident_count++;
2080
2081	pa = VM_PAGE_TO_PHYS(m);
2082
2083	/*
2084	 * Now validate mapping with RO protection
2085	 */
2086	if (m->flags & (PG_FICTITIOUS|PG_UNMANAGED))
2087		pte_store(pte, pa | PG_V | PG_U);
2088	else
2089		pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
2090
2091	return mpte;
2092}
2093
2094/*
2095 * Make a temporary mapping for a physical address.  This is only intended
2096 * to be used for panic dumps.
2097 */
2098void *
2099pmap_kenter_temporary(vm_offset_t pa, int i)
2100{
2101	vm_offset_t va;
2102
2103	va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
2104	pmap_kenter(va, pa);
2105#ifndef I386_CPU
2106	invlpg(va);
2107#else
2108	invltlb();
2109#endif
2110	return ((void *)crashdumpmap);
2111}
2112
2113/*
2114 * This code maps large physical mmap regions into the
2115 * processor address space.  Note that some shortcuts
2116 * are taken, but the code works.
2117 */
2118void
2119pmap_object_init_pt(pmap_t pmap, vm_offset_t addr,
2120		    vm_object_t object, vm_pindex_t pindex,
2121		    vm_size_t size)
2122{
2123	vm_page_t p;
2124
2125	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2126	KASSERT(object->type == OBJT_DEVICE,
2127	    ("pmap_object_init_pt: non-device object"));
2128	if (pseflag &&
2129	    ((addr & (NBPDR - 1)) == 0) && ((size & (NBPDR - 1)) == 0)) {
2130		int i;
2131		vm_page_t m[1];
2132		unsigned int ptepindex;
2133		int npdes;
2134		pd_entry_t ptepa;
2135
2136		if (pmap->pm_pdir[ptepindex = (addr >> PDRSHIFT)])
2137			return;
2138retry:
2139		p = vm_page_lookup(object, pindex);
2140		if (p != NULL) {
2141			vm_page_lock_queues();
2142			if (vm_page_sleep_if_busy(p, FALSE, "init4p"))
2143				goto retry;
2144		} else {
2145			p = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL);
2146			if (p == NULL)
2147				return;
2148			m[0] = p;
2149
2150			if (vm_pager_get_pages(object, m, 1, 0) != VM_PAGER_OK) {
2151				vm_page_lock_queues();
2152				vm_page_free(p);
2153				vm_page_unlock_queues();
2154				return;
2155			}
2156
2157			p = vm_page_lookup(object, pindex);
2158			vm_page_lock_queues();
2159			vm_page_wakeup(p);
2160		}
2161		vm_page_unlock_queues();
2162
2163		ptepa = VM_PAGE_TO_PHYS(p);
2164		if (ptepa & (NBPDR - 1))
2165			return;
2166
2167		p->valid = VM_PAGE_BITS_ALL;
2168
2169		pmap->pm_stats.resident_count += size >> PAGE_SHIFT;
2170		npdes = size >> PDRSHIFT;
2171		for(i = 0; i < npdes; i++) {
2172			pde_store(&pmap->pm_pdir[ptepindex],
2173			    ptepa | PG_U | PG_RW | PG_V | PG_PS);
2174			ptepa += NBPDR;
2175			ptepindex += 1;
2176		}
2177		pmap_invalidate_all(pmap);
2178	}
2179}
2180
2181/*
2182 *	Routine:	pmap_change_wiring
2183 *	Function:	Change the wiring attribute for a map/virtual-address
2184 *			pair.
2185 *	In/out conditions:
2186 *			The mapping must already exist in the pmap.
2187 */
2188void
2189pmap_change_wiring(pmap, va, wired)
2190	register pmap_t pmap;
2191	vm_offset_t va;
2192	boolean_t wired;
2193{
2194	register pt_entry_t *pte;
2195
2196	if (pmap == NULL)
2197		return;
2198
2199	pte = pmap_pte_quick(pmap, va);
2200
2201	if (wired && !pmap_pte_w(pte))
2202		pmap->pm_stats.wired_count++;
2203	else if (!wired && pmap_pte_w(pte))
2204		pmap->pm_stats.wired_count--;
2205
2206	/*
2207	 * Wiring is not a hardware characteristic so there is no need to
2208	 * invalidate TLB.
2209	 */
2210	pmap_pte_set_w(pte, wired);
2211}
2212
2213
2214
2215/*
2216 *	Copy the range specified by src_addr/len
2217 *	from the source map to the range dst_addr/len
2218 *	in the destination map.
2219 *
2220 *	This routine is only advisory and need not do anything.
2221 */
2222
2223void
2224pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
2225	  vm_offset_t src_addr)
2226{
2227	vm_offset_t addr;
2228	vm_offset_t end_addr = src_addr + len;
2229	vm_offset_t pdnxt;
2230	vm_page_t m;
2231
2232	if (dst_addr != src_addr)
2233		return;
2234
2235	if (!pmap_is_current(src_pmap))
2236		return;
2237
2238	for (addr = src_addr; addr < end_addr; addr = pdnxt) {
2239		pt_entry_t *src_pte, *dst_pte;
2240		vm_page_t dstmpte, srcmpte;
2241		pd_entry_t srcptepaddr;
2242		unsigned ptepindex;
2243
2244		if (addr >= UPT_MIN_ADDRESS)
2245			panic("pmap_copy: invalid to pmap_copy page tables\n");
2246
2247		/*
2248		 * Don't let optional prefaulting of pages make us go
2249		 * way below the low water mark of free pages or way
2250		 * above high water mark of used pv entries.
2251		 */
2252		if (cnt.v_free_count < cnt.v_free_reserved ||
2253		    pv_entry_count > pv_entry_high_water)
2254			break;
2255
2256		pdnxt = (addr + NBPDR) & ~PDRMASK;
2257		ptepindex = addr >> PDRSHIFT;
2258
2259		srcptepaddr = src_pmap->pm_pdir[ptepindex];
2260		if (srcptepaddr == 0)
2261			continue;
2262
2263		if (srcptepaddr & PG_PS) {
2264			if (dst_pmap->pm_pdir[ptepindex] == 0) {
2265				dst_pmap->pm_pdir[ptepindex] = srcptepaddr;
2266				dst_pmap->pm_stats.resident_count +=
2267				    NBPDR / PAGE_SIZE;
2268			}
2269			continue;
2270		}
2271
2272		srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
2273		if (srcmpte->hold_count == 0 || (srcmpte->flags & PG_BUSY))
2274			continue;
2275
2276		if (pdnxt > end_addr)
2277			pdnxt = end_addr;
2278
2279		src_pte = vtopte(addr);
2280		while (addr < pdnxt) {
2281			pt_entry_t ptetemp;
2282			ptetemp = *src_pte;
2283			/*
2284			 * we only virtual copy managed pages
2285			 */
2286			if ((ptetemp & PG_MANAGED) != 0) {
2287				/*
2288				 * We have to check after allocpte for the
2289				 * pte still being around...  allocpte can
2290				 * block.
2291				 */
2292				dstmpte = pmap_allocpte(dst_pmap, addr);
2293				dst_pte = pmap_pte_quick(dst_pmap, addr);
2294				if ((*dst_pte == 0) && (ptetemp = *src_pte)) {
2295					/*
2296					 * Clear the modified and
2297					 * accessed (referenced) bits
2298					 * during the copy.
2299					 */
2300					m = PHYS_TO_VM_PAGE(ptetemp);
2301					*dst_pte = ptetemp & ~(PG_M | PG_A);
2302					dst_pmap->pm_stats.resident_count++;
2303					pmap_insert_entry(dst_pmap, addr,
2304						dstmpte, m);
2305	 			} else {
2306					vm_page_lock_queues();
2307					pmap_unwire_pte_hold(dst_pmap, dstmpte);
2308					vm_page_unlock_queues();
2309				}
2310				if (dstmpte->hold_count >= srcmpte->hold_count)
2311					break;
2312			}
2313			addr += PAGE_SIZE;
2314			src_pte++;
2315		}
2316	}
2317}
2318
2319#ifdef SMP
2320
2321/*
2322 *	pmap_zpi_switchout*()
2323 *
2324 *	These functions allow us to avoid doing IPIs alltogether in certain
2325 *	temporary page-mapping situations (page zeroing).  Instead to deal
2326 *	with being preempted and moved onto a different cpu we invalidate
2327 *	the page when the scheduler switches us in.  This does not occur
2328 *	very often so we remain relatively optimal with very little effort.
2329 */
2330static void
2331pmap_zpi_switchout12(void)
2332{
2333	invlpg((u_int)CADDR1);
2334	invlpg((u_int)CADDR2);
2335}
2336
2337static void
2338pmap_zpi_switchout2(void)
2339{
2340	invlpg((u_int)CADDR2);
2341}
2342
2343static void
2344pmap_zpi_switchout3(void)
2345{
2346	invlpg((u_int)CADDR3);
2347}
2348
2349#endif
2350
2351static __inline void
2352pagezero(void *page)
2353{
2354#if defined(I686_CPU)
2355	if (cpu_class == CPUCLASS_686) {
2356#if defined(CPU_ENABLE_SSE)
2357		if (cpu_feature & CPUID_SSE2)
2358			sse2_pagezero(page);
2359		else
2360#endif
2361			i686_pagezero(page);
2362	} else
2363#endif
2364		bzero(page, PAGE_SIZE);
2365}
2366
2367static __inline void
2368invlcaddr(void *caddr)
2369{
2370#ifdef I386_CPU
2371	invltlb();
2372#else
2373	invlpg((u_int)caddr);
2374#endif
2375}
2376
2377/*
2378 *	pmap_zero_page zeros the specified hardware page by mapping
2379 *	the page into KVM and using bzero to clear its contents.
2380 */
2381void
2382pmap_zero_page(vm_page_t m)
2383{
2384
2385	mtx_lock(&CMAPCADDR12_lock);
2386	if (*CMAP2)
2387		panic("pmap_zero_page: CMAP2 busy");
2388#ifdef SMP
2389	curthread->td_pcb->pcb_switchout = pmap_zpi_switchout2;
2390#endif
2391	*CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M;
2392#ifdef SMP
2393	invlpg((u_int)CADDR2);
2394#endif
2395	pagezero(CADDR2);
2396	*CMAP2 = 0;
2397	invlcaddr(CADDR2);
2398#ifdef SMP
2399	curthread->td_pcb->pcb_switchout = NULL;
2400#endif
2401	mtx_unlock(&CMAPCADDR12_lock);
2402}
2403
2404/*
2405 *	pmap_zero_page_area zeros the specified hardware page by mapping
2406 *	the page into KVM and using bzero to clear its contents.
2407 *
2408 *	off and size may not cover an area beyond a single hardware page.
2409 */
2410void
2411pmap_zero_page_area(vm_page_t m, int off, int size)
2412{
2413
2414	mtx_lock(&CMAPCADDR12_lock);
2415	if (*CMAP2)
2416		panic("pmap_zero_page: CMAP2 busy");
2417#ifdef SMP
2418	curthread->td_pcb->pcb_switchout = pmap_zpi_switchout2;
2419#endif
2420	*CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M;
2421#ifdef SMP
2422	invlpg((u_int)CADDR2);
2423#endif
2424	if (off == 0 && size == PAGE_SIZE)
2425		pagezero(CADDR2);
2426	else
2427		bzero((char *)CADDR2 + off, size);
2428	*CMAP2 = 0;
2429	invlcaddr(CADDR2);
2430#ifdef SMP
2431	curthread->td_pcb->pcb_switchout = NULL;
2432#endif
2433	mtx_unlock(&CMAPCADDR12_lock);
2434}
2435
2436/*
2437 *	pmap_zero_page_idle zeros the specified hardware page by mapping
2438 *	the page into KVM and using bzero to clear its contents.  This
2439 *	is intended to be called from the vm_pagezero process only and
2440 *	outside of Giant.
2441 */
2442void
2443pmap_zero_page_idle(vm_page_t m)
2444{
2445
2446	if (*CMAP3)
2447		panic("pmap_zero_page: CMAP3 busy");
2448#ifdef SMP
2449	curthread->td_pcb->pcb_switchout = pmap_zpi_switchout3;
2450#endif
2451	*CMAP3 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M;
2452#ifdef SMP
2453	invlpg((u_int)CADDR3);
2454#endif
2455	pagezero(CADDR3);
2456	*CMAP3 = 0;
2457	invlcaddr(CADDR3);
2458#ifdef SMP
2459	curthread->td_pcb->pcb_switchout = NULL;
2460#endif
2461}
2462
2463/*
2464 *	pmap_copy_page copies the specified (machine independent)
2465 *	page by mapping the page into virtual memory and using
2466 *	bcopy to copy the page, one machine dependent page at a
2467 *	time.
2468 */
2469void
2470pmap_copy_page(vm_page_t src, vm_page_t dst)
2471{
2472
2473	mtx_lock(&CMAPCADDR12_lock);
2474	if (*CMAP1)
2475		panic("pmap_copy_page: CMAP1 busy");
2476	if (*CMAP2)
2477		panic("pmap_copy_page: CMAP2 busy");
2478#ifdef SMP
2479	curthread->td_pcb->pcb_switchout = pmap_zpi_switchout12;
2480#endif
2481	*CMAP1 = PG_V | VM_PAGE_TO_PHYS(src) | PG_A;
2482	*CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(dst) | PG_A | PG_M;
2483#ifdef SMP
2484	invlpg((u_int)CADDR1);
2485	invlpg((u_int)CADDR2);
2486#endif
2487	bcopy(CADDR1, CADDR2, PAGE_SIZE);
2488	*CMAP1 = 0;
2489	*CMAP2 = 0;
2490#ifdef I386_CPU
2491	invltlb();
2492#else
2493	invlpg((u_int)CADDR1);
2494	invlpg((u_int)CADDR2);
2495#endif
2496#ifdef SMP
2497	curthread->td_pcb->pcb_switchout = NULL;
2498#endif
2499	mtx_unlock(&CMAPCADDR12_lock);
2500}
2501
2502/*
2503 * Returns true if the pmap's pv is one of the first
2504 * 16 pvs linked to from this page.  This count may
2505 * be changed upwards or downwards in the future; it
2506 * is only necessary that true be returned for a small
2507 * subset of pmaps for proper page aging.
2508 */
2509boolean_t
2510pmap_page_exists_quick(pmap, m)
2511	pmap_t pmap;
2512	vm_page_t m;
2513{
2514	pv_entry_t pv;
2515	int loops = 0;
2516	int s;
2517
2518	if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
2519		return FALSE;
2520
2521	s = splvm();
2522	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2523	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2524		if (pv->pv_pmap == pmap) {
2525			splx(s);
2526			return TRUE;
2527		}
2528		loops++;
2529		if (loops >= 16)
2530			break;
2531	}
2532	splx(s);
2533	return (FALSE);
2534}
2535
2536#define PMAP_REMOVE_PAGES_CURPROC_ONLY
2537/*
2538 * Remove all pages from specified address space
2539 * this aids process exit speeds.  Also, this code
2540 * is special cased for current process only, but
2541 * can have the more generic (and slightly slower)
2542 * mode enabled.  This is much faster than pmap_remove
2543 * in the case of running down an entire address space.
2544 */
2545void
2546pmap_remove_pages(pmap, sva, eva)
2547	pmap_t pmap;
2548	vm_offset_t sva, eva;
2549{
2550	pt_entry_t *pte, tpte;
2551	vm_page_t m;
2552	pv_entry_t pv, npv;
2553	int s;
2554
2555#ifdef PMAP_REMOVE_PAGES_CURPROC_ONLY
2556	if (!curthread || (pmap != vmspace_pmap(curthread->td_proc->p_vmspace))) {
2557		printf("warning: pmap_remove_pages called with non-current pmap\n");
2558		return;
2559	}
2560#endif
2561	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2562	s = splvm();
2563	for (pv = TAILQ_FIRST(&pmap->pm_pvlist); pv; pv = npv) {
2564
2565		if (pv->pv_va >= eva || pv->pv_va < sva) {
2566			npv = TAILQ_NEXT(pv, pv_plist);
2567			continue;
2568		}
2569
2570#ifdef PMAP_REMOVE_PAGES_CURPROC_ONLY
2571		pte = vtopte(pv->pv_va);
2572#else
2573		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
2574#endif
2575		tpte = *pte;
2576
2577		if (tpte == 0) {
2578			printf("TPTE at %p  IS ZERO @ VA %08x\n",
2579							pte, pv->pv_va);
2580			panic("bad pte");
2581		}
2582
2583/*
2584 * We cannot remove wired pages from a process' mapping at this time
2585 */
2586		if (tpte & PG_W) {
2587			npv = TAILQ_NEXT(pv, pv_plist);
2588			continue;
2589		}
2590
2591		m = PHYS_TO_VM_PAGE(tpte);
2592		KASSERT(m->phys_addr == (tpte & PG_FRAME),
2593		    ("vm_page_t %p phys_addr mismatch %016jx %016jx",
2594		    m, (uintmax_t)m->phys_addr, (uintmax_t)tpte));
2595
2596		KASSERT(m < &vm_page_array[vm_page_array_size],
2597			("pmap_remove_pages: bad tpte %#jx", (uintmax_t)tpte));
2598
2599		pv->pv_pmap->pm_stats.resident_count--;
2600
2601		pte_clear(pte);
2602
2603		/*
2604		 * Update the vm_page_t clean and reference bits.
2605		 */
2606		if (tpte & PG_M) {
2607			vm_page_dirty(m);
2608		}
2609
2610		npv = TAILQ_NEXT(pv, pv_plist);
2611		TAILQ_REMOVE(&pv->pv_pmap->pm_pvlist, pv, pv_plist);
2612
2613		m->md.pv_list_count--;
2614		TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2615		if (TAILQ_FIRST(&m->md.pv_list) == NULL) {
2616			vm_page_flag_clear(m, PG_WRITEABLE);
2617		}
2618
2619		pmap_unuse_pt(pv->pv_pmap, pv->pv_va, pv->pv_ptem);
2620		free_pv_entry(pv);
2621	}
2622	splx(s);
2623	pmap_invalidate_all(pmap);
2624}
2625
2626/*
2627 *	pmap_is_modified:
2628 *
2629 *	Return whether or not the specified physical page was modified
2630 *	in any physical maps.
2631 */
2632boolean_t
2633pmap_is_modified(vm_page_t m)
2634{
2635	pv_entry_t pv;
2636	pt_entry_t *pte;
2637	int s;
2638
2639	if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
2640		return FALSE;
2641
2642	s = splvm();
2643	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2644	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2645		/*
2646		 * if the bit being tested is the modified bit, then
2647		 * mark clean_map and ptes as never
2648		 * modified.
2649		 */
2650		if (!pmap_track_modified(pv->pv_va))
2651			continue;
2652#if defined(PMAP_DIAGNOSTIC)
2653		if (!pv->pv_pmap) {
2654			printf("Null pmap (tb) at va: 0x%x\n", pv->pv_va);
2655			continue;
2656		}
2657#endif
2658		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
2659		if (*pte & PG_M) {
2660			splx(s);
2661			return TRUE;
2662		}
2663	}
2664	splx(s);
2665	return (FALSE);
2666}
2667
2668/*
2669 *	pmap_is_prefaultable:
2670 *
2671 *	Return whether or not the specified virtual address is elgible
2672 *	for prefault.
2673 */
2674boolean_t
2675pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
2676{
2677	pt_entry_t *pte;
2678
2679	if ((*pmap_pde(pmap, addr)) == 0)
2680		return (FALSE);
2681	pte = vtopte(addr);
2682	if (*pte)
2683		return (FALSE);
2684	return (TRUE);
2685}
2686
2687/*
2688 *	Clear the given bit in each of the given page's ptes.
2689 */
2690static __inline void
2691pmap_clear_ptes(vm_page_t m, int bit)
2692{
2693	register pv_entry_t pv;
2694	pt_entry_t pbits, *pte;
2695	int s;
2696
2697	if (!pmap_initialized || (m->flags & PG_FICTITIOUS) ||
2698	    (bit == PG_RW && (m->flags & PG_WRITEABLE) == 0))
2699		return;
2700
2701	s = splvm();
2702	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2703	/*
2704	 * Loop over all current mappings setting/clearing as appropos If
2705	 * setting RO do we need to clear the VAC?
2706	 */
2707	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2708		/*
2709		 * don't write protect pager mappings
2710		 */
2711		if (bit == PG_RW) {
2712			if (!pmap_track_modified(pv->pv_va))
2713				continue;
2714		}
2715
2716#if defined(PMAP_DIAGNOSTIC)
2717		if (!pv->pv_pmap) {
2718			printf("Null pmap (cb) at va: 0x%x\n", pv->pv_va);
2719			continue;
2720		}
2721#endif
2722
2723		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
2724		pbits = *pte;
2725		if (pbits & bit) {
2726			if (bit == PG_RW) {
2727				if (pbits & PG_M) {
2728					vm_page_dirty(m);
2729				}
2730				pte_store(pte, pbits & ~(PG_M|PG_RW));
2731			} else {
2732				pte_store(pte, pbits & ~bit);
2733			}
2734			pmap_invalidate_page(pv->pv_pmap, pv->pv_va);
2735		}
2736	}
2737	if (bit == PG_RW)
2738		vm_page_flag_clear(m, PG_WRITEABLE);
2739	splx(s);
2740}
2741
2742/*
2743 *      pmap_page_protect:
2744 *
2745 *      Lower the permission for all mappings to a given page.
2746 */
2747void
2748pmap_page_protect(vm_page_t m, vm_prot_t prot)
2749{
2750	if ((prot & VM_PROT_WRITE) == 0) {
2751		if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
2752			pmap_clear_ptes(m, PG_RW);
2753		} else {
2754			pmap_remove_all(m);
2755		}
2756	}
2757}
2758
2759/*
2760 *	pmap_ts_referenced:
2761 *
2762 *	Return a count of reference bits for a page, clearing those bits.
2763 *	It is not necessary for every reference bit to be cleared, but it
2764 *	is necessary that 0 only be returned when there are truly no
2765 *	reference bits set.
2766 *
2767 *	XXX: The exact number of bits to check and clear is a matter that
2768 *	should be tested and standardized at some point in the future for
2769 *	optimal aging of shared pages.
2770 */
2771int
2772pmap_ts_referenced(vm_page_t m)
2773{
2774	register pv_entry_t pv, pvf, pvn;
2775	pt_entry_t *pte;
2776	pt_entry_t v;
2777	int s;
2778	int rtval = 0;
2779
2780	if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
2781		return (rtval);
2782
2783	s = splvm();
2784	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2785	if ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
2786
2787		pvf = pv;
2788
2789		do {
2790			pvn = TAILQ_NEXT(pv, pv_list);
2791
2792			TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2793
2794			TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
2795
2796			if (!pmap_track_modified(pv->pv_va))
2797				continue;
2798
2799			pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
2800
2801			if (pte && ((v = pte_load(pte)) & PG_A) != 0) {
2802				pte_store(pte, v & ~PG_A);
2803				pmap_invalidate_page(pv->pv_pmap, pv->pv_va);
2804
2805				rtval++;
2806				if (rtval > 4) {
2807					break;
2808				}
2809			}
2810		} while ((pv = pvn) != NULL && pv != pvf);
2811	}
2812	splx(s);
2813
2814	return (rtval);
2815}
2816
2817/*
2818 *	Clear the modify bits on the specified physical page.
2819 */
2820void
2821pmap_clear_modify(vm_page_t m)
2822{
2823	pmap_clear_ptes(m, PG_M);
2824}
2825
2826/*
2827 *	pmap_clear_reference:
2828 *
2829 *	Clear the reference bit on the specified physical page.
2830 */
2831void
2832pmap_clear_reference(vm_page_t m)
2833{
2834	pmap_clear_ptes(m, PG_A);
2835}
2836
2837/*
2838 * Miscellaneous support routines follow
2839 */
2840
2841static void
2842i386_protection_init()
2843{
2844	register int *kp, prot;
2845
2846	kp = protection_codes;
2847	for (prot = 0; prot < 8; prot++) {
2848		switch (prot) {
2849		case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_NONE:
2850			/*
2851			 * Read access is also 0. There isn't any execute bit,
2852			 * so just make it readable.
2853			 */
2854		case VM_PROT_READ | VM_PROT_NONE | VM_PROT_NONE:
2855		case VM_PROT_READ | VM_PROT_NONE | VM_PROT_EXECUTE:
2856		case VM_PROT_NONE | VM_PROT_NONE | VM_PROT_EXECUTE:
2857			*kp++ = 0;
2858			break;
2859		case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_NONE:
2860		case VM_PROT_NONE | VM_PROT_WRITE | VM_PROT_EXECUTE:
2861		case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_NONE:
2862		case VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE:
2863			*kp++ = PG_RW;
2864			break;
2865		}
2866	}
2867}
2868
2869/*
2870 * Map a set of physical memory pages into the kernel virtual
2871 * address space. Return a pointer to where it is mapped. This
2872 * routine is intended to be used for mapping device memory,
2873 * NOT real memory.
2874 */
2875void *
2876pmap_mapdev(pa, size)
2877	vm_paddr_t pa;
2878	vm_size_t size;
2879{
2880	vm_offset_t va, tmpva, offset;
2881
2882	offset = pa & PAGE_MASK;
2883	size = roundup(offset + size, PAGE_SIZE);
2884	pa = pa & PG_FRAME;
2885
2886	if (pa < KERNLOAD && pa + size <= KERNLOAD)
2887		va = KERNBASE + pa;
2888	else
2889		va = kmem_alloc_nofault(kernel_map, size);
2890	if (!va)
2891		panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
2892
2893	for (tmpva = va; size > 0; ) {
2894		pmap_kenter(tmpva, pa);
2895		size -= PAGE_SIZE;
2896		tmpva += PAGE_SIZE;
2897		pa += PAGE_SIZE;
2898	}
2899	pmap_invalidate_range(kernel_pmap, va, tmpva);
2900	return ((void *)(va + offset));
2901}
2902
2903void
2904pmap_unmapdev(va, size)
2905	vm_offset_t va;
2906	vm_size_t size;
2907{
2908	vm_offset_t base, offset, tmpva;
2909
2910	if (va >= KERNBASE && va + size <= KERNBASE + KERNLOAD)
2911		return;
2912	base = va & PG_FRAME;
2913	offset = va & PAGE_MASK;
2914	size = roundup(offset + size, PAGE_SIZE);
2915	for (tmpva = base; tmpva < (base + size); tmpva += PAGE_SIZE)
2916		pmap_kremove(tmpva);
2917	pmap_invalidate_range(kernel_pmap, va, tmpva);
2918	kmem_free(kernel_map, base, size);
2919}
2920
2921/*
2922 * perform the pmap work for mincore
2923 */
2924int
2925pmap_mincore(pmap, addr)
2926	pmap_t pmap;
2927	vm_offset_t addr;
2928{
2929	pt_entry_t *ptep, pte;
2930	vm_page_t m;
2931	int val = 0;
2932
2933	ptep = pmap_pte_quick(pmap, addr);
2934	if (ptep == 0) {
2935		return 0;
2936	}
2937
2938	if ((pte = *ptep) != 0) {
2939		vm_paddr_t pa;
2940
2941		val = MINCORE_INCORE;
2942		if ((pte & PG_MANAGED) == 0)
2943			return val;
2944
2945		pa = pte & PG_FRAME;
2946
2947		m = PHYS_TO_VM_PAGE(pa);
2948
2949		/*
2950		 * Modified by us
2951		 */
2952		if (pte & PG_M)
2953			val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
2954		else {
2955			/*
2956			 * Modified by someone else
2957			 */
2958			vm_page_lock_queues();
2959			if (m->dirty || pmap_is_modified(m))
2960				val |= MINCORE_MODIFIED_OTHER;
2961			vm_page_unlock_queues();
2962		}
2963		/*
2964		 * Referenced by us
2965		 */
2966		if (pte & PG_A)
2967			val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
2968		else {
2969			/*
2970			 * Referenced by someone else
2971			 */
2972			vm_page_lock_queues();
2973			if ((m->flags & PG_REFERENCED) ||
2974			    pmap_ts_referenced(m)) {
2975				val |= MINCORE_REFERENCED_OTHER;
2976				vm_page_flag_set(m, PG_REFERENCED);
2977			}
2978			vm_page_unlock_queues();
2979		}
2980	}
2981	return val;
2982}
2983
2984void
2985pmap_activate(struct thread *td)
2986{
2987	struct proc *p = td->td_proc;
2988	pmap_t	pmap, oldpmap;
2989	u_int32_t  cr3;
2990
2991	critical_enter();
2992	pmap = vmspace_pmap(td->td_proc->p_vmspace);
2993	oldpmap = PCPU_GET(curpmap);
2994#if defined(SMP)
2995	atomic_clear_int(&oldpmap->pm_active, PCPU_GET(cpumask));
2996	atomic_set_int(&pmap->pm_active, PCPU_GET(cpumask));
2997#else
2998	oldpmap->pm_active &= ~1;
2999	pmap->pm_active |= 1;
3000#endif
3001#ifdef PAE
3002	cr3 = vtophys(pmap->pm_pdpt);
3003#else
3004	cr3 = vtophys(pmap->pm_pdir);
3005#endif
3006	/* XXXKSE this is wrong.
3007	 * pmap_activate is for the current thread on the current cpu
3008	 */
3009	if (p->p_flag & P_SA) {
3010		/* Make sure all other cr3 entries are updated. */
3011		/* what if they are running?  XXXKSE (maybe abort them) */
3012		FOREACH_THREAD_IN_PROC(p, td) {
3013			td->td_pcb->pcb_cr3 = cr3;
3014		}
3015	} else {
3016		td->td_pcb->pcb_cr3 = cr3;
3017	}
3018	load_cr3(cr3);
3019	PCPU_SET(curpmap, pmap);
3020	critical_exit();
3021}
3022
3023vm_offset_t
3024pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
3025{
3026
3027	if ((obj == NULL) || (size < NBPDR) || (obj->type != OBJT_DEVICE)) {
3028		return addr;
3029	}
3030
3031	addr = (addr + PDRMASK) & ~PDRMASK;
3032	return addr;
3033}
3034
3035
3036#if defined(PMAP_DEBUG)
3037pmap_pid_dump(int pid)
3038{
3039	pmap_t pmap;
3040	struct proc *p;
3041	int npte = 0;
3042	int index;
3043
3044	sx_slock(&allproc_lock);
3045	LIST_FOREACH(p, &allproc, p_list) {
3046		if (p->p_pid != pid)
3047			continue;
3048
3049		if (p->p_vmspace) {
3050			int i,j;
3051			index = 0;
3052			pmap = vmspace_pmap(p->p_vmspace);
3053			for (i = 0; i < NPDEPTD; i++) {
3054				pd_entry_t *pde;
3055				pt_entry_t *pte;
3056				vm_offset_t base = i << PDRSHIFT;
3057
3058				pde = &pmap->pm_pdir[i];
3059				if (pde && pmap_pde_v(pde)) {
3060					for (j = 0; j < NPTEPG; j++) {
3061						vm_offset_t va = base + (j << PAGE_SHIFT);
3062						if (va >= (vm_offset_t) VM_MIN_KERNEL_ADDRESS) {
3063							if (index) {
3064								index = 0;
3065								printf("\n");
3066							}
3067							sx_sunlock(&allproc_lock);
3068							return npte;
3069						}
3070						pte = pmap_pte_quick(pmap, va);
3071						if (pte && pmap_pte_v(pte)) {
3072							pt_entry_t pa;
3073							vm_page_t m;
3074							pa = *pte;
3075							m = PHYS_TO_VM_PAGE(pa);
3076							printf("va: 0x%x, pt: 0x%x, h: %d, w: %d, f: 0x%x",
3077								va, pa, m->hold_count, m->wire_count, m->flags);
3078							npte++;
3079							index++;
3080							if (index >= 2) {
3081								index = 0;
3082								printf("\n");
3083							} else {
3084								printf(" ");
3085							}
3086						}
3087					}
3088				}
3089			}
3090		}
3091	}
3092	sx_sunlock(&allproc_lock);
3093	return npte;
3094}
3095#endif
3096
3097#if defined(DEBUG)
3098
3099static void	pads(pmap_t pm);
3100void		pmap_pvdump(vm_offset_t pa);
3101
3102/* print address space of pmap*/
3103static void
3104pads(pm)
3105	pmap_t pm;
3106{
3107	int i, j;
3108	vm_paddr_t va;
3109	pt_entry_t *ptep;
3110
3111	if (pm == kernel_pmap)
3112		return;
3113	for (i = 0; i < NPDEPTD; i++)
3114		if (pm->pm_pdir[i])
3115			for (j = 0; j < NPTEPG; j++) {
3116				va = (i << PDRSHIFT) + (j << PAGE_SHIFT);
3117				if (pm == kernel_pmap && va < KERNBASE)
3118					continue;
3119				if (pm != kernel_pmap && va > UPT_MAX_ADDRESS)
3120					continue;
3121				ptep = pmap_pte_quick(pm, va);
3122				if (pmap_pte_v(ptep))
3123					printf("%x:%x ", va, *ptep);
3124			};
3125
3126}
3127
3128void
3129pmap_pvdump(pa)
3130	vm_paddr_t pa;
3131{
3132	pv_entry_t pv;
3133	vm_page_t m;
3134
3135	printf("pa %x", pa);
3136	m = PHYS_TO_VM_PAGE(pa);
3137	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3138		printf(" -> pmap %p, va %x", (void *)pv->pv_pmap, pv->pv_va);
3139		pads(pv->pv_pmap);
3140	}
3141	printf(" ");
3142}
3143#endif
3144