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