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