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