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