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