pmap.c revision 123925
1139826Simp/*-
253541Sshin * Copyright (c) 1991 Regents of the University of California.
353541Sshin * All rights reserved.
453541Sshin * Copyright (c) 1994 John S. Dyson
553541Sshin * All rights reserved.
653541Sshin * Copyright (c) 1994 David Greenman
753541Sshin * All rights reserved.
853541Sshin *
953541Sshin * This code is derived from software contributed to Berkeley by
1053541Sshin * the Systems Programming Group of the University of Utah Computer
1153541Sshin * Science Department and William Jolitz of UUNET Technologies Inc.
1253541Sshin *
1353541Sshin * Redistribution and use in source and binary forms, with or without
1453541Sshin * modification, are permitted provided that the following conditions
1553541Sshin * are met:
1653541Sshin * 1. Redistributions of source code must retain the above copyright
1753541Sshin *    notice, this list of conditions and the following disclaimer.
1853541Sshin * 2. Redistributions in binary form must reproduce the above copyright
1953541Sshin *    notice, this list of conditions and the following disclaimer in the
2053541Sshin *    documentation and/or other materials provided with the distribution.
2153541Sshin * 3. All advertising materials mentioning features or use of this software
2253541Sshin *    must display the following acknowledgement:
2353541Sshin *	This product includes software developed by the University of
2453541Sshin *	California, Berkeley and its contributors.
2553541Sshin * 4. Neither the name of the University nor the names of its contributors
2653541Sshin *    may be used to endorse or promote products derived from this software
2753541Sshin *    without specific prior written permission.
28174510Sobrien *
29174510Sobrien * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
3053541Sshin * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3153541Sshin * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32174510Sobrien * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33174510Sobrien * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34174510Sobrien * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3562587Sitojun * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3662587Sitojun * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37225044Sbz * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3855009Sshin * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39148921Ssuz * SUCH DAMAGE.
4053541Sshin *
4153541Sshin *	from:	@(#)pmap.c	7.7 (Berkeley)	5/12/91
4253541Sshin */
4378064Sume/*-
4453541Sshin * Copyright (c) 2003 Networks Associates Technology, Inc.
4553541Sshin * All rights reserved.
4653541Sshin *
4753541Sshin * This software was developed for the FreeBSD Project by Jake Burkholder,
4853541Sshin * Safeport Network Services, and Network Associates Laboratories, the
4953541Sshin * Security Research Division of Network Associates, Inc. under
5078064Sume * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
5153541Sshin * CHATS research program.
5253541Sshin *
5353541Sshin * Redistribution and use in source and binary forms, with or without
54225044Sbz * modification, are permitted provided that the following conditions
5553541Sshin * are met:
5684994Sdarrenr * 1. Redistributions of source code must retain the above copyright
5753541Sshin *    notice, this list of conditions and the following disclaimer.
5853541Sshin * 2. Redistributions in binary form must reproduce the above copyright
5953541Sshin *    notice, this list of conditions and the following disclaimer in the
6078064Sume *    documentation and/or other materials provided with the distribution.
6178064Sume *
6262587Sitojun * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
6378064Sume * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
6462587Sitojun * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
6553541Sshin * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
66148385Sume * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
6762587Sitojun * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
6853541Sshin * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
6953541Sshin * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
7078064Sume * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
7178064Sume * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
72171167Sgnn * SUCH DAMAGE.
73105199Ssam */
74105199Ssam
75105199Ssam#include <sys/cdefs.h>
76171167Sgnn__FBSDID("$FreeBSD: head/sys/i386/i386/pmap.c 123925 2003-12-28 05:10:21Z alc $");
77105199Ssam
7884994Sdarrenr/*
7984994Sdarrenr *	Manages physical address maps.
8053541Sshin *
8153541Sshin *	In addition to hardware address maps, this
8253541Sshin *	module is called upon to provide software-use-only
8353541Sshin *	maps which may or may not be stored in the same
8453541Sshin *	form as hardware maps.  These pseudo-maps are
8553541Sshin *	used to store intermediate results from copy
8653541Sshin *	operations to and from address spaces.
8753541Sshin *
8853541Sshin *	Since the information managed by this module is
8953541Sshin *	also stored by the logical address mapping module,
9053541Sshin *	this module may throw away valid virtual-to-physical
9153541Sshin *	mappings at almost any time.  However, invalidations
9253541Sshin *	of virtual-to-physical mappings must be done as
93171259Sdelphij *	requested.
9453541Sshin *
9553541Sshin *	In order to cope with hardware architectures which
96122062Sume *	make virtual-to-physical map invalidates expensive,
97122062Sume *	this module may delay invalidate or reduced protection
98187989Sbz *	operations until such time as they are actually
9953541Sshin *	necessary.  This module is given full information as
10062587Sitojun *	to which processors are currently using which maps,
10162587Sitojun *	and to when physical maps must be made correct.
102148385Sume */
103225044Sbz
104171167Sgnn#include "opt_pmap.h"
10553541Sshin#include "opt_msgbuf.h"
106122062Sume#include "opt_kstack_pages.h"
10753541Sshin
108225044Sbz#include <sys/param.h>
109225044Sbz#include <sys/systm.h>
110225044Sbz#include <sys/kernel.h>
111225044Sbz#include <sys/lock.h>
112165118Sbz#include <sys/mman.h>
11353541Sshin#include <sys/msgbuf.h>
114171167Sgnn#include <sys/mutex.h>
11553541Sshin#include <sys/proc.h>
11653541Sshin#include <sys/sx.h>
11753541Sshin#include <sys/user.h>
11853541Sshin#include <sys/vmmeter.h>
11953541Sshin#include <sys/sysctl.h>
12053541Sshin#ifdef SMP
12153541Sshin#include <sys/smp.h>
12253541Sshin#endif
123253571Sae
12453541Sshin#include <vm/vm.h>
12553541Sshin#include <vm/vm_param.h>
12653541Sshin#include <vm/vm_kern.h>
127171167Sgnn#include <vm/vm_page.h>
12853541Sshin#include <vm/vm_map.h>
12978064Sume#include <vm/vm_object.h>
13078064Sume#include <vm/vm_extern.h>
13178064Sume#include <vm/vm_pageout.h>
13278064Sume#include <vm/vm_pager.h>
133120913Sume#include <vm/uma.h>
13478064Sume
13562587Sitojun#include <machine/cpu.h>
13678064Sume#include <machine/cputypes.h>
13778064Sume#include <machine/md_var.h>
138249294Sae#include <machine/specialreg.h>
13953541Sshin#ifdef SMP
140253970Shrs#include <machine/smp.h>
141253970Shrs#endif
14253541Sshin
14353541Sshin#define PMAP_KEEP_PDIRS
14453541Sshin#ifndef PMAP_SHPGPERPROC
145165118Sbz#define PMAP_SHPGPERPROC 200
146165118Sbz#endif
14753541Sshin
14853541Sshin#if defined(DIAGNOSTIC)
14953541Sshin#define PMAP_DIAGNOSTIC
15053541Sshin#endif
15153541Sshin
15253541Sshin#define MINPV 2048
15353541Sshin
154148921Ssuz#if !defined(PMAP_DIAGNOSTIC)
155181803Sbz#define PMAP_INLINE __inline
156148921Ssuz#else
15753541Sshin#define PMAP_INLINE
15853541Sshin#endif
15953541Sshin
16053541Sshin/*
16153541Sshin * Get PDEs and PTEs for user/kernel address space
16253541Sshin */
16353541Sshin#define	pmap_pde(m, v)	(&((m)->pm_pdir[(vm_offset_t)(v) >> PDRSHIFT]))
16453541Sshin#define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
165148921Ssuz
166148921Ssuz#define pmap_pde_v(pte)		((*(int *)pte & PG_V) != 0)
167148921Ssuz#define pmap_pte_w(pte)		((*(int *)pte & PG_W) != 0)
168148921Ssuz#define pmap_pte_m(pte)		((*(int *)pte & PG_M) != 0)
16962587Sitojun#define pmap_pte_u(pte)		((*(int *)pte & PG_A) != 0)
17062587Sitojun#define pmap_pte_v(pte)		((*(int *)pte & PG_V) != 0)
17162587Sitojun
17262587Sitojun#define pmap_pte_set_w(pte, v) ((v)?(*(int *)pte |= PG_W):(*(int *)pte &= ~PG_W))
17362587Sitojun#define pmap_pte_set_prot(pte, v) ((*(int *)pte &= ~PG_PROT), (*(int *)pte |= (v)))
17462587Sitojun
17562587Sitojunstruct pmap kernel_pmap_store;
17662587SitojunLIST_HEAD(pmaplist, pmap);
17762587Sitojunstatic struct pmaplist allpmaps;
17862587Sitojunstatic struct mtx allpmaps_lock;
17962587Sitojun#ifdef SMP
180171167Sgnnstatic struct mtx lazypmap_lock;
18153541Sshin#endif
182171133Sgnn
183120913Sumevm_paddr_t avail_start;	/* PA of first available physical page */
18453541Sshinvm_paddr_t avail_end;	/* PA of last available physical page */
185253571Saevm_offset_t virtual_avail;	/* VA of first avail page (after kernel bss) */
186249294Saevm_offset_t virtual_end;	/* VA of last avail page (end of kernel AS) */
18762587Sitojunstatic boolean_t pmap_initialized = FALSE;	/* Has pmap_init completed? */
18862587Sitojunint pgeflag = 0;		/* PG_G or-in */
18962587Sitojunint pseflag = 0;		/* PG_PS or-in */
19062587Sitojun
19162587Sitojunstatic int nkpt;
19262587Sitojunvm_offset_t kernel_vm_end;
19362587Sitojunextern u_int32_t KERNend;
19453541Sshin
19553541Sshin#ifdef PAE
19653541Sshinstatic uma_zone_t pdptzone;
19753541Sshin#endif
19853541Sshin
19953541Sshin/*
20053541Sshin * Data for the pv entry allocation mechanism
20153541Sshin */
20253541Sshinstatic uma_zone_t pvzone;
20353541Sshinstatic struct vm_object pvzone_obj;
20453541Sshinstatic int pv_entry_count = 0, pv_entry_max = 0, pv_entry_high_water = 0;
20553541Sshinint pmap_pagedaemon_waken;
206253571Sae
207249294Sae/*
208171133Sgnn * All those kernel PT submaps that BSD is so fond of
20962587Sitojun */
21062587Sitojunpt_entry_t *CMAP1 = 0;
21162587Sitojunstatic pt_entry_t *CMAP2, *CMAP3, *ptmmap;
21262587Sitojuncaddr_t CADDR1 = 0, ptvmmap = 0;
21362587Sitojunstatic caddr_t CADDR2, CADDR3;
21462587Sitojunstatic struct mtx CMAPCADDR12_lock;
21562587Sitojunstatic pt_entry_t *msgbufmap;
21653541Sshinstruct msgbuf *msgbufp = 0;
21753541Sshin
21853541Sshin/*
21953541Sshin * Crashdump maps.
22053541Sshin */
22153541Sshinstatic pt_entry_t *pt_crashdumpmap;
222171133Sgnnstatic caddr_t crashdumpmap;
22353541Sshin
22462587Sitojun#ifdef SMP
22553541Sshinextern pt_entry_t *SMPpt;
22653541Sshin#endif
22753541Sshinstatic pt_entry_t *PMAP1 = 0, *PMAP2;
22853541Sshinstatic pt_entry_t *PADDR1 = 0, *PADDR2;
229249294Sae
230171133Sgnnstatic PMAP_INLINE void	free_pv_entry(pv_entry_t pv);
23162587Sitojunstatic pv_entry_t get_pv_entry(void);
23262587Sitojunstatic void	pmap_clear_ptes(vm_page_t m, int bit)
23362587Sitojun    __always_inline;
23462587Sitojun
23562587Sitojunstatic int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva);
23662587Sitojunstatic void pmap_remove_page(struct pmap *pmap, vm_offset_t va);
23762587Sitojunstatic int pmap_remove_entry(struct pmap *pmap, vm_page_t m,
23853541Sshin					vm_offset_t va);
23953541Sshinstatic void pmap_insert_entry(pmap_t pmap, vm_offset_t va,
24053541Sshin		vm_page_t mpte, vm_page_t m);
24153541Sshin
24253541Sshinstatic vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va);
24353541Sshin
24453541Sshinstatic vm_page_t _pmap_allocpte(pmap_t pmap, unsigned ptepindex);
24553541Sshinstatic pt_entry_t *pmap_pte_quick(pmap_t pmap, vm_offset_t va);
24653541Sshinstatic int pmap_unuse_pt(pmap_t, vm_offset_t, vm_page_t);
24753541Sshinstatic vm_offset_t pmap_kmem_choose(vm_offset_t addr);
248171133Sgnn#ifdef PAE
24953541Sshinstatic void *pmap_pdpt_allocf(uma_zone_t zone, int bytes, u_int8_t *flags, int wait);
25053541Sshin#endif
25153541Sshin
25253541SshinCTASSERT(1 << PDESHIFT == sizeof(pd_entry_t));
253122062SumeCTASSERT(1 << PTESHIFT == sizeof(pt_entry_t));
25453541Sshin
25553541Sshin/*
25653541Sshin * Move the kernel virtual free pointer to the next
257122062Sume * 4MB.  This is used to help improve performance
258122062Sume * by using a large (4MB) page for much of the kernel
259122062Sume * (.text, .data, .bss)
260122062Sume */
261122062Sumestatic vm_offset_t
262122062Sumepmap_kmem_choose(vm_offset_t addr)
263122062Sume{
264122062Sume	vm_offset_t newaddr = addr;
265122062Sume
266126006Sume#ifndef DISABLE_PSE
267126006Sume	if (cpu_feature & CPUID_PSE)
268126006Sume		newaddr = (addr + PDRMASK) & ~PDRMASK;
269126006Sume#endif
270122062Sume	return newaddr;
271122062Sume}
272122062Sume
273126006Sume/*
274126006Sume *	Bootstrap the system enough to run with virtual memory.
275126006Sume *
276126006Sume *	On the i386 this is called after mapping has already been enabled
277126006Sume *	and just syncs the pmap module with what has already been done.
278126006Sume *	[We can't call it easily with mapping off since the kernel is not
279126006Sume *	mapped with PA == VA, hence we would have to relocate every address
28053541Sshin *	from the linked base (virtual) address "KERNBASE" to the actual
28153541Sshin *	(physical) address starting relative to 0]
28253541Sshin */
28353541Sshinvoid
28453541Sshinpmap_bootstrap(firstaddr, loadaddr)
28553541Sshin	vm_paddr_t firstaddr;
28653541Sshin	vm_paddr_t loadaddr;
28753541Sshin{
28853541Sshin	vm_offset_t va;
28953541Sshin	pt_entry_t *pte;
29053541Sshin	int i;
29153541Sshin
29253541Sshin	avail_start = firstaddr;
29353541Sshin
29453541Sshin	/*
295171133Sgnn	 * XXX The calculation of virtual_avail is wrong. It's NKPT*PAGE_SIZE too
29653541Sshin	 * large. It should instead be correctly calculated in locore.s and
29753541Sshin	 * not based on 'first' (which is a physical address, not a virtual
29853541Sshin	 * address, for the start of unused physical memory). The kernel
29953541Sshin	 * page tables are NOT double mapped and thus should not be included
30053541Sshin	 * in this calculation.
30153541Sshin	 */
30253541Sshin	virtual_avail = (vm_offset_t) KERNBASE + firstaddr;
30353541Sshin	virtual_avail = pmap_kmem_choose(virtual_avail);
30453541Sshin
30553541Sshin	virtual_end = VM_MAX_KERNEL_ADDRESS;
30653541Sshin
30753541Sshin	/*
308120913Sume	 * Initialize the kernel pmap (which is statically allocated).
30953541Sshin	 */
31053541Sshin	kernel_pmap->pm_pdir = (pd_entry_t *) (KERNBASE + (u_int)IdlePTD);
31153541Sshin#ifdef PAE
31253541Sshin	kernel_pmap->pm_pdpt = (pdpt_entry_t *) (KERNBASE + (u_int)IdlePDPT);
313249294Sae#endif
31462587Sitojun	kernel_pmap->pm_active = -1;	/* don't allow deactivation */
31562587Sitojun	TAILQ_INIT(&kernel_pmap->pm_pvlist);
31662587Sitojun	LIST_INIT(&allpmaps);
31762587Sitojun#ifdef SMP
31862587Sitojun	mtx_init(&lazypmap_lock, "lazypmap", NULL, MTX_SPIN);
31962587Sitojun#endif
32062587Sitojun	mtx_init(&allpmaps_lock, "allpmaps", NULL, MTX_SPIN);
32153541Sshin	mtx_lock_spin(&allpmaps_lock);
32253541Sshin	LIST_INSERT_HEAD(&allpmaps, kernel_pmap, pm_list);
323171133Sgnn	mtx_unlock_spin(&allpmaps_lock);
324171260Sdelphij	nkpt = NKPT;
325171260Sdelphij
326171133Sgnn	/*
327171260Sdelphij	 * Reserve some special page table entries/VA space for temporary
328171133Sgnn	 * mapping of pages.
329171133Sgnn	 */
330171133Sgnn#define	SYSMAP(c, p, v, n)	\
331171133Sgnn	v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
33253541Sshin
333122062Sume	va = virtual_avail;
334171133Sgnn	pte = vtopte(va);
335126006Sume
336126006Sume	/*
337126006Sume	 * CMAP1/CMAP2 are used for zeroing and copying pages.
338126006Sume	 * CMAP3 is used for the idle process page zeroing.
339126006Sume	 */
340126006Sume	SYSMAP(caddr_t, CMAP1, CADDR1, 1)
341126006Sume	SYSMAP(caddr_t, CMAP2, CADDR2, 1)
342126006Sume	SYSMAP(caddr_t, CMAP3, CADDR3, 1)
343126006Sume	*CMAP3 = 0;
344122062Sume
345122062Sume	mtx_init(&CMAPCADDR12_lock, "CMAPCADDR12", NULL, MTX_DEF);
346122062Sume
347122062Sume	/*
348122062Sume	 * Crashdump maps.
34953541Sshin	 */
350122062Sume	SYSMAP(caddr_t, pt_crashdumpmap, crashdumpmap, MAXDUMPPGS);
351122062Sume
352187949Sbz	/*
353122062Sume	 * ptvmmap is used for reading arbitrary physical pages via /dev/mem.
354225044Sbz	 * XXX ptmmap is not used.
355187989Sbz	 */
356187989Sbz	SYSMAP(caddr_t, ptmmap, ptvmmap, 1)
357187989Sbz
358187989Sbz	/*
359187989Sbz	 * msgbufp is used to map the system message buffer.
360225044Sbz	 * XXX msgbufmap is not used.
361231852Sbz	 */
362187989Sbz	SYSMAP(struct msgbuf *, msgbufmap, msgbufp,
363187989Sbz	       atop(round_page(MSGBUF_SIZE)))
364187989Sbz
365249294Sae	/*
366187989Sbz	 * ptemap is used for pmap_pte_quick
367187989Sbz	 */
368187989Sbz	SYSMAP(pt_entry_t *, PMAP1, PADDR1, 1);
369187989Sbz	SYSMAP(pt_entry_t *, PMAP2, PADDR2, 1);
37053541Sshin
371187989Sbz	virtual_avail = va;
37253541Sshin
373187989Sbz	*CMAP1 = *CMAP2 = 0;
374171167Sgnn	for (i = 0; i < NKPT; i++)
375187989Sbz		PTD[i] = 0;
376122062Sume
37762587Sitojun	/* Turn on PG_G on kernel page(s) */
37862587Sitojun	pmap_set_pg();
379148385Sume}
380148385Sume
381148385Sume/*
382148385Sume * Set PG_G on kernel pages.  Only the BSP calls this when SMP is turned on.
383148385Sume */
384148385Sumevoid
385148385Sumepmap_set_pg(void)
38662587Sitojun{
387148385Sume	pd_entry_t pdir;
388148385Sume	pt_entry_t *pte;
389122062Sume	vm_offset_t va, endva;
390249294Sae	int i;
391249294Sae
392187989Sbz	if (pgeflag == 0)
393122062Sume		return;
394148385Sume
395249294Sae	i = KERNLOAD/NBPDR;
396249294Sae	endva = KERNBASE + KERNend;
397187989Sbz
398148385Sume	if (pseflag) {
399148385Sume		va = KERNBASE + KERNLOAD;
400171167Sgnn		while (va  < endva) {
401122062Sume			pdir = kernel_pmap->pm_pdir[KPTDI+i];
402122062Sume			pdir |= pgeflag;
403122062Sume			kernel_pmap->pm_pdir[KPTDI+i] = PTD[KPTDI+i] = pdir;
404249294Sae			invltlb();	/* Play it safe, invltlb() every time */
405249294Sae			i++;
40662587Sitojun			va += NBPDR;
40762587Sitojun		}
408253970Shrs	} else {
409253970Shrs		va = (vm_offset_t)btext;
41062587Sitojun		while (va < endva) {
41162587Sitojun			pte = vtopte(va);
41262587Sitojun			if (*pte)
413165118Sbz				*pte |= pgeflag;
414165118Sbz			invltlb();	/* Play it safe, invltlb() every time */
41562587Sitojun			va += PAGE_SIZE;
41662587Sitojun		}
41762587Sitojun	}
41862587Sitojun}
41962587Sitojun
42062587Sitojun#ifdef PAE
421187989Sbzstatic void *
42262587Sitojunpmap_pdpt_allocf(uma_zone_t zone, int bytes, u_int8_t *flags, int wait)
42362587Sitojun{
424148385Sume	*flags = UMA_SLAB_PRIV;
425148385Sume	return (contigmalloc(PAGE_SIZE, NULL, 0, 0x0ULL, 0xffffffffULL, 1, 0));
426148385Sume}
427148385Sume#endif
428148385Sume
429148385Sume/*
430148385Sume *	Initialize the pmap module.
431148385Sume *	Called by vm_init, to initialize any structures that the pmap
432148385Sume *	system needs to map virtual memory.
433148385Sume *	pmap_init has been enhanced to support in a fairly consistant
434148385Sume *	way, discontiguous physical memory.
435249294Sae */
436249294Saevoid
437187989Sbzpmap_init(phys_start, phys_end)
438148385Sume	vm_paddr_t phys_start, phys_end;
439148385Sume{
440121283Sume	int i;
44153541Sshin
44262587Sitojun	/*
44362587Sitojun	 * Allocate memory for random pmap data structures.  Includes the
444171167Sgnn	 * pv_head_table.
44562587Sitojun	 */
44662587Sitojun
44762587Sitojun	for(i = 0; i < vm_page_array_size; i++) {
448171167Sgnn		vm_page_t m;
44962587Sitojun
450121283Sume		m = &vm_page_array[i];
451171167Sgnn		TAILQ_INIT(&m->md.pv_list);
45262587Sitojun		m->md.pv_list_count = 0;
45362587Sitojun	}
454122062Sume
45562587Sitojun	/*
45662587Sitojun	 * init the pv free list
45762587Sitojun	 */
45862587Sitojun	pvzone = uma_zcreate("PV ENTRY", sizeof (struct pv_entry), NULL, NULL,
459171133Sgnn	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_VM | UMA_ZONE_NOFREE);
46062587Sitojun	uma_prealloc(pvzone, MINPV);
46162587Sitojun
462188306Sbz#ifdef PAE
46362587Sitojun	pdptzone = uma_zcreate("PDPT", NPGPTD * sizeof(pdpt_entry_t), NULL,
46462587Sitojun	    NULL, NULL, NULL, (NPGPTD * sizeof(pdpt_entry_t)) - 1,
46562587Sitojun	    UMA_ZONE_VM | UMA_ZONE_NOFREE);
46662587Sitojun	uma_zone_set_allocf(pdptzone, pmap_pdpt_allocf);
46762587Sitojun#endif
46862587Sitojun
46962587Sitojun	/*
47062587Sitojun	 * Now it is safe to enable pv_table recording.
47162587Sitojun	 */
47262587Sitojun	pmap_initialized = TRUE;
47362587Sitojun}
474171167Sgnn
47562587Sitojun/*
47662587Sitojun * Initialize the address space (zone) for the pv_entries.  Set a
477187989Sbz * high water mark so that the system can recover from excessive
478120913Sume * numbers of pv entries.
47953541Sshin */
48053541Sshinvoid
48153541Sshinpmap_init2()
48253541Sshin{
48353541Sshin	int shpgperproc = PMAP_SHPGPERPROC;
48453541Sshin
48553541Sshin	TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
48653541Sshin	pv_entry_max = shpgperproc * maxproc + vm_page_array_size;
48753541Sshin	TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
48853541Sshin	pv_entry_high_water = 9 * (pv_entry_max / 10);
48953541Sshin	uma_zone_set_obj(pvzone, &pvzone_obj, pv_entry_max);
49053541Sshin}
49153541Sshin
492181803Sbz
493171167Sgnn/***************************************************
494122062Sume * Low level helper routines.....
495171167Sgnn ***************************************************/
49678064Sume
49778064Sume#if defined(PMAP_DIAGNOSTIC)
49878064Sume
49978064Sume/*
50078064Sume * This code checks for non-writeable/modified pages.
50178064Sume * This should be an invalid condition.
50278064Sume */
50378064Sumestatic int
50478064Sumepmap_nw_modified(pt_entry_t ptea)
50578064Sume{
50678064Sume	int pte;
50778064Sume
50878064Sume	pte = (int) ptea;
50978064Sume
510187989Sbz	if ((pte & (PG_M|PG_RW)) == PG_M)
51178064Sume		return 1;
51253541Sshin	else
51378064Sume		return 0;
51453541Sshin}
51553541Sshin#endif
51662587Sitojun
51762587Sitojun
51862587Sitojun/*
51962587Sitojun * this routine defines the region(s) of memory that should
52078064Sume * not be tested for the modified bit.
52178064Sume */
52262587Sitojunstatic PMAP_INLINE int
52362587Sitojunpmap_track_modified(vm_offset_t va)
52462587Sitojun{
52562587Sitojun	if ((va < kmi.clean_sva) || (va >= kmi.clean_eva))
52662587Sitojun		return 1;
52762587Sitojun	else
52862587Sitojun		return 0;
52962587Sitojun}
53062587Sitojun
53162587Sitojun#ifdef I386_CPU
53262587Sitojun/*
53362587Sitojun * i386 only has "invalidate everything" and no SMP to worry about.
53462587Sitojun */
53562587SitojunPMAP_INLINE void
53662587Sitojunpmap_invalidate_page(pmap_t pmap, vm_offset_t va)
53762587Sitojun{
53862587Sitojun
53962587Sitojun	if (pmap == kernel_pmap || pmap->pm_active)
540120913Sume		invltlb();
541165118Sbz}
542165118Sbz
543120913SumePMAP_INLINE void
544120913Sumepmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
54562587Sitojun{
54662587Sitojun
54778064Sume	if (pmap == kernel_pmap || pmap->pm_active)
54878064Sume		invltlb();
54962587Sitojun}
55062587Sitojun
55162587SitojunPMAP_INLINE void
55278064Sumepmap_invalidate_all(pmap_t pmap)
55378064Sume{
55478064Sume
55578064Sume	if (pmap == kernel_pmap || pmap->pm_active)
55678064Sume		invltlb();
55778064Sume}
55862587Sitojun#else /* !I386_CPU */
559134383Sandre#ifdef SMP
560197952Sjulian/*
561134383Sandre * For SMP, these functions have to use the IPI mechanism for coherence.
562134383Sandre */
563225044Sbzvoid
564134383Sandrepmap_invalidate_page(pmap_t pmap, vm_offset_t va)
565197952Sjulian{
566120593Ssam	u_int cpumask;
567120593Ssam	u_int other_cpus;
568120386Ssam
569120386Ssam	if (smp_started) {
570120386Ssam		if (!(read_eflags() & PSL_I))
57184994Sdarrenr			panic("%s: interrupts disabled", __func__);
572225044Sbz		mtx_lock_spin(&smp_tlb_mtx);
573225044Sbz	} else
574225044Sbz		critical_enter();
575225044Sbz	/*
576225044Sbz	 * We need to disable interrupt preemption but MUST NOT have
577225044Sbz	 * interrupts disabled here.
578225044Sbz	 * XXX we may need to hold schedlock to get a coherent pm_active
579225044Sbz	 * XXX critical sections disable interrupts again
580236170Sbz	 */
581225044Sbz	if (pmap == kernel_pmap || pmap->pm_active == all_cpus) {
582236170Sbz		invlpg(va);
583225044Sbz		smp_invlpg(va);
584225044Sbz	} else {
585225044Sbz		cpumask = PCPU_GET(cpumask);
586236332Stuexen		other_cpus = PCPU_GET(other_cpus);
587225044Sbz		if (pmap->pm_active & cpumask)
588225044Sbz			invlpg(va);
589225044Sbz		if (pmap->pm_active & other_cpus)
590225044Sbz			smp_masked_invlpg(pmap->pm_active & other_cpus, va);
591225044Sbz	}
592225044Sbz	if (smp_started)
593225044Sbz		mtx_unlock_spin(&smp_tlb_mtx);
594225044Sbz	else
595225044Sbz		critical_exit();
596225044Sbz}
597225044Sbz
598225044Sbzvoid
599236170Sbzpmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
600225044Sbz{
601236170Sbz	u_int cpumask;
602225044Sbz	u_int other_cpus;
603225044Sbz	vm_offset_t addr;
604225044Sbz
605236332Stuexen	if (smp_started) {
606236332Stuexen		if (!(read_eflags() & PSL_I))
607236332Stuexen			panic("%s: interrupts disabled", __func__);
608225044Sbz		mtx_lock_spin(&smp_tlb_mtx);
609225044Sbz	} else
610225044Sbz		critical_enter();
611225044Sbz	/*
612242463Sae	 * We need to disable interrupt preemption but MUST NOT have
613242463Sae	 * interrupts disabled here.
614225044Sbz	 * XXX we may need to hold schedlock to get a coherent pm_active
615225044Sbz	 * XXX critical sections disable interrupts again
616225044Sbz	 */
617242463Sae	if (pmap == kernel_pmap || pmap->pm_active == all_cpus) {
618225044Sbz		for (addr = sva; addr < eva; addr += PAGE_SIZE)
619225044Sbz			invlpg(addr);
620225044Sbz		smp_invlpg_range(sva, eva);
621225044Sbz	} else {
622134383Sandre		cpumask = PCPU_GET(cpumask);
62362587Sitojun		other_cpus = PCPU_GET(other_cpus);
62453541Sshin		if (pmap->pm_active & cpumask)
62553541Sshin			for (addr = sva; addr < eva; addr += PAGE_SIZE)
626249294Sae				invlpg(addr);
62753541Sshin		if (pmap->pm_active & other_cpus)
628249294Sae			smp_masked_invlpg_range(pmap->pm_active & other_cpus,
62953541Sshin			    sva, eva);
63053541Sshin	}
631249294Sae	if (smp_started)
63253541Sshin		mtx_unlock_spin(&smp_tlb_mtx);
63353541Sshin	else
63453541Sshin		critical_exit();
63553541Sshin}
63653541Sshin
637120913Sumevoid
638120593Ssampmap_invalidate_all(pmap_t pmap)
63953541Sshin{
640187989Sbz	u_int cpumask;
64153541Sshin	u_int other_cpus;
64253541Sshin
64353541Sshin	if (smp_started) {
64453541Sshin		if (!(read_eflags() & PSL_I))
645187989Sbz			panic("%s: interrupts disabled", __func__);
64653541Sshin		mtx_lock_spin(&smp_tlb_mtx);
64753541Sshin	} else
64853541Sshin		critical_enter();
64953541Sshin	/*
65053541Sshin	 * We need to disable interrupt preemption but MUST NOT have
65153541Sshin	 * interrupts disabled here.
65253541Sshin	 * XXX we may need to hold schedlock to get a coherent pm_active
65353541Sshin	 * XXX critical sections disable interrupts again
65453541Sshin	 */
65553541Sshin	if (pmap == kernel_pmap || pmap->pm_active == all_cpus) {
65653541Sshin		invltlb();
65753541Sshin		smp_invltlb();
65853541Sshin	} else {
65953541Sshin		cpumask = PCPU_GET(cpumask);
66053541Sshin		other_cpus = PCPU_GET(other_cpus);
66153541Sshin		if (pmap->pm_active & cpumask)
66253541Sshin			invltlb();
66353541Sshin		if (pmap->pm_active & other_cpus)
66453541Sshin			smp_masked_invltlb(pmap->pm_active & other_cpus);
66553541Sshin	}
66653541Sshin	if (smp_started)
667187989Sbz		mtx_unlock_spin(&smp_tlb_mtx);
66853541Sshin	else
66953541Sshin		critical_exit();
67053541Sshin}
671187989Sbz#else /* !SMP */
672187989Sbz/*
673187989Sbz * Normal, non-SMP, 486+ invalidation functions.
674187989Sbz * We inline these within pmap.c for speed.
675187989Sbz */
676187989SbzPMAP_INLINE void
677187989Sbzpmap_invalidate_page(pmap_t pmap, vm_offset_t va)
678187989Sbz{
679187989Sbz
680187989Sbz	if (pmap == kernel_pmap || pmap->pm_active)
68153541Sshin		invlpg(va);
682}
683
684PMAP_INLINE void
685pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
686{
687	vm_offset_t addr;
688
689	if (pmap == kernel_pmap || pmap->pm_active)
690		for (addr = sva; addr < eva; addr += PAGE_SIZE)
691			invlpg(addr);
692}
693
694PMAP_INLINE void
695pmap_invalidate_all(pmap_t pmap)
696{
697
698	if (pmap == kernel_pmap || pmap->pm_active)
699		invltlb();
700}
701#endif /* !SMP */
702#endif /* !I386_CPU */
703
704/*
705 * Are we current address space or kernel?  N.B. We return FALSE when
706 * a pmap's page table is in use because a kernel thread is borrowing
707 * it.  The borrowed page table can change spontaneously, making any
708 * dependence on its continued use subject to a race condition.
709 */
710static __inline int
711pmap_is_current(pmap_t pmap)
712{
713
714	return (pmap == kernel_pmap ||
715		(pmap == vmspace_pmap(curthread->td_proc->p_vmspace) &&
716	    (pmap->pm_pdir[PTDPTDI] & PG_FRAME) == (PTDpde[0] & PG_FRAME)));
717}
718
719/*
720 * If the given pmap is not the current pmap, Giant must be held.
721 */
722pt_entry_t *
723pmap_pte(pmap_t pmap, vm_offset_t va)
724{
725	pd_entry_t newpf;
726	pd_entry_t *pde;
727
728	pde = pmap_pde(pmap, va);
729	if (*pde & PG_PS)
730		return (pde);
731	if (*pde != 0) {
732		/* are we current address space or kernel? */
733		if (pmap_is_current(pmap))
734			return (vtopte(va));
735		GIANT_REQUIRED;
736		newpf = *pde & PG_FRAME;
737		if ((*PMAP2 & PG_FRAME) != newpf) {
738			*PMAP2 = newpf | PG_RW | PG_V | PG_A | PG_M;
739			pmap_invalidate_page(kernel_pmap, (vm_offset_t)PADDR2);
740		}
741		return (PADDR2 + (i386_btop(va) & (NPTEPG - 1)));
742	}
743	return (0);
744}
745
746/*
747 * Super fast pmap_pte routine best used when scanning
748 * the pv lists.  This eliminates many coarse-grained
749 * invltlb calls.  Note that many of the pv list
750 * scans are across different pmaps.  It is very wasteful
751 * to do an entire invltlb for checking a single mapping.
752 *
753 * If the given pmap is not the current pmap, vm_page_queue_mtx
754 * must be held.
755 */
756static pt_entry_t *
757pmap_pte_quick(pmap_t pmap, vm_offset_t va)
758{
759	pd_entry_t newpf;
760	pd_entry_t *pde;
761
762	pde = pmap_pde(pmap, va);
763	if (*pde & PG_PS)
764		return (pde);
765	if (*pde != 0) {
766		/* are we current address space or kernel? */
767		if (pmap_is_current(pmap))
768			return (vtopte(va));
769		mtx_assert(&vm_page_queue_mtx, MA_OWNED);
770		newpf = *pde & PG_FRAME;
771		if ((*PMAP1 & PG_FRAME) != newpf) {
772			*PMAP1 = newpf | PG_RW | PG_V | PG_A | PG_M;
773			pmap_invalidate_page(kernel_pmap, (vm_offset_t)PADDR1);
774		}
775		return (PADDR1 + (i386_btop(va) & (NPTEPG - 1)));
776	}
777	return (0);
778}
779
780/*
781 *	Routine:	pmap_extract
782 *	Function:
783 *		Extract the physical page address associated
784 *		with the given map/virtual_address pair.
785 */
786vm_paddr_t
787pmap_extract(pmap, va)
788	register pmap_t pmap;
789	vm_offset_t va;
790{
791	vm_paddr_t rtval;
792	pt_entry_t *pte;
793	pd_entry_t pde;
794
795	if (pmap == 0)
796		return 0;
797	pde = pmap->pm_pdir[va >> PDRSHIFT];
798	if (pde != 0) {
799		if ((pde & PG_PS) != 0) {
800			rtval = (pde & ~PDRMASK) | (va & PDRMASK);
801			return rtval;
802		}
803		pte = pmap_pte(pmap, va);
804		rtval = ((*pte & PG_FRAME) | (va & PAGE_MASK));
805		return rtval;
806	}
807	return 0;
808
809}
810
811/*
812 *	Routine:	pmap_extract_and_hold
813 *	Function:
814 *		Atomically extract and hold the physical page
815 *		with the given pmap and virtual address pair
816 *		if that mapping permits the given protection.
817 */
818vm_page_t
819pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
820{
821	vm_paddr_t pa;
822	vm_page_t m;
823
824	m = NULL;
825	mtx_lock(&Giant);
826	if ((pa = pmap_extract(pmap, va)) != 0) {
827		m = PHYS_TO_VM_PAGE(pa);
828		vm_page_lock_queues();
829		vm_page_hold(m);
830		vm_page_unlock_queues();
831	}
832	mtx_unlock(&Giant);
833	return (m);
834}
835
836/***************************************************
837 * Low level mapping routines.....
838 ***************************************************/
839
840/*
841 * Add a wired page to the kva.
842 * Note: not SMP coherent.
843 */
844PMAP_INLINE void
845pmap_kenter(vm_offset_t va, vm_paddr_t pa)
846{
847	pt_entry_t *pte;
848
849	pte = vtopte(va);
850	pte_store(pte, pa | PG_RW | PG_V | pgeflag);
851}
852
853/*
854 * Remove a page from the kernel pagetables.
855 * Note: not SMP coherent.
856 */
857PMAP_INLINE void
858pmap_kremove(vm_offset_t va)
859{
860	pt_entry_t *pte;
861
862	pte = vtopte(va);
863	pte_clear(pte);
864}
865
866/*
867 *	Used to map a range of physical addresses into kernel
868 *	virtual address space.
869 *
870 *	The value passed in '*virt' is a suggested virtual address for
871 *	the mapping. Architectures which can support a direct-mapped
872 *	physical to virtual region can return the appropriate address
873 *	within that region, leaving '*virt' unchanged. Other
874 *	architectures should map the pages starting at '*virt' and
875 *	update '*virt' with the first usable address after the mapped
876 *	region.
877 */
878vm_offset_t
879pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
880{
881	vm_offset_t va, sva;
882
883	va = sva = *virt;
884	while (start < end) {
885		pmap_kenter(va, start);
886		va += PAGE_SIZE;
887		start += PAGE_SIZE;
888	}
889	pmap_invalidate_range(kernel_pmap, sva, va);
890	*virt = va;
891	return (sva);
892}
893
894
895/*
896 * Add a list of wired pages to the kva
897 * this routine is only used for temporary
898 * kernel mappings that do not need to have
899 * page modification or references recorded.
900 * Note that old mappings are simply written
901 * over.  The page *must* be wired.
902 * Note: SMP coherent.  Uses a ranged shootdown IPI.
903 */
904void
905pmap_qenter(vm_offset_t sva, vm_page_t *m, int count)
906{
907	vm_offset_t va;
908
909	va = sva;
910	while (count-- > 0) {
911		pmap_kenter(va, VM_PAGE_TO_PHYS(*m));
912		va += PAGE_SIZE;
913		m++;
914	}
915	pmap_invalidate_range(kernel_pmap, sva, va);
916}
917
918/*
919 * This routine tears out page mappings from the
920 * kernel -- it is meant only for temporary mappings.
921 * Note: SMP coherent.  Uses a ranged shootdown IPI.
922 */
923void
924pmap_qremove(vm_offset_t sva, int count)
925{
926	vm_offset_t va;
927
928	va = sva;
929	while (count-- > 0) {
930		pmap_kremove(va);
931		va += PAGE_SIZE;
932	}
933	pmap_invalidate_range(kernel_pmap, sva, va);
934}
935
936/***************************************************
937 * Page table page management routines.....
938 ***************************************************/
939
940/*
941 * This routine unholds page table pages, and if the hold count
942 * drops to zero, then it decrements the wire count.
943 */
944static int
945_pmap_unwire_pte_hold(pmap_t pmap, vm_page_t m)
946{
947
948	while (vm_page_sleep_if_busy(m, FALSE, "pmuwpt"))
949		vm_page_lock_queues();
950
951	if (m->hold_count == 0) {
952		vm_offset_t pteva;
953		/*
954		 * unmap the page table page
955		 */
956		pmap->pm_pdir[m->pindex] = 0;
957		--pmap->pm_stats.resident_count;
958		/*
959		 * We never unwire a kernel page table page, making a
960		 * check for the kernel_pmap unnecessary.
961		 */
962		if ((pmap->pm_pdir[PTDPTDI] & PG_FRAME) == (PTDpde[0] & PG_FRAME)) {
963			/*
964			 * Do an invltlb to make the invalidated mapping
965			 * take effect immediately.
966			 */
967			pteva = VM_MAXUSER_ADDRESS + i386_ptob(m->pindex);
968			pmap_invalidate_page(pmap, pteva);
969		}
970
971		/*
972		 * If the page is finally unwired, simply free it.
973		 */
974		--m->wire_count;
975		if (m->wire_count == 0) {
976			vm_page_busy(m);
977			vm_page_free_zero(m);
978			atomic_subtract_int(&cnt.v_wire_count, 1);
979		}
980		return 1;
981	}
982	return 0;
983}
984
985static PMAP_INLINE int
986pmap_unwire_pte_hold(pmap_t pmap, vm_page_t m)
987{
988	vm_page_unhold(m);
989	if (m->hold_count == 0)
990		return _pmap_unwire_pte_hold(pmap, m);
991	else
992		return 0;
993}
994
995/*
996 * After removing a page table entry, this routine is used to
997 * conditionally free the page, and manage the hold/wire counts.
998 */
999static int
1000pmap_unuse_pt(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
1001{
1002
1003	if (va >= VM_MAXUSER_ADDRESS)
1004		return 0;
1005
1006	return pmap_unwire_pte_hold(pmap, mpte);
1007}
1008
1009void
1010pmap_pinit0(pmap)
1011	struct pmap *pmap;
1012{
1013
1014	pmap->pm_pdir = (pd_entry_t *)(KERNBASE + (vm_offset_t)IdlePTD);
1015#ifdef PAE
1016	pmap->pm_pdpt = (pdpt_entry_t *)(KERNBASE + (vm_offset_t)IdlePDPT);
1017#endif
1018	pmap->pm_active = 0;
1019	PCPU_SET(curpmap, pmap);
1020	TAILQ_INIT(&pmap->pm_pvlist);
1021	bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1022	mtx_lock_spin(&allpmaps_lock);
1023	LIST_INSERT_HEAD(&allpmaps, pmap, pm_list);
1024	mtx_unlock_spin(&allpmaps_lock);
1025}
1026
1027/*
1028 * Initialize a preallocated and zeroed pmap structure,
1029 * such as one in a vmspace structure.
1030 */
1031void
1032pmap_pinit(pmap)
1033	register struct pmap *pmap;
1034{
1035	vm_page_t m, ptdpg[NPGPTD];
1036	vm_paddr_t pa;
1037	static int color;
1038	int i;
1039
1040	/*
1041	 * No need to allocate page table space yet but we do need a valid
1042	 * page directory table.
1043	 */
1044	if (pmap->pm_pdir == NULL) {
1045		pmap->pm_pdir = (pd_entry_t *)kmem_alloc_nofault(kernel_map,
1046		    NBPTD);
1047#ifdef PAE
1048		pmap->pm_pdpt = uma_zalloc(pdptzone, M_WAITOK | M_ZERO);
1049		KASSERT(((vm_offset_t)pmap->pm_pdpt &
1050		    ((NPGPTD * sizeof(pdpt_entry_t)) - 1)) == 0,
1051		    ("pmap_pinit: pdpt misaligned"));
1052		KASSERT(pmap_kextract((vm_offset_t)pmap->pm_pdpt) < (4ULL<<30),
1053		    ("pmap_pinit: pdpt above 4g"));
1054#endif
1055	}
1056
1057	/*
1058	 * allocate the page directory page(s)
1059	 */
1060	for (i = 0; i < NPGPTD;) {
1061		m = vm_page_alloc(NULL, color++,
1062		    VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
1063		    VM_ALLOC_ZERO);
1064		if (m == NULL)
1065			VM_WAIT;
1066		else {
1067			ptdpg[i++] = m;
1068		}
1069	}
1070
1071	pmap_qenter((vm_offset_t)pmap->pm_pdir, ptdpg, NPGPTD);
1072
1073	for (i = 0; i < NPGPTD; i++) {
1074		if ((ptdpg[i]->flags & PG_ZERO) == 0)
1075			bzero(pmap->pm_pdir + (i * NPDEPG), PAGE_SIZE);
1076	}
1077
1078	mtx_lock_spin(&allpmaps_lock);
1079	LIST_INSERT_HEAD(&allpmaps, pmap, pm_list);
1080	mtx_unlock_spin(&allpmaps_lock);
1081	/* Wire in kernel global address entries. */
1082	/* XXX copies current process, does not fill in MPPTDI */
1083	bcopy(PTD + KPTDI, pmap->pm_pdir + KPTDI, nkpt * sizeof(pd_entry_t));
1084#ifdef SMP
1085	pmap->pm_pdir[MPPTDI] = PTD[MPPTDI];
1086#endif
1087
1088	/* install self-referential address mapping entry(s) */
1089	for (i = 0; i < NPGPTD; i++) {
1090		pa = VM_PAGE_TO_PHYS(ptdpg[i]);
1091		pmap->pm_pdir[PTDPTDI + i] = pa | PG_V | PG_RW | PG_A | PG_M;
1092#ifdef PAE
1093		pmap->pm_pdpt[i] = pa | PG_V;
1094#endif
1095	}
1096
1097	pmap->pm_active = 0;
1098	TAILQ_INIT(&pmap->pm_pvlist);
1099	bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1100}
1101
1102/*
1103 * Wire in kernel global address entries.  To avoid a race condition
1104 * between pmap initialization and pmap_growkernel, this procedure
1105 * should be called after the vmspace is attached to the process
1106 * but before this pmap is activated.
1107 */
1108void
1109pmap_pinit2(pmap)
1110	struct pmap *pmap;
1111{
1112	/* XXX: Remove this stub when no longer called */
1113}
1114
1115/*
1116 * this routine is called if the page table page is not
1117 * mapped correctly.
1118 */
1119static vm_page_t
1120_pmap_allocpte(pmap, ptepindex)
1121	pmap_t	pmap;
1122	unsigned ptepindex;
1123{
1124	vm_paddr_t ptepa;
1125	vm_page_t m;
1126
1127	/*
1128	 * Allocate a page table page.
1129	 */
1130	if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
1131	    VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
1132		VM_WAIT;
1133		/*
1134		 * Indicate the need to retry.  While waiting, the page table
1135		 * page may have been allocated.
1136		 */
1137		return (NULL);
1138	}
1139	if ((m->flags & PG_ZERO) == 0)
1140		pmap_zero_page(m);
1141
1142	KASSERT(m->queue == PQ_NONE,
1143		("_pmap_allocpte: %p->queue != PQ_NONE", m));
1144
1145	/*
1146	 * Increment the hold count for the page table page
1147	 * (denoting a new mapping.)
1148	 */
1149	m->hold_count++;
1150
1151	/*
1152	 * Map the pagetable page into the process address space, if
1153	 * it isn't already there.
1154	 */
1155
1156	pmap->pm_stats.resident_count++;
1157
1158	ptepa = VM_PAGE_TO_PHYS(m);
1159	pmap->pm_pdir[ptepindex] =
1160		(pd_entry_t) (ptepa | PG_U | PG_RW | PG_V | PG_A | PG_M);
1161
1162	vm_page_lock_queues();
1163	vm_page_flag_clear(m, PG_ZERO);
1164	vm_page_wakeup(m);
1165	vm_page_unlock_queues();
1166
1167	return m;
1168}
1169
1170static vm_page_t
1171pmap_allocpte(pmap_t pmap, vm_offset_t va)
1172{
1173	unsigned ptepindex;
1174	pd_entry_t ptepa;
1175	vm_page_t m;
1176
1177	/*
1178	 * Calculate pagetable page index
1179	 */
1180	ptepindex = va >> PDRSHIFT;
1181retry:
1182	/*
1183	 * Get the page directory entry
1184	 */
1185	ptepa = pmap->pm_pdir[ptepindex];
1186
1187	/*
1188	 * This supports switching from a 4MB page to a
1189	 * normal 4K page.
1190	 */
1191	if (ptepa & PG_PS) {
1192		pmap->pm_pdir[ptepindex] = 0;
1193		ptepa = 0;
1194		pmap_invalidate_all(kernel_pmap);
1195	}
1196
1197	/*
1198	 * If the page table page is mapped, we just increment the
1199	 * hold count, and activate it.
1200	 */
1201	if (ptepa) {
1202		m = PHYS_TO_VM_PAGE(ptepa);
1203		m->hold_count++;
1204	} else {
1205		/*
1206		 * Here if the pte page isn't mapped, or if it has
1207		 * been deallocated.
1208		 */
1209		m = _pmap_allocpte(pmap, ptepindex);
1210		if (m == NULL)
1211			goto retry;
1212	}
1213	return (m);
1214}
1215
1216
1217/***************************************************
1218* Pmap allocation/deallocation routines.
1219 ***************************************************/
1220
1221#ifdef SMP
1222/*
1223 * Deal with a SMP shootdown of other users of the pmap that we are
1224 * trying to dispose of.  This can be a bit hairy.
1225 */
1226static u_int *lazymask;
1227static u_int lazyptd;
1228static volatile u_int lazywait;
1229
1230void pmap_lazyfix_action(void);
1231
1232void
1233pmap_lazyfix_action(void)
1234{
1235	u_int mymask = PCPU_GET(cpumask);
1236
1237	if (rcr3() == lazyptd)
1238		load_cr3(PCPU_GET(curpcb)->pcb_cr3);
1239	atomic_clear_int(lazymask, mymask);
1240	atomic_store_rel_int(&lazywait, 1);
1241}
1242
1243static void
1244pmap_lazyfix_self(u_int mymask)
1245{
1246
1247	if (rcr3() == lazyptd)
1248		load_cr3(PCPU_GET(curpcb)->pcb_cr3);
1249	atomic_clear_int(lazymask, mymask);
1250}
1251
1252
1253static void
1254pmap_lazyfix(pmap_t pmap)
1255{
1256	u_int mymask = PCPU_GET(cpumask);
1257	u_int mask;
1258	register u_int spins;
1259
1260	while ((mask = pmap->pm_active) != 0) {
1261		spins = 50000000;
1262		mask = mask & -mask;	/* Find least significant set bit */
1263		mtx_lock_spin(&lazypmap_lock);
1264#ifdef PAE
1265		lazyptd = vtophys(pmap->pm_pdpt);
1266#else
1267		lazyptd = vtophys(pmap->pm_pdir);
1268#endif
1269		if (mask == mymask) {
1270			lazymask = &pmap->pm_active;
1271			pmap_lazyfix_self(mymask);
1272		} else {
1273			atomic_store_rel_int((u_int *)&lazymask,
1274			    (u_int)&pmap->pm_active);
1275			atomic_store_rel_int(&lazywait, 0);
1276			ipi_selected(mask, IPI_LAZYPMAP);
1277			while (lazywait == 0) {
1278				ia32_pause();
1279				if (--spins == 0)
1280					break;
1281			}
1282		}
1283		mtx_unlock_spin(&lazypmap_lock);
1284		if (spins == 0)
1285			printf("pmap_lazyfix: spun for 50000000\n");
1286	}
1287}
1288
1289#else	/* SMP */
1290
1291/*
1292 * Cleaning up on uniprocessor is easy.  For various reasons, we're
1293 * unlikely to have to even execute this code, including the fact
1294 * that the cleanup is deferred until the parent does a wait(2), which
1295 * means that another userland process has run.
1296 */
1297static void
1298pmap_lazyfix(pmap_t pmap)
1299{
1300	u_int cr3;
1301
1302	cr3 = vtophys(pmap->pm_pdir);
1303	if (cr3 == rcr3()) {
1304		load_cr3(PCPU_GET(curpcb)->pcb_cr3);
1305		pmap->pm_active &= ~(PCPU_GET(cpumask));
1306	}
1307}
1308#endif	/* SMP */
1309
1310/*
1311 * Release any resources held by the given physical map.
1312 * Called when a pmap initialized by pmap_pinit is being released.
1313 * Should only be called if the map contains no valid mappings.
1314 */
1315void
1316pmap_release(pmap_t pmap)
1317{
1318	vm_page_t m, ptdpg[NPGPTD];
1319	int i;
1320
1321	KASSERT(pmap->pm_stats.resident_count == 0,
1322	    ("pmap_release: pmap resident count %ld != 0",
1323	    pmap->pm_stats.resident_count));
1324
1325	pmap_lazyfix(pmap);
1326	mtx_lock_spin(&allpmaps_lock);
1327	LIST_REMOVE(pmap, pm_list);
1328	mtx_unlock_spin(&allpmaps_lock);
1329
1330	for (i = 0; i < NPGPTD; i++)
1331		ptdpg[i] = PHYS_TO_VM_PAGE(pmap->pm_pdir[PTDPTDI + i]);
1332
1333	bzero(pmap->pm_pdir + PTDPTDI, (nkpt + NPGPTD) *
1334	    sizeof(*pmap->pm_pdir));
1335#ifdef SMP
1336	pmap->pm_pdir[MPPTDI] = 0;
1337#endif
1338
1339	pmap_qremove((vm_offset_t)pmap->pm_pdir, NPGPTD);
1340
1341	vm_page_lock_queues();
1342	for (i = 0; i < NPGPTD; i++) {
1343		m = ptdpg[i];
1344#ifdef PAE
1345		KASSERT(VM_PAGE_TO_PHYS(m) == (pmap->pm_pdpt[i] & PG_FRAME),
1346		    ("pmap_release: got wrong ptd page"));
1347#endif
1348		m->wire_count--;
1349		atomic_subtract_int(&cnt.v_wire_count, 1);
1350		vm_page_free_zero(m);
1351	}
1352	vm_page_unlock_queues();
1353}
1354
1355static int
1356kvm_size(SYSCTL_HANDLER_ARGS)
1357{
1358	unsigned long ksize = VM_MAX_KERNEL_ADDRESS - KERNBASE;
1359
1360	return sysctl_handle_long(oidp, &ksize, 0, req);
1361}
1362SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
1363    0, 0, kvm_size, "IU", "Size of KVM");
1364
1365static int
1366kvm_free(SYSCTL_HANDLER_ARGS)
1367{
1368	unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
1369
1370	return sysctl_handle_long(oidp, &kfree, 0, req);
1371}
1372SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
1373    0, 0, kvm_free, "IU", "Amount of KVM free");
1374
1375/*
1376 * grow the number of kernel page table entries, if needed
1377 */
1378void
1379pmap_growkernel(vm_offset_t addr)
1380{
1381	struct pmap *pmap;
1382	int s;
1383	vm_paddr_t ptppaddr;
1384	vm_page_t nkpg;
1385	pd_entry_t newpdir;
1386	pt_entry_t *pde;
1387
1388	s = splhigh();
1389	mtx_assert(&kernel_map->system_mtx, MA_OWNED);
1390	if (kernel_vm_end == 0) {
1391		kernel_vm_end = KERNBASE;
1392		nkpt = 0;
1393		while (pdir_pde(PTD, kernel_vm_end)) {
1394			kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1395			nkpt++;
1396		}
1397	}
1398	addr = roundup2(addr, PAGE_SIZE * NPTEPG);
1399	while (kernel_vm_end < addr) {
1400		if (pdir_pde(PTD, kernel_vm_end)) {
1401			kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1402			continue;
1403		}
1404
1405		/*
1406		 * This index is bogus, but out of the way
1407		 */
1408		nkpg = vm_page_alloc(NULL, nkpt,
1409		    VM_ALLOC_NOOBJ | VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
1410		if (!nkpg)
1411			panic("pmap_growkernel: no memory to grow kernel");
1412
1413		nkpt++;
1414
1415		pmap_zero_page(nkpg);
1416		ptppaddr = VM_PAGE_TO_PHYS(nkpg);
1417		newpdir = (pd_entry_t) (ptppaddr | PG_V | PG_RW | PG_A | PG_M);
1418		pdir_pde(PTD, kernel_vm_end) = newpdir;
1419
1420		mtx_lock_spin(&allpmaps_lock);
1421		LIST_FOREACH(pmap, &allpmaps, pm_list) {
1422			pde = pmap_pde(pmap, kernel_vm_end);
1423			pde_store(pde, newpdir);
1424		}
1425		mtx_unlock_spin(&allpmaps_lock);
1426		kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1427	}
1428	splx(s);
1429}
1430
1431
1432/***************************************************
1433 * page management routines.
1434 ***************************************************/
1435
1436/*
1437 * free the pv_entry back to the free list
1438 */
1439static PMAP_INLINE void
1440free_pv_entry(pv_entry_t pv)
1441{
1442	pv_entry_count--;
1443	uma_zfree(pvzone, pv);
1444}
1445
1446/*
1447 * get a new pv_entry, allocating a block from the system
1448 * when needed.
1449 * the memory allocation is performed bypassing the malloc code
1450 * because of the possibility of allocations at interrupt time.
1451 */
1452static pv_entry_t
1453get_pv_entry(void)
1454{
1455	pv_entry_count++;
1456	if (pv_entry_high_water &&
1457		(pv_entry_count > pv_entry_high_water) &&
1458		(pmap_pagedaemon_waken == 0)) {
1459		pmap_pagedaemon_waken = 1;
1460		wakeup (&vm_pages_needed);
1461	}
1462	return uma_zalloc(pvzone, M_NOWAIT);
1463}
1464
1465/*
1466 * If it is the first entry on the list, it is actually
1467 * in the header and we must copy the following entry up
1468 * to the header.  Otherwise we must search the list for
1469 * the entry.  In either case we free the now unused entry.
1470 */
1471
1472static int
1473pmap_remove_entry(pmap_t pmap, vm_page_t m, vm_offset_t va)
1474{
1475	pv_entry_t pv;
1476	int rtval;
1477	int s;
1478
1479	s = splvm();
1480	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1481	if (m->md.pv_list_count < pmap->pm_stats.resident_count) {
1482		TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
1483			if (pmap == pv->pv_pmap && va == pv->pv_va)
1484				break;
1485		}
1486	} else {
1487		TAILQ_FOREACH(pv, &pmap->pm_pvlist, pv_plist) {
1488			if (va == pv->pv_va)
1489				break;
1490		}
1491	}
1492
1493	rtval = 0;
1494	if (pv) {
1495		rtval = pmap_unuse_pt(pmap, va, pv->pv_ptem);
1496		TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
1497		m->md.pv_list_count--;
1498		if (TAILQ_FIRST(&m->md.pv_list) == NULL)
1499			vm_page_flag_clear(m, PG_WRITEABLE);
1500
1501		TAILQ_REMOVE(&pmap->pm_pvlist, pv, pv_plist);
1502		free_pv_entry(pv);
1503	}
1504
1505	splx(s);
1506	return rtval;
1507}
1508
1509/*
1510 * Create a pv entry for page at pa for
1511 * (pmap, va).
1512 */
1513static void
1514pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t mpte, vm_page_t m)
1515{
1516
1517	int s;
1518	pv_entry_t pv;
1519
1520	s = splvm();
1521	pv = get_pv_entry();
1522	pv->pv_va = va;
1523	pv->pv_pmap = pmap;
1524	pv->pv_ptem = mpte;
1525
1526	vm_page_lock_queues();
1527	TAILQ_INSERT_TAIL(&pmap->pm_pvlist, pv, pv_plist);
1528	TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
1529	m->md.pv_list_count++;
1530
1531	vm_page_unlock_queues();
1532	splx(s);
1533}
1534
1535/*
1536 * pmap_remove_pte: do the things to unmap a page in a process
1537 */
1538static int
1539pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va)
1540{
1541	pt_entry_t oldpte;
1542	vm_page_t m, mpte;
1543
1544	oldpte = pte_load_clear(ptq);
1545	if (oldpte & PG_W)
1546		pmap->pm_stats.wired_count -= 1;
1547	/*
1548	 * Machines that don't support invlpg, also don't support
1549	 * PG_G.
1550	 */
1551	if (oldpte & PG_G)
1552		pmap_invalidate_page(kernel_pmap, va);
1553	pmap->pm_stats.resident_count -= 1;
1554	if (oldpte & PG_MANAGED) {
1555		m = PHYS_TO_VM_PAGE(oldpte);
1556		if (oldpte & PG_M) {
1557#if defined(PMAP_DIAGNOSTIC)
1558			if (pmap_nw_modified((pt_entry_t) oldpte)) {
1559				printf(
1560	"pmap_remove: modified page not writable: va: 0x%x, pte: 0x%x\n",
1561				    va, oldpte);
1562			}
1563#endif
1564			if (pmap_track_modified(va))
1565				vm_page_dirty(m);
1566		}
1567		if (oldpte & PG_A)
1568			vm_page_flag_set(m, PG_REFERENCED);
1569		return pmap_remove_entry(pmap, m, va);
1570	} else {
1571		mpte = PHYS_TO_VM_PAGE(*pmap_pde(pmap, va));
1572		return pmap_unuse_pt(pmap, va, mpte);
1573	}
1574}
1575
1576/*
1577 * Remove a single page from a process address space
1578 */
1579static void
1580pmap_remove_page(pmap_t pmap, vm_offset_t va)
1581{
1582	pt_entry_t *pte;
1583
1584	if ((pte = pmap_pte(pmap, va)) == NULL || *pte == 0)
1585		return;
1586	pmap_remove_pte(pmap, pte, va);
1587	pmap_invalidate_page(pmap, va);
1588}
1589
1590/*
1591 *	Remove the given range of addresses from the specified map.
1592 *
1593 *	It is assumed that the start and end are properly
1594 *	rounded to the page size.
1595 */
1596void
1597pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1598{
1599	vm_offset_t pdnxt;
1600	pd_entry_t ptpaddr;
1601	pt_entry_t *pte;
1602	int anyvalid;
1603
1604	if (pmap == NULL)
1605		return;
1606
1607	if (pmap->pm_stats.resident_count == 0)
1608		return;
1609
1610	/*
1611	 * special handling of removing one page.  a very
1612	 * common operation and easy to short circuit some
1613	 * code.
1614	 */
1615	if ((sva + PAGE_SIZE == eva) &&
1616	    ((pmap->pm_pdir[(sva >> PDRSHIFT)] & PG_PS) == 0)) {
1617		pmap_remove_page(pmap, sva);
1618		return;
1619	}
1620
1621	anyvalid = 0;
1622
1623	for (; sva < eva; sva = pdnxt) {
1624		unsigned pdirindex;
1625
1626		/*
1627		 * Calculate index for next page table.
1628		 */
1629		pdnxt = (sva + NBPDR) & ~PDRMASK;
1630		if (pmap->pm_stats.resident_count == 0)
1631			break;
1632
1633		pdirindex = sva >> PDRSHIFT;
1634		ptpaddr = pmap->pm_pdir[pdirindex];
1635
1636		/*
1637		 * Weed out invalid mappings. Note: we assume that the page
1638		 * directory table is always allocated, and in kernel virtual.
1639		 */
1640		if (ptpaddr == 0)
1641			continue;
1642
1643		/*
1644		 * Check for large page.
1645		 */
1646		if ((ptpaddr & PG_PS) != 0) {
1647			pmap->pm_pdir[pdirindex] = 0;
1648			pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
1649			anyvalid = 1;
1650			continue;
1651		}
1652
1653		/*
1654		 * Limit our scan to either the end of the va represented
1655		 * by the current page table page, or to the end of the
1656		 * range being removed.
1657		 */
1658		if (pdnxt > eva)
1659			pdnxt = eva;
1660
1661		for (; sva != pdnxt; sva += PAGE_SIZE) {
1662			if ((pte = pmap_pte(pmap, sva)) == NULL ||
1663			    *pte == 0)
1664				continue;
1665			anyvalid = 1;
1666			if (pmap_remove_pte(pmap, pte, sva))
1667				break;
1668		}
1669	}
1670
1671	if (anyvalid)
1672		pmap_invalidate_all(pmap);
1673}
1674
1675/*
1676 *	Routine:	pmap_remove_all
1677 *	Function:
1678 *		Removes this physical page from
1679 *		all physical maps in which it resides.
1680 *		Reflects back modify bits to the pager.
1681 *
1682 *	Notes:
1683 *		Original versions of this routine were very
1684 *		inefficient because they iteratively called
1685 *		pmap_remove (slow...)
1686 */
1687
1688void
1689pmap_remove_all(vm_page_t m)
1690{
1691	register pv_entry_t pv;
1692	pt_entry_t *pte, tpte;
1693	int s;
1694
1695#if defined(PMAP_DIAGNOSTIC)
1696	/*
1697	 * XXX This makes pmap_remove_all() illegal for non-managed pages!
1698	 */
1699	if (!pmap_initialized || (m->flags & PG_FICTITIOUS)) {
1700		panic("pmap_remove_all: illegal for unmanaged page, va: 0x%x",
1701		    VM_PAGE_TO_PHYS(m));
1702	}
1703#endif
1704	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1705	s = splvm();
1706	while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
1707		pv->pv_pmap->pm_stats.resident_count--;
1708		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
1709		tpte = pte_load_clear(pte);
1710		if (tpte & PG_W)
1711			pv->pv_pmap->pm_stats.wired_count--;
1712		if (tpte & PG_A)
1713			vm_page_flag_set(m, PG_REFERENCED);
1714
1715		/*
1716		 * Update the vm_page_t clean and reference bits.
1717		 */
1718		if (tpte & PG_M) {
1719#if defined(PMAP_DIAGNOSTIC)
1720			if (pmap_nw_modified((pt_entry_t) tpte)) {
1721				printf(
1722	"pmap_remove_all: modified page not writable: va: 0x%x, pte: 0x%x\n",
1723				    pv->pv_va, tpte);
1724			}
1725#endif
1726			if (pmap_track_modified(pv->pv_va))
1727				vm_page_dirty(m);
1728		}
1729		pmap_invalidate_page(pv->pv_pmap, pv->pv_va);
1730		TAILQ_REMOVE(&pv->pv_pmap->pm_pvlist, pv, pv_plist);
1731		TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
1732		m->md.pv_list_count--;
1733		pmap_unuse_pt(pv->pv_pmap, pv->pv_va, pv->pv_ptem);
1734		free_pv_entry(pv);
1735	}
1736	vm_page_flag_clear(m, PG_WRITEABLE);
1737	splx(s);
1738}
1739
1740/*
1741 *	Set the physical protection on the
1742 *	specified range of this map as requested.
1743 */
1744void
1745pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
1746{
1747	vm_offset_t pdnxt;
1748	pd_entry_t ptpaddr;
1749	int anychanged;
1750
1751	if (pmap == NULL)
1752		return;
1753
1754	if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
1755		pmap_remove(pmap, sva, eva);
1756		return;
1757	}
1758
1759	if (prot & VM_PROT_WRITE)
1760		return;
1761
1762	anychanged = 0;
1763
1764	for (; sva < eva; sva = pdnxt) {
1765		unsigned pdirindex;
1766
1767		pdnxt = (sva + NBPDR) & ~PDRMASK;
1768
1769		pdirindex = sva >> PDRSHIFT;
1770		ptpaddr = pmap->pm_pdir[pdirindex];
1771
1772		/*
1773		 * Weed out invalid mappings. Note: we assume that the page
1774		 * directory table is always allocated, and in kernel virtual.
1775		 */
1776		if (ptpaddr == 0)
1777			continue;
1778
1779		/*
1780		 * Check for large page.
1781		 */
1782		if ((ptpaddr & PG_PS) != 0) {
1783			pmap->pm_pdir[pdirindex] &= ~(PG_M|PG_RW);
1784			pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
1785			anychanged = 1;
1786			continue;
1787		}
1788
1789		if (pdnxt > eva)
1790			pdnxt = eva;
1791
1792		for (; sva != pdnxt; sva += PAGE_SIZE) {
1793			pt_entry_t pbits;
1794			pt_entry_t *pte;
1795			vm_page_t m;
1796
1797			if ((pte = pmap_pte(pmap, sva)) == NULL)
1798				continue;
1799			pbits = *pte;
1800			if (pbits & PG_MANAGED) {
1801				m = NULL;
1802				if (pbits & PG_A) {
1803					m = PHYS_TO_VM_PAGE(pbits);
1804					vm_page_flag_set(m, PG_REFERENCED);
1805					pbits &= ~PG_A;
1806				}
1807				if ((pbits & PG_M) != 0 &&
1808				    pmap_track_modified(sva)) {
1809					if (m == NULL)
1810						m = PHYS_TO_VM_PAGE(pbits);
1811					vm_page_dirty(m);
1812					pbits &= ~PG_M;
1813				}
1814			}
1815
1816			pbits &= ~PG_RW;
1817
1818			if (pbits != *pte) {
1819				pte_store(pte, pbits);
1820				anychanged = 1;
1821			}
1822		}
1823	}
1824	if (anychanged)
1825		pmap_invalidate_all(pmap);
1826}
1827
1828/*
1829 *	Insert the given physical page (p) at
1830 *	the specified virtual address (v) in the
1831 *	target physical map with the protection requested.
1832 *
1833 *	If specified, the page will be wired down, meaning
1834 *	that the related pte can not be reclaimed.
1835 *
1836 *	NB:  This is the only routine which MAY NOT lazy-evaluate
1837 *	or lose information.  That is, this routine must actually
1838 *	insert this page into the given map NOW.
1839 */
1840void
1841pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
1842	   boolean_t wired)
1843{
1844	vm_paddr_t pa;
1845	register pt_entry_t *pte;
1846	vm_paddr_t opa;
1847	pt_entry_t origpte, newpte;
1848	vm_page_t mpte;
1849
1850	if (pmap == NULL)
1851		return;
1852
1853	va &= PG_FRAME;
1854#ifdef PMAP_DIAGNOSTIC
1855	if (va > VM_MAX_KERNEL_ADDRESS)
1856		panic("pmap_enter: toobig");
1857	if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
1858		panic("pmap_enter: invalid to pmap_enter page table pages (va: 0x%x)", va);
1859#endif
1860
1861	mpte = NULL;
1862	/*
1863	 * In the case that a page table page is not
1864	 * resident, we are creating it here.
1865	 */
1866	if (va < VM_MAXUSER_ADDRESS) {
1867		mpte = pmap_allocpte(pmap, va);
1868	}
1869#if 0 && defined(PMAP_DIAGNOSTIC)
1870	else {
1871		pd_entry_t *pdeaddr = pmap_pde(pmap, va);
1872		origpte = *pdeaddr;
1873		if ((origpte & PG_V) == 0) {
1874			panic("pmap_enter: invalid kernel page table page, pdir=%p, pde=%p, va=%p\n",
1875				pmap->pm_pdir[PTDPTDI], origpte, va);
1876		}
1877	}
1878#endif
1879
1880	pte = pmap_pte(pmap, va);
1881
1882	/*
1883	 * Page Directory table entry not valid, we need a new PT page
1884	 */
1885	if (pte == NULL) {
1886		panic("pmap_enter: invalid page directory pdir=%#jx, va=%#x\n",
1887			(uintmax_t)pmap->pm_pdir[PTDPTDI], va);
1888	}
1889
1890	pa = VM_PAGE_TO_PHYS(m) & PG_FRAME;
1891	origpte = *pte;
1892	opa = origpte & PG_FRAME;
1893
1894	if (origpte & PG_PS) {
1895		/*
1896		 * Yes, I know this will truncate upper address bits for PAE,
1897		 * but I'm actually more interested in the lower bits
1898		 */
1899		printf("pmap_enter: va %p, pte %p, origpte %p\n",
1900		    (void *)va, (void *)pte, (void *)(uintptr_t)origpte);
1901		panic("pmap_enter: attempted pmap_enter on 4MB page");
1902	}
1903
1904	/*
1905	 * Mapping has not changed, must be protection or wiring change.
1906	 */
1907	if (origpte && (opa == pa)) {
1908		/*
1909		 * Wiring change, just update stats. We don't worry about
1910		 * wiring PT pages as they remain resident as long as there
1911		 * are valid mappings in them. Hence, if a user page is wired,
1912		 * the PT page will be also.
1913		 */
1914		if (wired && ((origpte & PG_W) == 0))
1915			pmap->pm_stats.wired_count++;
1916		else if (!wired && (origpte & PG_W))
1917			pmap->pm_stats.wired_count--;
1918
1919#if defined(PMAP_DIAGNOSTIC)
1920		if (pmap_nw_modified((pt_entry_t) origpte)) {
1921			printf(
1922	"pmap_enter: modified page not writable: va: 0x%x, pte: 0x%x\n",
1923			    va, origpte);
1924		}
1925#endif
1926
1927		/*
1928		 * Remove extra pte reference
1929		 */
1930		if (mpte)
1931			mpte->hold_count--;
1932
1933		if ((prot & VM_PROT_WRITE) && (origpte & PG_V)) {
1934			if ((origpte & PG_RW) == 0) {
1935				pte_store(pte, origpte | PG_RW);
1936				pmap_invalidate_page(pmap, va);
1937			}
1938			return;
1939		}
1940
1941		/*
1942		 * We might be turning off write access to the page,
1943		 * so we go ahead and sense modify status.
1944		 */
1945		if (origpte & PG_MANAGED) {
1946			if ((origpte & PG_M) && pmap_track_modified(va)) {
1947				vm_page_t om;
1948				om = PHYS_TO_VM_PAGE(opa);
1949				vm_page_dirty(om);
1950			}
1951			pa |= PG_MANAGED;
1952		}
1953		goto validate;
1954	}
1955	/*
1956	 * Mapping has changed, invalidate old range and fall through to
1957	 * handle validating new mapping.
1958	 */
1959	if (opa) {
1960		int err;
1961		vm_page_lock_queues();
1962		err = pmap_remove_pte(pmap, pte, va);
1963		vm_page_unlock_queues();
1964		if (err)
1965			panic("pmap_enter: pte vanished, va: 0x%x", va);
1966	}
1967
1968	/*
1969	 * Enter on the PV list if part of our managed memory. Note that we
1970	 * raise IPL while manipulating pv_table since pmap_enter can be
1971	 * called at interrupt time.
1972	 */
1973	if (pmap_initialized &&
1974	    (m->flags & (PG_FICTITIOUS|PG_UNMANAGED)) == 0) {
1975		pmap_insert_entry(pmap, va, mpte, m);
1976		pa |= PG_MANAGED;
1977	}
1978
1979	/*
1980	 * Increment counters
1981	 */
1982	pmap->pm_stats.resident_count++;
1983	if (wired)
1984		pmap->pm_stats.wired_count++;
1985
1986validate:
1987	/*
1988	 * Now validate mapping with desired protection/wiring.
1989	 */
1990	newpte = (pt_entry_t)(pa | PG_V);
1991	if ((prot & VM_PROT_WRITE) != 0)
1992		newpte |= PG_RW;
1993	if (wired)
1994		newpte |= PG_W;
1995	if (va < VM_MAXUSER_ADDRESS)
1996		newpte |= PG_U;
1997	if (pmap == kernel_pmap)
1998		newpte |= pgeflag;
1999
2000	/*
2001	 * if the mapping or permission bits are different, we need
2002	 * to update the pte.
2003	 */
2004	if ((origpte & ~(PG_M|PG_A)) != newpte) {
2005		pte_store(pte, newpte | PG_A);
2006		/*if (origpte)*/ {
2007			pmap_invalidate_page(pmap, va);
2008		}
2009	}
2010}
2011
2012/*
2013 * this code makes some *MAJOR* assumptions:
2014 * 1. Current pmap & pmap exists.
2015 * 2. Not wired.
2016 * 3. Read access.
2017 * 4. No page table pages.
2018 * 5. Tlbflush is deferred to calling procedure.
2019 * 6. Page IS managed.
2020 * but is *MUCH* faster than pmap_enter...
2021 */
2022
2023vm_page_t
2024pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_page_t mpte)
2025{
2026	pt_entry_t *pte;
2027	vm_paddr_t pa;
2028
2029	/*
2030	 * In the case that a page table page is not
2031	 * resident, we are creating it here.
2032	 */
2033	if (va < VM_MAXUSER_ADDRESS) {
2034		unsigned ptepindex;
2035		pd_entry_t ptepa;
2036
2037		/*
2038		 * Calculate pagetable page index
2039		 */
2040		ptepindex = va >> PDRSHIFT;
2041		if (mpte && (mpte->pindex == ptepindex)) {
2042			mpte->hold_count++;
2043		} else {
2044retry:
2045			/*
2046			 * Get the page directory entry
2047			 */
2048			ptepa = pmap->pm_pdir[ptepindex];
2049
2050			/*
2051			 * If the page table page is mapped, we just increment
2052			 * the hold count, and activate it.
2053			 */
2054			if (ptepa) {
2055				if (ptepa & PG_PS)
2056					panic("pmap_enter_quick: unexpected mapping into 4MB page");
2057				mpte = PHYS_TO_VM_PAGE(ptepa);
2058				mpte->hold_count++;
2059			} else {
2060				mpte = _pmap_allocpte(pmap, ptepindex);
2061				if (mpte == NULL)
2062					goto retry;
2063			}
2064		}
2065	} else {
2066		mpte = NULL;
2067	}
2068
2069	/*
2070	 * This call to vtopte makes the assumption that we are
2071	 * entering the page into the current pmap.  In order to support
2072	 * quick entry into any pmap, one would likely use pmap_pte_quick.
2073	 * But that isn't as quick as vtopte.
2074	 */
2075	pte = vtopte(va);
2076	if (*pte) {
2077		if (mpte != NULL) {
2078			vm_page_lock_queues();
2079			pmap_unwire_pte_hold(pmap, mpte);
2080			vm_page_unlock_queues();
2081		}
2082		return 0;
2083	}
2084
2085	/*
2086	 * Enter on the PV list if part of our managed memory. Note that we
2087	 * raise IPL while manipulating pv_table since pmap_enter can be
2088	 * called at interrupt time.
2089	 */
2090	if ((m->flags & (PG_FICTITIOUS|PG_UNMANAGED)) == 0)
2091		pmap_insert_entry(pmap, va, mpte, m);
2092
2093	/*
2094	 * Increment counters
2095	 */
2096	pmap->pm_stats.resident_count++;
2097
2098	pa = VM_PAGE_TO_PHYS(m);
2099
2100	/*
2101	 * Now validate mapping with RO protection
2102	 */
2103	if (m->flags & (PG_FICTITIOUS|PG_UNMANAGED))
2104		pte_store(pte, pa | PG_V | PG_U);
2105	else
2106		pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
2107
2108	return mpte;
2109}
2110
2111/*
2112 * Make a temporary mapping for a physical address.  This is only intended
2113 * to be used for panic dumps.
2114 */
2115void *
2116pmap_kenter_temporary(vm_offset_t pa, int i)
2117{
2118	vm_offset_t va;
2119
2120	va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
2121	pmap_kenter(va, pa);
2122#ifndef I386_CPU
2123	invlpg(va);
2124#else
2125	invltlb();
2126#endif
2127	return ((void *)crashdumpmap);
2128}
2129
2130/*
2131 * This code maps large physical mmap regions into the
2132 * processor address space.  Note that some shortcuts
2133 * are taken, but the code works.
2134 */
2135void
2136pmap_object_init_pt(pmap_t pmap, vm_offset_t addr,
2137		    vm_object_t object, vm_pindex_t pindex,
2138		    vm_size_t size)
2139{
2140	vm_page_t p;
2141
2142	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2143	KASSERT(object->type == OBJT_DEVICE,
2144	    ("pmap_object_init_pt: non-device object"));
2145	if (pseflag &&
2146	    ((addr & (NBPDR - 1)) == 0) && ((size & (NBPDR - 1)) == 0)) {
2147		int i;
2148		vm_page_t m[1];
2149		unsigned int ptepindex;
2150		int npdes;
2151		pd_entry_t ptepa;
2152
2153		if (pmap->pm_pdir[ptepindex = (addr >> PDRSHIFT)])
2154			return;
2155retry:
2156		p = vm_page_lookup(object, pindex);
2157		if (p != NULL) {
2158			vm_page_lock_queues();
2159			if (vm_page_sleep_if_busy(p, FALSE, "init4p"))
2160				goto retry;
2161		} else {
2162			p = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL);
2163			if (p == NULL)
2164				return;
2165			m[0] = p;
2166
2167			if (vm_pager_get_pages(object, m, 1, 0) != VM_PAGER_OK) {
2168				vm_page_lock_queues();
2169				vm_page_free(p);
2170				vm_page_unlock_queues();
2171				return;
2172			}
2173
2174			p = vm_page_lookup(object, pindex);
2175			vm_page_lock_queues();
2176			vm_page_wakeup(p);
2177		}
2178		vm_page_unlock_queues();
2179
2180		ptepa = VM_PAGE_TO_PHYS(p);
2181		if (ptepa & (NBPDR - 1))
2182			return;
2183
2184		p->valid = VM_PAGE_BITS_ALL;
2185
2186		pmap->pm_stats.resident_count += size >> PAGE_SHIFT;
2187		npdes = size >> PDRSHIFT;
2188		for(i = 0; i < npdes; i++) {
2189			pde_store(&pmap->pm_pdir[ptepindex],
2190			    ptepa | PG_U | PG_RW | PG_V | PG_PS);
2191			ptepa += NBPDR;
2192			ptepindex += 1;
2193		}
2194		pmap_invalidate_all(pmap);
2195	}
2196}
2197
2198/*
2199 *	Routine:	pmap_change_wiring
2200 *	Function:	Change the wiring attribute for a map/virtual-address
2201 *			pair.
2202 *	In/out conditions:
2203 *			The mapping must already exist in the pmap.
2204 */
2205void
2206pmap_change_wiring(pmap, va, wired)
2207	register pmap_t pmap;
2208	vm_offset_t va;
2209	boolean_t wired;
2210{
2211	register pt_entry_t *pte;
2212
2213	if (pmap == NULL)
2214		return;
2215
2216	pte = pmap_pte(pmap, va);
2217
2218	if (wired && !pmap_pte_w(pte))
2219		pmap->pm_stats.wired_count++;
2220	else if (!wired && pmap_pte_w(pte))
2221		pmap->pm_stats.wired_count--;
2222
2223	/*
2224	 * Wiring is not a hardware characteristic so there is no need to
2225	 * invalidate TLB.
2226	 */
2227	pmap_pte_set_w(pte, wired);
2228}
2229
2230
2231
2232/*
2233 *	Copy the range specified by src_addr/len
2234 *	from the source map to the range dst_addr/len
2235 *	in the destination map.
2236 *
2237 *	This routine is only advisory and need not do anything.
2238 */
2239
2240void
2241pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
2242	  vm_offset_t src_addr)
2243{
2244	vm_offset_t addr;
2245	vm_offset_t end_addr = src_addr + len;
2246	vm_offset_t pdnxt;
2247	vm_page_t m;
2248
2249	if (dst_addr != src_addr)
2250		return;
2251
2252	if (!pmap_is_current(src_pmap))
2253		return;
2254
2255	for (addr = src_addr; addr < end_addr; addr = pdnxt) {
2256		pt_entry_t *src_pte, *dst_pte;
2257		vm_page_t dstmpte, srcmpte;
2258		pd_entry_t srcptepaddr;
2259		unsigned ptepindex;
2260
2261		if (addr >= UPT_MIN_ADDRESS)
2262			panic("pmap_copy: invalid to pmap_copy page tables\n");
2263
2264		/*
2265		 * Don't let optional prefaulting of pages make us go
2266		 * way below the low water mark of free pages or way
2267		 * above high water mark of used pv entries.
2268		 */
2269		if (cnt.v_free_count < cnt.v_free_reserved ||
2270		    pv_entry_count > pv_entry_high_water)
2271			break;
2272
2273		pdnxt = (addr + NBPDR) & ~PDRMASK;
2274		ptepindex = addr >> PDRSHIFT;
2275
2276		srcptepaddr = src_pmap->pm_pdir[ptepindex];
2277		if (srcptepaddr == 0)
2278			continue;
2279
2280		if (srcptepaddr & PG_PS) {
2281			if (dst_pmap->pm_pdir[ptepindex] == 0) {
2282				dst_pmap->pm_pdir[ptepindex] = srcptepaddr;
2283				dst_pmap->pm_stats.resident_count +=
2284				    NBPDR / PAGE_SIZE;
2285			}
2286			continue;
2287		}
2288
2289		srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
2290		if (srcmpte->hold_count == 0 || (srcmpte->flags & PG_BUSY))
2291			continue;
2292
2293		if (pdnxt > end_addr)
2294			pdnxt = end_addr;
2295
2296		src_pte = vtopte(addr);
2297		while (addr < pdnxt) {
2298			pt_entry_t ptetemp;
2299			ptetemp = *src_pte;
2300			/*
2301			 * we only virtual copy managed pages
2302			 */
2303			if ((ptetemp & PG_MANAGED) != 0) {
2304				/*
2305				 * We have to check after allocpte for the
2306				 * pte still being around...  allocpte can
2307				 * block.
2308				 */
2309				dstmpte = pmap_allocpte(dst_pmap, addr);
2310				dst_pte = pmap_pte(dst_pmap, addr);
2311				if ((*dst_pte == 0) && (ptetemp = *src_pte)) {
2312					/*
2313					 * Clear the modified and
2314					 * accessed (referenced) bits
2315					 * during the copy.
2316					 */
2317					m = PHYS_TO_VM_PAGE(ptetemp);
2318					*dst_pte = ptetemp & ~(PG_M | PG_A);
2319					dst_pmap->pm_stats.resident_count++;
2320					pmap_insert_entry(dst_pmap, addr,
2321						dstmpte, m);
2322	 			} else {
2323					vm_page_lock_queues();
2324					pmap_unwire_pte_hold(dst_pmap, dstmpte);
2325					vm_page_unlock_queues();
2326				}
2327				if (dstmpte->hold_count >= srcmpte->hold_count)
2328					break;
2329			}
2330			addr += PAGE_SIZE;
2331			src_pte++;
2332		}
2333	}
2334}
2335
2336#ifdef SMP
2337
2338/*
2339 *	pmap_zpi_switchout*()
2340 *
2341 *	These functions allow us to avoid doing IPIs alltogether in certain
2342 *	temporary page-mapping situations (page zeroing).  Instead to deal
2343 *	with being preempted and moved onto a different cpu we invalidate
2344 *	the page when the scheduler switches us in.  This does not occur
2345 *	very often so we remain relatively optimal with very little effort.
2346 */
2347static void
2348pmap_zpi_switchout12(void)
2349{
2350	invlpg((u_int)CADDR1);
2351	invlpg((u_int)CADDR2);
2352}
2353
2354static void
2355pmap_zpi_switchout2(void)
2356{
2357	invlpg((u_int)CADDR2);
2358}
2359
2360static void
2361pmap_zpi_switchout3(void)
2362{
2363	invlpg((u_int)CADDR3);
2364}
2365
2366#endif
2367
2368static __inline void
2369pagezero(void *page)
2370{
2371#if defined(I686_CPU)
2372	if (cpu_class == CPUCLASS_686) {
2373#if defined(CPU_ENABLE_SSE)
2374		if (cpu_feature & CPUID_SSE2)
2375			sse2_pagezero(page);
2376		else
2377#endif
2378			i686_pagezero(page);
2379	} else
2380#endif
2381		bzero(page, PAGE_SIZE);
2382}
2383
2384static __inline void
2385invlcaddr(void *caddr)
2386{
2387#ifdef I386_CPU
2388	invltlb();
2389#else
2390	invlpg((u_int)caddr);
2391#endif
2392}
2393
2394/*
2395 *	pmap_zero_page zeros the specified hardware page by mapping
2396 *	the page into KVM and using bzero to clear its contents.
2397 */
2398void
2399pmap_zero_page(vm_page_t m)
2400{
2401
2402	mtx_lock(&CMAPCADDR12_lock);
2403	if (*CMAP2)
2404		panic("pmap_zero_page: CMAP2 busy");
2405#ifdef SMP
2406	curthread->td_pcb->pcb_switchout = pmap_zpi_switchout2;
2407#endif
2408	*CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M;
2409#ifdef SMP
2410	invlpg((u_int)CADDR2);
2411#endif
2412	pagezero(CADDR2);
2413	*CMAP2 = 0;
2414	invlcaddr(CADDR2);
2415#ifdef SMP
2416	curthread->td_pcb->pcb_switchout = NULL;
2417#endif
2418	mtx_unlock(&CMAPCADDR12_lock);
2419}
2420
2421/*
2422 *	pmap_zero_page_area zeros the specified hardware page by mapping
2423 *	the page into KVM and using bzero to clear its contents.
2424 *
2425 *	off and size may not cover an area beyond a single hardware page.
2426 */
2427void
2428pmap_zero_page_area(vm_page_t m, int off, int size)
2429{
2430
2431	mtx_lock(&CMAPCADDR12_lock);
2432	if (*CMAP2)
2433		panic("pmap_zero_page: CMAP2 busy");
2434#ifdef SMP
2435	curthread->td_pcb->pcb_switchout = pmap_zpi_switchout2;
2436#endif
2437	*CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M;
2438#ifdef SMP
2439	invlpg((u_int)CADDR2);
2440#endif
2441	if (off == 0 && size == PAGE_SIZE)
2442		pagezero(CADDR2);
2443	else
2444		bzero((char *)CADDR2 + off, size);
2445	*CMAP2 = 0;
2446	invlcaddr(CADDR2);
2447#ifdef SMP
2448	curthread->td_pcb->pcb_switchout = NULL;
2449#endif
2450	mtx_unlock(&CMAPCADDR12_lock);
2451}
2452
2453/*
2454 *	pmap_zero_page_idle zeros the specified hardware page by mapping
2455 *	the page into KVM and using bzero to clear its contents.  This
2456 *	is intended to be called from the vm_pagezero process only and
2457 *	outside of Giant.
2458 */
2459void
2460pmap_zero_page_idle(vm_page_t m)
2461{
2462
2463	if (*CMAP3)
2464		panic("pmap_zero_page: CMAP3 busy");
2465#ifdef SMP
2466	curthread->td_pcb->pcb_switchout = pmap_zpi_switchout3;
2467#endif
2468	*CMAP3 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M;
2469#ifdef SMP
2470	invlpg((u_int)CADDR3);
2471#endif
2472	pagezero(CADDR3);
2473	*CMAP3 = 0;
2474	invlcaddr(CADDR3);
2475#ifdef SMP
2476	curthread->td_pcb->pcb_switchout = NULL;
2477#endif
2478}
2479
2480/*
2481 *	pmap_copy_page copies the specified (machine independent)
2482 *	page by mapping the page into virtual memory and using
2483 *	bcopy to copy the page, one machine dependent page at a
2484 *	time.
2485 */
2486void
2487pmap_copy_page(vm_page_t src, vm_page_t dst)
2488{
2489
2490	mtx_lock(&CMAPCADDR12_lock);
2491	if (*CMAP1)
2492		panic("pmap_copy_page: CMAP1 busy");
2493	if (*CMAP2)
2494		panic("pmap_copy_page: CMAP2 busy");
2495#ifdef SMP
2496	curthread->td_pcb->pcb_switchout = pmap_zpi_switchout12;
2497#endif
2498	*CMAP1 = PG_V | VM_PAGE_TO_PHYS(src) | PG_A;
2499	*CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(dst) | PG_A | PG_M;
2500#ifdef SMP
2501	invlpg((u_int)CADDR1);
2502	invlpg((u_int)CADDR2);
2503#endif
2504	bcopy(CADDR1, CADDR2, PAGE_SIZE);
2505	*CMAP1 = 0;
2506	*CMAP2 = 0;
2507#ifdef I386_CPU
2508	invltlb();
2509#else
2510	invlpg((u_int)CADDR1);
2511	invlpg((u_int)CADDR2);
2512#endif
2513#ifdef SMP
2514	curthread->td_pcb->pcb_switchout = NULL;
2515#endif
2516	mtx_unlock(&CMAPCADDR12_lock);
2517}
2518
2519/*
2520 * Returns true if the pmap's pv is one of the first
2521 * 16 pvs linked to from this page.  This count may
2522 * be changed upwards or downwards in the future; it
2523 * is only necessary that true be returned for a small
2524 * subset of pmaps for proper page aging.
2525 */
2526boolean_t
2527pmap_page_exists_quick(pmap, m)
2528	pmap_t pmap;
2529	vm_page_t m;
2530{
2531	pv_entry_t pv;
2532	int loops = 0;
2533	int s;
2534
2535	if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
2536		return FALSE;
2537
2538	s = splvm();
2539	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2540	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2541		if (pv->pv_pmap == pmap) {
2542			splx(s);
2543			return TRUE;
2544		}
2545		loops++;
2546		if (loops >= 16)
2547			break;
2548	}
2549	splx(s);
2550	return (FALSE);
2551}
2552
2553#define PMAP_REMOVE_PAGES_CURPROC_ONLY
2554/*
2555 * Remove all pages from specified address space
2556 * this aids process exit speeds.  Also, this code
2557 * is special cased for current process only, but
2558 * can have the more generic (and slightly slower)
2559 * mode enabled.  This is much faster than pmap_remove
2560 * in the case of running down an entire address space.
2561 */
2562void
2563pmap_remove_pages(pmap, sva, eva)
2564	pmap_t pmap;
2565	vm_offset_t sva, eva;
2566{
2567	pt_entry_t *pte, tpte;
2568	vm_page_t m;
2569	pv_entry_t pv, npv;
2570	int s;
2571
2572#ifdef PMAP_REMOVE_PAGES_CURPROC_ONLY
2573	if (!curthread || (pmap != vmspace_pmap(curthread->td_proc->p_vmspace))) {
2574		printf("warning: pmap_remove_pages called with non-current pmap\n");
2575		return;
2576	}
2577#endif
2578	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2579	s = splvm();
2580	for (pv = TAILQ_FIRST(&pmap->pm_pvlist); pv; pv = npv) {
2581
2582		if (pv->pv_va >= eva || pv->pv_va < sva) {
2583			npv = TAILQ_NEXT(pv, pv_plist);
2584			continue;
2585		}
2586
2587#ifdef PMAP_REMOVE_PAGES_CURPROC_ONLY
2588		pte = vtopte(pv->pv_va);
2589#else
2590		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
2591#endif
2592		tpte = *pte;
2593
2594		if (tpte == 0) {
2595			printf("TPTE at %p  IS ZERO @ VA %08x\n",
2596							pte, pv->pv_va);
2597			panic("bad pte");
2598		}
2599
2600/*
2601 * We cannot remove wired pages from a process' mapping at this time
2602 */
2603		if (tpte & PG_W) {
2604			npv = TAILQ_NEXT(pv, pv_plist);
2605			continue;
2606		}
2607
2608		m = PHYS_TO_VM_PAGE(tpte);
2609		KASSERT(m->phys_addr == (tpte & PG_FRAME),
2610		    ("vm_page_t %p phys_addr mismatch %016jx %016jx",
2611		    m, (uintmax_t)m->phys_addr, (uintmax_t)tpte));
2612
2613		KASSERT(m < &vm_page_array[vm_page_array_size],
2614			("pmap_remove_pages: bad tpte %#jx", (uintmax_t)tpte));
2615
2616		pv->pv_pmap->pm_stats.resident_count--;
2617
2618		pte_clear(pte);
2619
2620		/*
2621		 * Update the vm_page_t clean and reference bits.
2622		 */
2623		if (tpte & PG_M) {
2624			vm_page_dirty(m);
2625		}
2626
2627		npv = TAILQ_NEXT(pv, pv_plist);
2628		TAILQ_REMOVE(&pv->pv_pmap->pm_pvlist, pv, pv_plist);
2629
2630		m->md.pv_list_count--;
2631		TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2632		if (TAILQ_FIRST(&m->md.pv_list) == NULL) {
2633			vm_page_flag_clear(m, PG_WRITEABLE);
2634		}
2635
2636		pmap_unuse_pt(pv->pv_pmap, pv->pv_va, pv->pv_ptem);
2637		free_pv_entry(pv);
2638	}
2639	splx(s);
2640	pmap_invalidate_all(pmap);
2641}
2642
2643/*
2644 *	pmap_is_modified:
2645 *
2646 *	Return whether or not the specified physical page was modified
2647 *	in any physical maps.
2648 */
2649boolean_t
2650pmap_is_modified(vm_page_t m)
2651{
2652	pv_entry_t pv;
2653	pt_entry_t *pte;
2654	int s;
2655
2656	if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
2657		return FALSE;
2658
2659	s = splvm();
2660	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2661	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2662		/*
2663		 * if the bit being tested is the modified bit, then
2664		 * mark clean_map and ptes as never
2665		 * modified.
2666		 */
2667		if (!pmap_track_modified(pv->pv_va))
2668			continue;
2669#if defined(PMAP_DIAGNOSTIC)
2670		if (!pv->pv_pmap) {
2671			printf("Null pmap (tb) at va: 0x%x\n", pv->pv_va);
2672			continue;
2673		}
2674#endif
2675		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
2676		if (*pte & PG_M) {
2677			splx(s);
2678			return TRUE;
2679		}
2680	}
2681	splx(s);
2682	return (FALSE);
2683}
2684
2685/*
2686 *	pmap_is_prefaultable:
2687 *
2688 *	Return whether or not the specified virtual address is elgible
2689 *	for prefault.
2690 */
2691boolean_t
2692pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
2693{
2694	pt_entry_t *pte;
2695
2696	if ((*pmap_pde(pmap, addr)) == 0)
2697		return (FALSE);
2698	pte = vtopte(addr);
2699	if (*pte)
2700		return (FALSE);
2701	return (TRUE);
2702}
2703
2704/*
2705 *	Clear the given bit in each of the given page's ptes.
2706 */
2707static __inline void
2708pmap_clear_ptes(vm_page_t m, int bit)
2709{
2710	register pv_entry_t pv;
2711	pt_entry_t pbits, *pte;
2712	int s;
2713
2714	if (!pmap_initialized || (m->flags & PG_FICTITIOUS) ||
2715	    (bit == PG_RW && (m->flags & PG_WRITEABLE) == 0))
2716		return;
2717
2718	s = splvm();
2719	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2720	/*
2721	 * Loop over all current mappings setting/clearing as appropos If
2722	 * setting RO do we need to clear the VAC?
2723	 */
2724	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2725		/*
2726		 * don't write protect pager mappings
2727		 */
2728		if (bit == PG_RW) {
2729			if (!pmap_track_modified(pv->pv_va))
2730				continue;
2731		}
2732
2733#if defined(PMAP_DIAGNOSTIC)
2734		if (!pv->pv_pmap) {
2735			printf("Null pmap (cb) at va: 0x%x\n", pv->pv_va);
2736			continue;
2737		}
2738#endif
2739
2740		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
2741		pbits = *pte;
2742		if (pbits & bit) {
2743			if (bit == PG_RW) {
2744				if (pbits & PG_M) {
2745					vm_page_dirty(m);
2746				}
2747				pte_store(pte, pbits & ~(PG_M|PG_RW));
2748			} else {
2749				pte_store(pte, pbits & ~bit);
2750			}
2751			pmap_invalidate_page(pv->pv_pmap, pv->pv_va);
2752		}
2753	}
2754	if (bit == PG_RW)
2755		vm_page_flag_clear(m, PG_WRITEABLE);
2756	splx(s);
2757}
2758
2759/*
2760 *      pmap_page_protect:
2761 *
2762 *      Lower the permission for all mappings to a given page.
2763 */
2764void
2765pmap_page_protect(vm_page_t m, vm_prot_t prot)
2766{
2767	if ((prot & VM_PROT_WRITE) == 0) {
2768		if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
2769			pmap_clear_ptes(m, PG_RW);
2770		} else {
2771			pmap_remove_all(m);
2772		}
2773	}
2774}
2775
2776/*
2777 *	pmap_ts_referenced:
2778 *
2779 *	Return a count of reference bits for a page, clearing those bits.
2780 *	It is not necessary for every reference bit to be cleared, but it
2781 *	is necessary that 0 only be returned when there are truly no
2782 *	reference bits set.
2783 *
2784 *	XXX: The exact number of bits to check and clear is a matter that
2785 *	should be tested and standardized at some point in the future for
2786 *	optimal aging of shared pages.
2787 */
2788int
2789pmap_ts_referenced(vm_page_t m)
2790{
2791	register pv_entry_t pv, pvf, pvn;
2792	pt_entry_t *pte;
2793	pt_entry_t v;
2794	int s;
2795	int rtval = 0;
2796
2797	if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
2798		return (rtval);
2799
2800	s = splvm();
2801	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2802	if ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
2803
2804		pvf = pv;
2805
2806		do {
2807			pvn = TAILQ_NEXT(pv, pv_list);
2808
2809			TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2810
2811			TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
2812
2813			if (!pmap_track_modified(pv->pv_va))
2814				continue;
2815
2816			pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
2817
2818			if (pte && ((v = pte_load(pte)) & PG_A) != 0) {
2819				pte_store(pte, v & ~PG_A);
2820				pmap_invalidate_page(pv->pv_pmap, pv->pv_va);
2821
2822				rtval++;
2823				if (rtval > 4) {
2824					break;
2825				}
2826			}
2827		} while ((pv = pvn) != NULL && pv != pvf);
2828	}
2829	splx(s);
2830
2831	return (rtval);
2832}
2833
2834/*
2835 *	Clear the modify bits on the specified physical page.
2836 */
2837void
2838pmap_clear_modify(vm_page_t m)
2839{
2840	pmap_clear_ptes(m, PG_M);
2841}
2842
2843/*
2844 *	pmap_clear_reference:
2845 *
2846 *	Clear the reference bit on the specified physical page.
2847 */
2848void
2849pmap_clear_reference(vm_page_t m)
2850{
2851	pmap_clear_ptes(m, PG_A);
2852}
2853
2854/*
2855 * Miscellaneous support routines follow
2856 */
2857
2858/*
2859 * Map a set of physical memory pages into the kernel virtual
2860 * address space. Return a pointer to where it is mapped. This
2861 * routine is intended to be used for mapping device memory,
2862 * NOT real memory.
2863 */
2864void *
2865pmap_mapdev(pa, size)
2866	vm_paddr_t pa;
2867	vm_size_t size;
2868{
2869	vm_offset_t va, tmpva, offset;
2870
2871	offset = pa & PAGE_MASK;
2872	size = roundup(offset + size, PAGE_SIZE);
2873	pa = pa & PG_FRAME;
2874
2875	if (pa < KERNLOAD && pa + size <= KERNLOAD)
2876		va = KERNBASE + pa;
2877	else
2878		va = kmem_alloc_nofault(kernel_map, size);
2879	if (!va)
2880		panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
2881
2882	for (tmpva = va; size > 0; ) {
2883		pmap_kenter(tmpva, pa);
2884		size -= PAGE_SIZE;
2885		tmpva += PAGE_SIZE;
2886		pa += PAGE_SIZE;
2887	}
2888	pmap_invalidate_range(kernel_pmap, va, tmpva);
2889	return ((void *)(va + offset));
2890}
2891
2892void
2893pmap_unmapdev(va, size)
2894	vm_offset_t va;
2895	vm_size_t size;
2896{
2897	vm_offset_t base, offset, tmpva;
2898
2899	if (va >= KERNBASE && va + size <= KERNBASE + KERNLOAD)
2900		return;
2901	base = va & PG_FRAME;
2902	offset = va & PAGE_MASK;
2903	size = roundup(offset + size, PAGE_SIZE);
2904	for (tmpva = base; tmpva < (base + size); tmpva += PAGE_SIZE)
2905		pmap_kremove(tmpva);
2906	pmap_invalidate_range(kernel_pmap, va, tmpva);
2907	kmem_free(kernel_map, base, size);
2908}
2909
2910/*
2911 * perform the pmap work for mincore
2912 */
2913int
2914pmap_mincore(pmap, addr)
2915	pmap_t pmap;
2916	vm_offset_t addr;
2917{
2918	pt_entry_t *ptep, pte;
2919	vm_page_t m;
2920	int val = 0;
2921
2922	ptep = pmap_pte(pmap, addr);
2923	if (ptep == 0) {
2924		return 0;
2925	}
2926
2927	if ((pte = *ptep) != 0) {
2928		vm_paddr_t pa;
2929
2930		val = MINCORE_INCORE;
2931		if ((pte & PG_MANAGED) == 0)
2932			return val;
2933
2934		pa = pte & PG_FRAME;
2935
2936		m = PHYS_TO_VM_PAGE(pa);
2937
2938		/*
2939		 * Modified by us
2940		 */
2941		if (pte & PG_M)
2942			val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
2943		else {
2944			/*
2945			 * Modified by someone else
2946			 */
2947			vm_page_lock_queues();
2948			if (m->dirty || pmap_is_modified(m))
2949				val |= MINCORE_MODIFIED_OTHER;
2950			vm_page_unlock_queues();
2951		}
2952		/*
2953		 * Referenced by us
2954		 */
2955		if (pte & PG_A)
2956			val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
2957		else {
2958			/*
2959			 * Referenced by someone else
2960			 */
2961			vm_page_lock_queues();
2962			if ((m->flags & PG_REFERENCED) ||
2963			    pmap_ts_referenced(m)) {
2964				val |= MINCORE_REFERENCED_OTHER;
2965				vm_page_flag_set(m, PG_REFERENCED);
2966			}
2967			vm_page_unlock_queues();
2968		}
2969	}
2970	return val;
2971}
2972
2973void
2974pmap_activate(struct thread *td)
2975{
2976	struct proc *p = td->td_proc;
2977	pmap_t	pmap, oldpmap;
2978	u_int32_t  cr3;
2979
2980	critical_enter();
2981	pmap = vmspace_pmap(td->td_proc->p_vmspace);
2982	oldpmap = PCPU_GET(curpmap);
2983#if defined(SMP)
2984	atomic_clear_int(&oldpmap->pm_active, PCPU_GET(cpumask));
2985	atomic_set_int(&pmap->pm_active, PCPU_GET(cpumask));
2986#else
2987	oldpmap->pm_active &= ~1;
2988	pmap->pm_active |= 1;
2989#endif
2990#ifdef PAE
2991	cr3 = vtophys(pmap->pm_pdpt);
2992#else
2993	cr3 = vtophys(pmap->pm_pdir);
2994#endif
2995	/* XXXKSE this is wrong.
2996	 * pmap_activate is for the current thread on the current cpu
2997	 */
2998	if (p->p_flag & P_SA) {
2999		/* Make sure all other cr3 entries are updated. */
3000		/* what if they are running?  XXXKSE (maybe abort them) */
3001		FOREACH_THREAD_IN_PROC(p, td) {
3002			td->td_pcb->pcb_cr3 = cr3;
3003		}
3004	} else {
3005		td->td_pcb->pcb_cr3 = cr3;
3006	}
3007	load_cr3(cr3);
3008	PCPU_SET(curpmap, pmap);
3009	critical_exit();
3010}
3011
3012vm_offset_t
3013pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
3014{
3015
3016	if ((obj == NULL) || (size < NBPDR) || (obj->type != OBJT_DEVICE)) {
3017		return addr;
3018	}
3019
3020	addr = (addr + PDRMASK) & ~PDRMASK;
3021	return addr;
3022}
3023
3024
3025#if defined(PMAP_DEBUG)
3026pmap_pid_dump(int pid)
3027{
3028	pmap_t pmap;
3029	struct proc *p;
3030	int npte = 0;
3031	int index;
3032
3033	sx_slock(&allproc_lock);
3034	LIST_FOREACH(p, &allproc, p_list) {
3035		if (p->p_pid != pid)
3036			continue;
3037
3038		if (p->p_vmspace) {
3039			int i,j;
3040			index = 0;
3041			pmap = vmspace_pmap(p->p_vmspace);
3042			for (i = 0; i < NPDEPTD; i++) {
3043				pd_entry_t *pde;
3044				pt_entry_t *pte;
3045				vm_offset_t base = i << PDRSHIFT;
3046
3047				pde = &pmap->pm_pdir[i];
3048				if (pde && pmap_pde_v(pde)) {
3049					for (j = 0; j < NPTEPG; j++) {
3050						vm_offset_t va = base + (j << PAGE_SHIFT);
3051						if (va >= (vm_offset_t) VM_MIN_KERNEL_ADDRESS) {
3052							if (index) {
3053								index = 0;
3054								printf("\n");
3055							}
3056							sx_sunlock(&allproc_lock);
3057							return npte;
3058						}
3059						pte = pmap_pte(pmap, va);
3060						if (pte && pmap_pte_v(pte)) {
3061							pt_entry_t pa;
3062							vm_page_t m;
3063							pa = *pte;
3064							m = PHYS_TO_VM_PAGE(pa);
3065							printf("va: 0x%x, pt: 0x%x, h: %d, w: %d, f: 0x%x",
3066								va, pa, m->hold_count, m->wire_count, m->flags);
3067							npte++;
3068							index++;
3069							if (index >= 2) {
3070								index = 0;
3071								printf("\n");
3072							} else {
3073								printf(" ");
3074							}
3075						}
3076					}
3077				}
3078			}
3079		}
3080	}
3081	sx_sunlock(&allproc_lock);
3082	return npte;
3083}
3084#endif
3085
3086#if defined(DEBUG)
3087
3088static void	pads(pmap_t pm);
3089void		pmap_pvdump(vm_offset_t pa);
3090
3091/* print address space of pmap*/
3092static void
3093pads(pm)
3094	pmap_t pm;
3095{
3096	int i, j;
3097	vm_paddr_t va;
3098	pt_entry_t *ptep;
3099
3100	if (pm == kernel_pmap)
3101		return;
3102	for (i = 0; i < NPDEPTD; i++)
3103		if (pm->pm_pdir[i])
3104			for (j = 0; j < NPTEPG; j++) {
3105				va = (i << PDRSHIFT) + (j << PAGE_SHIFT);
3106				if (pm == kernel_pmap && va < KERNBASE)
3107					continue;
3108				if (pm != kernel_pmap && va > UPT_MAX_ADDRESS)
3109					continue;
3110				ptep = pmap_pte(pm, va);
3111				if (pmap_pte_v(ptep))
3112					printf("%x:%x ", va, *ptep);
3113			};
3114
3115}
3116
3117void
3118pmap_pvdump(pa)
3119	vm_paddr_t pa;
3120{
3121	pv_entry_t pv;
3122	vm_page_t m;
3123
3124	printf("pa %x", pa);
3125	m = PHYS_TO_VM_PAGE(pa);
3126	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3127		printf(" -> pmap %p, va %x", (void *)pv->pv_pmap, pv->pv_va);
3128		pads(pv->pv_pmap);
3129	}
3130	printf(" ");
3131}
3132#endif
3133