pmap.c revision 130560
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 130560 2004-06-16 05:42: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, *ptmmap;
220caddr_t CADDR1 = 0, ptvmmap = 0;
221static caddr_t CADDR2, CADDR3;
222static struct mtx CMAPCADDR12_lock;
223static pt_entry_t *msgbufmap;
224struct msgbuf *msgbufp = 0;
225
226/*
227 * Crashdump maps.
228 */
229static pt_entry_t *pt_crashdumpmap;
230static caddr_t crashdumpmap;
231
232#ifdef SMP
233extern pt_entry_t *SMPpt;
234#endif
235static pt_entry_t *PMAP1 = 0, *PMAP2;
236static pt_entry_t *PADDR1 = 0, *PADDR2;
237#ifdef SMP
238static int PMAP1cpu;
239static int PMAP1changedcpu;
240SYSCTL_INT(_debug, OID_AUTO, PMAP1changedcpu, CTLFLAG_RD,
241	   &PMAP1changedcpu, 0,
242	   "Number of times pmap_pte_quick changed CPU with same PMAP1");
243#endif
244static int PMAP1changed;
245SYSCTL_INT(_debug, OID_AUTO, PMAP1changed, CTLFLAG_RD,
246	   &PMAP1changed, 0,
247	   "Number of times pmap_pte_quick changed PMAP1");
248static int PMAP1unchanged;
249SYSCTL_INT(_debug, OID_AUTO, PMAP1unchanged, CTLFLAG_RD,
250	   &PMAP1unchanged, 0,
251	   "Number of times pmap_pte_quick didn't change PMAP1");
252
253static PMAP_INLINE void	free_pv_entry(pv_entry_t pv);
254static pv_entry_t get_pv_entry(void);
255static void	pmap_clear_ptes(vm_page_t m, int bit);
256
257static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva);
258static void pmap_remove_page(struct pmap *pmap, vm_offset_t va);
259static int pmap_remove_entry(struct pmap *pmap, vm_page_t m,
260					vm_offset_t va);
261static void pmap_insert_entry(pmap_t pmap, vm_offset_t va,
262		vm_page_t mpte, vm_page_t m);
263
264static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va);
265
266static vm_page_t _pmap_allocpte(pmap_t pmap, unsigned ptepindex);
267static pt_entry_t *pmap_pte_quick(pmap_t pmap, vm_offset_t va);
268static int pmap_unuse_pt(pmap_t, vm_offset_t, vm_page_t);
269static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
270#ifdef PAE
271static void *pmap_pdpt_allocf(uma_zone_t zone, int bytes, u_int8_t *flags, int wait);
272#endif
273
274CTASSERT(1 << PDESHIFT == sizeof(pd_entry_t));
275CTASSERT(1 << PTESHIFT == sizeof(pt_entry_t));
276
277/*
278 * Move the kernel virtual free pointer to the next
279 * 4MB.  This is used to help improve performance
280 * by using a large (4MB) page for much of the kernel
281 * (.text, .data, .bss)
282 */
283static vm_offset_t
284pmap_kmem_choose(vm_offset_t addr)
285{
286	vm_offset_t newaddr = addr;
287
288#ifndef DISABLE_PSE
289	if (cpu_feature & CPUID_PSE)
290		newaddr = (addr + PDRMASK) & ~PDRMASK;
291#endif
292	return newaddr;
293}
294
295/*
296 *	Bootstrap the system enough to run with virtual memory.
297 *
298 *	On the i386 this is called after mapping has already been enabled
299 *	and just syncs the pmap module with what has already been done.
300 *	[We can't call it easily with mapping off since the kernel is not
301 *	mapped with PA == VA, hence we would have to relocate every address
302 *	from the linked base (virtual) address "KERNBASE" to the actual
303 *	(physical) address starting relative to 0]
304 */
305void
306pmap_bootstrap(firstaddr, loadaddr)
307	vm_paddr_t firstaddr;
308	vm_paddr_t loadaddr;
309{
310	vm_offset_t va;
311	pt_entry_t *pte;
312	int i;
313
314	/*
315	 * XXX The calculation of virtual_avail is wrong. It's NKPT*PAGE_SIZE too
316	 * large. It should instead be correctly calculated in locore.s and
317	 * not based on 'first' (which is a physical address, not a virtual
318	 * address, for the start of unused physical memory). The kernel
319	 * page tables are NOT double mapped and thus should not be included
320	 * in this calculation.
321	 */
322	virtual_avail = (vm_offset_t) KERNBASE + firstaddr;
323	virtual_avail = pmap_kmem_choose(virtual_avail);
324
325	virtual_end = VM_MAX_KERNEL_ADDRESS;
326
327	/*
328	 * Initialize the kernel pmap (which is statically allocated).
329	 */
330	kernel_pmap->pm_pdir = (pd_entry_t *) (KERNBASE + (u_int)IdlePTD);
331#ifdef PAE
332	kernel_pmap->pm_pdpt = (pdpt_entry_t *) (KERNBASE + (u_int)IdlePDPT);
333#endif
334	kernel_pmap->pm_active = -1;	/* don't allow deactivation */
335	TAILQ_INIT(&kernel_pmap->pm_pvlist);
336	LIST_INIT(&allpmaps);
337#ifdef SMP
338	mtx_init(&lazypmap_lock, "lazypmap", NULL, MTX_SPIN);
339#endif
340	mtx_init(&allpmaps_lock, "allpmaps", NULL, MTX_SPIN);
341	mtx_lock_spin(&allpmaps_lock);
342	LIST_INSERT_HEAD(&allpmaps, kernel_pmap, pm_list);
343	mtx_unlock_spin(&allpmaps_lock);
344	nkpt = NKPT;
345
346	/*
347	 * Reserve some special page table entries/VA space for temporary
348	 * mapping of pages.
349	 */
350#define	SYSMAP(c, p, v, n)	\
351	v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
352
353	va = virtual_avail;
354	pte = vtopte(va);
355
356	/*
357	 * CMAP1/CMAP2 are used for zeroing and copying pages.
358	 * CMAP3 is used for the idle process page zeroing.
359	 */
360	SYSMAP(caddr_t, CMAP1, CADDR1, 1)
361	SYSMAP(caddr_t, CMAP2, CADDR2, 1)
362	SYSMAP(caddr_t, CMAP3, CADDR3, 1)
363	*CMAP3 = 0;
364
365	mtx_init(&CMAPCADDR12_lock, "CMAPCADDR12", NULL, MTX_DEF);
366
367	/*
368	 * Crashdump maps.
369	 */
370	SYSMAP(caddr_t, pt_crashdumpmap, crashdumpmap, MAXDUMPPGS);
371
372	/*
373	 * ptvmmap is used for reading arbitrary physical pages via /dev/mem.
374	 * XXX ptmmap is not used.
375	 */
376	SYSMAP(caddr_t, ptmmap, ptvmmap, 1)
377
378	/*
379	 * msgbufp is used to map the system message buffer.
380	 * XXX msgbufmap is not used.
381	 */
382	SYSMAP(struct msgbuf *, msgbufmap, msgbufp,
383	       atop(round_page(MSGBUF_SIZE)))
384
385	/*
386	 * ptemap is used for pmap_pte_quick
387	 */
388	SYSMAP(pt_entry_t *, PMAP1, PADDR1, 1);
389	SYSMAP(pt_entry_t *, PMAP2, PADDR2, 1);
390
391	virtual_avail = va;
392
393	*CMAP1 = *CMAP2 = 0;
394	for (i = 0; i < NKPT; i++)
395		PTD[i] = 0;
396
397	/* Turn on PG_G on kernel page(s) */
398	pmap_set_pg();
399}
400
401/*
402 * Set PG_G on kernel pages.  Only the BSP calls this when SMP is turned on.
403 */
404void
405pmap_set_pg(void)
406{
407	pd_entry_t pdir;
408	pt_entry_t *pte;
409	vm_offset_t va, endva;
410	int i;
411
412	if (pgeflag == 0)
413		return;
414
415	i = KERNLOAD/NBPDR;
416	endva = KERNBASE + KERNend;
417
418	if (pseflag) {
419		va = KERNBASE + KERNLOAD;
420		while (va  < endva) {
421			pdir = kernel_pmap->pm_pdir[KPTDI+i];
422			pdir |= pgeflag;
423			kernel_pmap->pm_pdir[KPTDI+i] = PTD[KPTDI+i] = pdir;
424			invltlb();	/* Play it safe, invltlb() every time */
425			i++;
426			va += NBPDR;
427		}
428	} else {
429		va = (vm_offset_t)btext;
430		while (va < endva) {
431			pte = vtopte(va);
432			if (*pte)
433				*pte |= pgeflag;
434			invltlb();	/* Play it safe, invltlb() every time */
435			va += PAGE_SIZE;
436		}
437	}
438}
439
440#ifdef PAE
441static void *
442pmap_pdpt_allocf(uma_zone_t zone, int bytes, u_int8_t *flags, int wait)
443{
444	*flags = UMA_SLAB_PRIV;
445	return (contigmalloc(PAGE_SIZE, NULL, 0, 0x0ULL, 0xffffffffULL, 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, va)
830	register pmap_t pmap;
831	vm_offset_t va;
832{
833	vm_paddr_t rtval;
834	pt_entry_t *pte;
835	pd_entry_t pde;
836
837	if (pmap == 0)
838		return 0;
839	pde = pmap->pm_pdir[va >> PDRSHIFT];
840	if (pde != 0) {
841		if ((pde & PG_PS) != 0) {
842			rtval = (pde & ~PDRMASK) | (va & PDRMASK);
843			return rtval;
844		}
845		pte = pmap_pte(pmap, va);
846		rtval = ((*pte & PG_FRAME) | (va & PAGE_MASK));
847		return rtval;
848	}
849	return 0;
850
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	vm_paddr_t pa;
864	vm_page_t m;
865
866	m = NULL;
867	mtx_lock(&Giant);
868	if ((pa = pmap_extract(pmap, va)) != 0) {
869		m = PHYS_TO_VM_PAGE(pa);
870		vm_page_lock_queues();
871		vm_page_hold(m);
872		vm_page_unlock_queues();
873	}
874	mtx_unlock(&Giant);
875	return (m);
876}
877
878/***************************************************
879 * Low level mapping routines.....
880 ***************************************************/
881
882/*
883 * Add a wired page to the kva.
884 * Note: not SMP coherent.
885 */
886PMAP_INLINE void
887pmap_kenter(vm_offset_t va, vm_paddr_t pa)
888{
889	pt_entry_t *pte;
890
891	pte = vtopte(va);
892	pte_store(pte, pa | PG_RW | PG_V | pgeflag);
893}
894
895/*
896 * Remove a page from the kernel pagetables.
897 * Note: not SMP coherent.
898 */
899PMAP_INLINE void
900pmap_kremove(vm_offset_t va)
901{
902	pt_entry_t *pte;
903
904	pte = vtopte(va);
905	pte_clear(pte);
906}
907
908/*
909 *	Used to map a range of physical addresses into kernel
910 *	virtual address space.
911 *
912 *	The value passed in '*virt' is a suggested virtual address for
913 *	the mapping. Architectures which can support a direct-mapped
914 *	physical to virtual region can return the appropriate address
915 *	within that region, leaving '*virt' unchanged. Other
916 *	architectures should map the pages starting at '*virt' and
917 *	update '*virt' with the first usable address after the mapped
918 *	region.
919 */
920vm_offset_t
921pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
922{
923	vm_offset_t va, sva;
924
925	va = sva = *virt;
926	while (start < end) {
927		pmap_kenter(va, start);
928		va += PAGE_SIZE;
929		start += PAGE_SIZE;
930	}
931	pmap_invalidate_range(kernel_pmap, sva, va);
932	*virt = va;
933	return (sva);
934}
935
936
937/*
938 * Add a list of wired pages to the kva
939 * this routine is only used for temporary
940 * kernel mappings that do not need to have
941 * page modification or references recorded.
942 * Note that old mappings are simply written
943 * over.  The page *must* be wired.
944 * Note: SMP coherent.  Uses a ranged shootdown IPI.
945 */
946void
947pmap_qenter(vm_offset_t sva, vm_page_t *m, int count)
948{
949	vm_offset_t va;
950
951	va = sva;
952	while (count-- > 0) {
953		pmap_kenter(va, VM_PAGE_TO_PHYS(*m));
954		va += PAGE_SIZE;
955		m++;
956	}
957	pmap_invalidate_range(kernel_pmap, sva, va);
958}
959
960/*
961 * This routine tears out page mappings from the
962 * kernel -- it is meant only for temporary mappings.
963 * Note: SMP coherent.  Uses a ranged shootdown IPI.
964 */
965void
966pmap_qremove(vm_offset_t sva, int count)
967{
968	vm_offset_t va;
969
970	va = sva;
971	while (count-- > 0) {
972		pmap_kremove(va);
973		va += PAGE_SIZE;
974	}
975	pmap_invalidate_range(kernel_pmap, sva, va);
976}
977
978/***************************************************
979 * Page table page management routines.....
980 ***************************************************/
981
982/*
983 * This routine unholds page table pages, and if the hold count
984 * drops to zero, then it decrements the wire count.
985 */
986static int
987_pmap_unwire_pte_hold(pmap_t pmap, vm_page_t m)
988{
989
990	while (vm_page_sleep_if_busy(m, FALSE, "pmuwpt"))
991		vm_page_lock_queues();
992
993	if (m->hold_count == 0) {
994		vm_offset_t pteva;
995		/*
996		 * unmap the page table page
997		 */
998		pmap->pm_pdir[m->pindex] = 0;
999		--pmap->pm_stats.resident_count;
1000		/*
1001		 * We never unwire a kernel page table page, making a
1002		 * check for the kernel_pmap unnecessary.
1003		 */
1004		if ((pmap->pm_pdir[PTDPTDI] & PG_FRAME) == (PTDpde[0] & PG_FRAME)) {
1005			/*
1006			 * Do an invltlb to make the invalidated mapping
1007			 * take effect immediately.
1008			 */
1009			pteva = VM_MAXUSER_ADDRESS + i386_ptob(m->pindex);
1010			pmap_invalidate_page(pmap, pteva);
1011		}
1012
1013		/*
1014		 * If the page is finally unwired, simply free it.
1015		 */
1016		--m->wire_count;
1017		if (m->wire_count == 0) {
1018			vm_page_busy(m);
1019			vm_page_free_zero(m);
1020			atomic_subtract_int(&cnt.v_wire_count, 1);
1021		}
1022		return 1;
1023	}
1024	return 0;
1025}
1026
1027static PMAP_INLINE int
1028pmap_unwire_pte_hold(pmap_t pmap, vm_page_t m)
1029{
1030	vm_page_unhold(m);
1031	if (m->hold_count == 0)
1032		return _pmap_unwire_pte_hold(pmap, m);
1033	else
1034		return 0;
1035}
1036
1037/*
1038 * After removing a page table entry, this routine is used to
1039 * conditionally free the page, and manage the hold/wire counts.
1040 */
1041static int
1042pmap_unuse_pt(pmap_t pmap, vm_offset_t va, vm_page_t mpte)
1043{
1044
1045	if (va >= VM_MAXUSER_ADDRESS)
1046		return 0;
1047
1048	return pmap_unwire_pte_hold(pmap, mpte);
1049}
1050
1051void
1052pmap_pinit0(pmap)
1053	struct pmap *pmap;
1054{
1055
1056	pmap->pm_pdir = (pd_entry_t *)(KERNBASE + (vm_offset_t)IdlePTD);
1057#ifdef PAE
1058	pmap->pm_pdpt = (pdpt_entry_t *)(KERNBASE + (vm_offset_t)IdlePDPT);
1059#endif
1060	pmap->pm_active = 0;
1061	PCPU_SET(curpmap, pmap);
1062	TAILQ_INIT(&pmap->pm_pvlist);
1063	bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1064	mtx_lock_spin(&allpmaps_lock);
1065	LIST_INSERT_HEAD(&allpmaps, pmap, pm_list);
1066	mtx_unlock_spin(&allpmaps_lock);
1067}
1068
1069/*
1070 * Initialize a preallocated and zeroed pmap structure,
1071 * such as one in a vmspace structure.
1072 */
1073void
1074pmap_pinit(pmap)
1075	register struct pmap *pmap;
1076{
1077	vm_page_t m, ptdpg[NPGPTD];
1078	vm_paddr_t pa;
1079	static int color;
1080	int i;
1081
1082	/*
1083	 * No need to allocate page table space yet but we do need a valid
1084	 * page directory table.
1085	 */
1086	if (pmap->pm_pdir == NULL) {
1087		pmap->pm_pdir = (pd_entry_t *)kmem_alloc_nofault(kernel_map,
1088		    NBPTD);
1089#ifdef PAE
1090		pmap->pm_pdpt = uma_zalloc(pdptzone, M_WAITOK | M_ZERO);
1091		KASSERT(((vm_offset_t)pmap->pm_pdpt &
1092		    ((NPGPTD * sizeof(pdpt_entry_t)) - 1)) == 0,
1093		    ("pmap_pinit: pdpt misaligned"));
1094		KASSERT(pmap_kextract((vm_offset_t)pmap->pm_pdpt) < (4ULL<<30),
1095		    ("pmap_pinit: pdpt above 4g"));
1096#endif
1097	}
1098
1099	/*
1100	 * allocate the page directory page(s)
1101	 */
1102	for (i = 0; i < NPGPTD;) {
1103		m = vm_page_alloc(NULL, color++,
1104		    VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
1105		    VM_ALLOC_ZERO);
1106		if (m == NULL)
1107			VM_WAIT;
1108		else {
1109			ptdpg[i++] = m;
1110		}
1111	}
1112
1113	pmap_qenter((vm_offset_t)pmap->pm_pdir, ptdpg, NPGPTD);
1114
1115	for (i = 0; i < NPGPTD; i++) {
1116		if ((ptdpg[i]->flags & PG_ZERO) == 0)
1117			bzero(pmap->pm_pdir + (i * NPDEPG), PAGE_SIZE);
1118	}
1119
1120	mtx_lock_spin(&allpmaps_lock);
1121	LIST_INSERT_HEAD(&allpmaps, pmap, pm_list);
1122	mtx_unlock_spin(&allpmaps_lock);
1123	/* Wire in kernel global address entries. */
1124	/* XXX copies current process, does not fill in MPPTDI */
1125	bcopy(PTD + KPTDI, pmap->pm_pdir + KPTDI, nkpt * sizeof(pd_entry_t));
1126#ifdef SMP
1127	pmap->pm_pdir[MPPTDI] = PTD[MPPTDI];
1128#endif
1129
1130	/* install self-referential address mapping entry(s) */
1131	for (i = 0; i < NPGPTD; i++) {
1132		pa = VM_PAGE_TO_PHYS(ptdpg[i]);
1133		pmap->pm_pdir[PTDPTDI + i] = pa | PG_V | PG_RW | PG_A | PG_M;
1134#ifdef PAE
1135		pmap->pm_pdpt[i] = pa | PG_V;
1136#endif
1137	}
1138
1139	pmap->pm_active = 0;
1140	TAILQ_INIT(&pmap->pm_pvlist);
1141	bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1142}
1143
1144/*
1145 * this routine is called if the page table page is not
1146 * mapped correctly.
1147 */
1148static vm_page_t
1149_pmap_allocpte(pmap, ptepindex)
1150	pmap_t	pmap;
1151	unsigned ptepindex;
1152{
1153	vm_paddr_t ptepa;
1154	vm_page_t m;
1155
1156	/*
1157	 * Allocate a page table page.
1158	 */
1159	if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
1160	    VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
1161		VM_WAIT;
1162		/*
1163		 * Indicate the need to retry.  While waiting, the page table
1164		 * page may have been allocated.
1165		 */
1166		return (NULL);
1167	}
1168	if ((m->flags & PG_ZERO) == 0)
1169		pmap_zero_page(m);
1170
1171	KASSERT(m->queue == PQ_NONE,
1172		("_pmap_allocpte: %p->queue != PQ_NONE", m));
1173
1174	/*
1175	 * Increment the hold count for the page table page
1176	 * (denoting a new mapping.)
1177	 */
1178	m->hold_count++;
1179
1180	/*
1181	 * Map the pagetable page into the process address space, if
1182	 * it isn't already there.
1183	 */
1184
1185	pmap->pm_stats.resident_count++;
1186
1187	ptepa = VM_PAGE_TO_PHYS(m);
1188	pmap->pm_pdir[ptepindex] =
1189		(pd_entry_t) (ptepa | PG_U | PG_RW | PG_V | PG_A | PG_M);
1190
1191	vm_page_lock_queues();
1192	vm_page_wakeup(m);
1193	vm_page_unlock_queues();
1194
1195	return m;
1196}
1197
1198static vm_page_t
1199pmap_allocpte(pmap_t pmap, vm_offset_t va)
1200{
1201	unsigned ptepindex;
1202	pd_entry_t ptepa;
1203	vm_page_t m;
1204
1205	/*
1206	 * Calculate pagetable page index
1207	 */
1208	ptepindex = va >> PDRSHIFT;
1209retry:
1210	/*
1211	 * Get the page directory entry
1212	 */
1213	ptepa = pmap->pm_pdir[ptepindex];
1214
1215	/*
1216	 * This supports switching from a 4MB page to a
1217	 * normal 4K page.
1218	 */
1219	if (ptepa & PG_PS) {
1220		pmap->pm_pdir[ptepindex] = 0;
1221		ptepa = 0;
1222		pmap_invalidate_all(kernel_pmap);
1223	}
1224
1225	/*
1226	 * If the page table page is mapped, we just increment the
1227	 * hold count, and activate it.
1228	 */
1229	if (ptepa) {
1230		m = PHYS_TO_VM_PAGE(ptepa);
1231		m->hold_count++;
1232	} else {
1233		/*
1234		 * Here if the pte page isn't mapped, or if it has
1235		 * been deallocated.
1236		 */
1237		m = _pmap_allocpte(pmap, ptepindex);
1238		if (m == NULL)
1239			goto retry;
1240	}
1241	return (m);
1242}
1243
1244
1245/***************************************************
1246* Pmap allocation/deallocation routines.
1247 ***************************************************/
1248
1249#ifdef SMP
1250/*
1251 * Deal with a SMP shootdown of other users of the pmap that we are
1252 * trying to dispose of.  This can be a bit hairy.
1253 */
1254static u_int *lazymask;
1255static u_int lazyptd;
1256static volatile u_int lazywait;
1257
1258void pmap_lazyfix_action(void);
1259
1260void
1261pmap_lazyfix_action(void)
1262{
1263	u_int mymask = PCPU_GET(cpumask);
1264
1265	if (rcr3() == lazyptd)
1266		load_cr3(PCPU_GET(curpcb)->pcb_cr3);
1267	atomic_clear_int(lazymask, mymask);
1268	atomic_store_rel_int(&lazywait, 1);
1269}
1270
1271static void
1272pmap_lazyfix_self(u_int mymask)
1273{
1274
1275	if (rcr3() == lazyptd)
1276		load_cr3(PCPU_GET(curpcb)->pcb_cr3);
1277	atomic_clear_int(lazymask, mymask);
1278}
1279
1280
1281static void
1282pmap_lazyfix(pmap_t pmap)
1283{
1284	u_int mymask = PCPU_GET(cpumask);
1285	u_int mask;
1286	register u_int spins;
1287
1288	while ((mask = pmap->pm_active) != 0) {
1289		spins = 50000000;
1290		mask = mask & -mask;	/* Find least significant set bit */
1291		mtx_lock_spin(&lazypmap_lock);
1292#ifdef PAE
1293		lazyptd = vtophys(pmap->pm_pdpt);
1294#else
1295		lazyptd = vtophys(pmap->pm_pdir);
1296#endif
1297		if (mask == mymask) {
1298			lazymask = &pmap->pm_active;
1299			pmap_lazyfix_self(mymask);
1300		} else {
1301			atomic_store_rel_int((u_int *)&lazymask,
1302			    (u_int)&pmap->pm_active);
1303			atomic_store_rel_int(&lazywait, 0);
1304			ipi_selected(mask, IPI_LAZYPMAP);
1305			while (lazywait == 0) {
1306				ia32_pause();
1307				if (--spins == 0)
1308					break;
1309			}
1310		}
1311		mtx_unlock_spin(&lazypmap_lock);
1312		if (spins == 0)
1313			printf("pmap_lazyfix: spun for 50000000\n");
1314	}
1315}
1316
1317#else	/* SMP */
1318
1319/*
1320 * Cleaning up on uniprocessor is easy.  For various reasons, we're
1321 * unlikely to have to even execute this code, including the fact
1322 * that the cleanup is deferred until the parent does a wait(2), which
1323 * means that another userland process has run.
1324 */
1325static void
1326pmap_lazyfix(pmap_t pmap)
1327{
1328	u_int cr3;
1329
1330	cr3 = vtophys(pmap->pm_pdir);
1331	if (cr3 == rcr3()) {
1332		load_cr3(PCPU_GET(curpcb)->pcb_cr3);
1333		pmap->pm_active &= ~(PCPU_GET(cpumask));
1334	}
1335}
1336#endif	/* SMP */
1337
1338/*
1339 * Release any resources held by the given physical map.
1340 * Called when a pmap initialized by pmap_pinit is being released.
1341 * Should only be called if the map contains no valid mappings.
1342 */
1343void
1344pmap_release(pmap_t pmap)
1345{
1346	vm_page_t m, ptdpg[NPGPTD];
1347	int i;
1348
1349	KASSERT(pmap->pm_stats.resident_count == 0,
1350	    ("pmap_release: pmap resident count %ld != 0",
1351	    pmap->pm_stats.resident_count));
1352
1353	pmap_lazyfix(pmap);
1354	mtx_lock_spin(&allpmaps_lock);
1355	LIST_REMOVE(pmap, pm_list);
1356	mtx_unlock_spin(&allpmaps_lock);
1357
1358	for (i = 0; i < NPGPTD; i++)
1359		ptdpg[i] = PHYS_TO_VM_PAGE(pmap->pm_pdir[PTDPTDI + i]);
1360
1361	bzero(pmap->pm_pdir + PTDPTDI, (nkpt + NPGPTD) *
1362	    sizeof(*pmap->pm_pdir));
1363#ifdef SMP
1364	pmap->pm_pdir[MPPTDI] = 0;
1365#endif
1366
1367	pmap_qremove((vm_offset_t)pmap->pm_pdir, NPGPTD);
1368
1369	vm_page_lock_queues();
1370	for (i = 0; i < NPGPTD; i++) {
1371		m = ptdpg[i];
1372#ifdef PAE
1373		KASSERT(VM_PAGE_TO_PHYS(m) == (pmap->pm_pdpt[i] & PG_FRAME),
1374		    ("pmap_release: got wrong ptd page"));
1375#endif
1376		m->wire_count--;
1377		atomic_subtract_int(&cnt.v_wire_count, 1);
1378		vm_page_free_zero(m);
1379	}
1380	vm_page_unlock_queues();
1381}
1382
1383static int
1384kvm_size(SYSCTL_HANDLER_ARGS)
1385{
1386	unsigned long ksize = VM_MAX_KERNEL_ADDRESS - KERNBASE;
1387
1388	return sysctl_handle_long(oidp, &ksize, 0, req);
1389}
1390SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
1391    0, 0, kvm_size, "IU", "Size of KVM");
1392
1393static int
1394kvm_free(SYSCTL_HANDLER_ARGS)
1395{
1396	unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
1397
1398	return sysctl_handle_long(oidp, &kfree, 0, req);
1399}
1400SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
1401    0, 0, kvm_free, "IU", "Amount of KVM free");
1402
1403/*
1404 * grow the number of kernel page table entries, if needed
1405 */
1406void
1407pmap_growkernel(vm_offset_t addr)
1408{
1409	struct pmap *pmap;
1410	vm_paddr_t ptppaddr;
1411	vm_page_t nkpg;
1412	pd_entry_t newpdir;
1413	pt_entry_t *pde;
1414
1415	mtx_assert(&kernel_map->system_mtx, MA_OWNED);
1416	if (kernel_vm_end == 0) {
1417		kernel_vm_end = KERNBASE;
1418		nkpt = 0;
1419		while (pdir_pde(PTD, kernel_vm_end)) {
1420			kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1421			nkpt++;
1422		}
1423	}
1424	addr = roundup2(addr, PAGE_SIZE * NPTEPG);
1425	while (kernel_vm_end < addr) {
1426		if (pdir_pde(PTD, kernel_vm_end)) {
1427			kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1428			continue;
1429		}
1430
1431		/*
1432		 * This index is bogus, but out of the way
1433		 */
1434		nkpg = vm_page_alloc(NULL, nkpt,
1435		    VM_ALLOC_NOOBJ | VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
1436		if (!nkpg)
1437			panic("pmap_growkernel: no memory to grow kernel");
1438
1439		nkpt++;
1440
1441		pmap_zero_page(nkpg);
1442		ptppaddr = VM_PAGE_TO_PHYS(nkpg);
1443		newpdir = (pd_entry_t) (ptppaddr | PG_V | PG_RW | PG_A | PG_M);
1444		pdir_pde(PTD, kernel_vm_end) = newpdir;
1445
1446		mtx_lock_spin(&allpmaps_lock);
1447		LIST_FOREACH(pmap, &allpmaps, pm_list) {
1448			pde = pmap_pde(pmap, kernel_vm_end);
1449			pde_store(pde, newpdir);
1450		}
1451		mtx_unlock_spin(&allpmaps_lock);
1452		kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1453	}
1454}
1455
1456
1457/***************************************************
1458 * page management routines.
1459 ***************************************************/
1460
1461/*
1462 * free the pv_entry back to the free list
1463 */
1464static PMAP_INLINE void
1465free_pv_entry(pv_entry_t pv)
1466{
1467	pv_entry_count--;
1468	uma_zfree(pvzone, pv);
1469}
1470
1471/*
1472 * get a new pv_entry, allocating a block from the system
1473 * when needed.
1474 * the memory allocation is performed bypassing the malloc code
1475 * because of the possibility of allocations at interrupt time.
1476 */
1477static pv_entry_t
1478get_pv_entry(void)
1479{
1480	pv_entry_count++;
1481	if (pv_entry_high_water &&
1482		(pv_entry_count > pv_entry_high_water) &&
1483		(pmap_pagedaemon_waken == 0)) {
1484		pmap_pagedaemon_waken = 1;
1485		wakeup (&vm_pages_needed);
1486	}
1487	return uma_zalloc(pvzone, M_NOWAIT);
1488}
1489
1490
1491static int
1492pmap_remove_entry(pmap_t pmap, vm_page_t m, vm_offset_t va)
1493{
1494	pv_entry_t pv;
1495	int rtval;
1496
1497	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1498	if (m->md.pv_list_count < pmap->pm_stats.resident_count) {
1499		TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
1500			if (pmap == pv->pv_pmap && va == pv->pv_va)
1501				break;
1502		}
1503	} else {
1504		TAILQ_FOREACH(pv, &pmap->pm_pvlist, pv_plist) {
1505			if (va == pv->pv_va)
1506				break;
1507		}
1508	}
1509
1510	rtval = 0;
1511	if (pv) {
1512		rtval = pmap_unuse_pt(pmap, va, pv->pv_ptem);
1513		TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
1514		m->md.pv_list_count--;
1515		if (TAILQ_FIRST(&m->md.pv_list) == NULL)
1516			vm_page_flag_clear(m, PG_WRITEABLE);
1517
1518		TAILQ_REMOVE(&pmap->pm_pvlist, pv, pv_plist);
1519		free_pv_entry(pv);
1520	}
1521
1522	return rtval;
1523}
1524
1525/*
1526 * Create a pv entry for page at pa for
1527 * (pmap, va).
1528 */
1529static void
1530pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t mpte, vm_page_t m)
1531{
1532
1533	pv_entry_t pv;
1534
1535	pv = get_pv_entry();
1536	pv->pv_va = va;
1537	pv->pv_pmap = pmap;
1538	pv->pv_ptem = mpte;
1539
1540	vm_page_lock_queues();
1541	TAILQ_INSERT_TAIL(&pmap->pm_pvlist, pv, pv_plist);
1542	TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
1543	m->md.pv_list_count++;
1544
1545	vm_page_unlock_queues();
1546}
1547
1548/*
1549 * pmap_remove_pte: do the things to unmap a page in a process
1550 */
1551static int
1552pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va)
1553{
1554	pt_entry_t oldpte;
1555	vm_page_t m, mpte;
1556
1557	oldpte = pte_load_clear(ptq);
1558	if (oldpte & PG_W)
1559		pmap->pm_stats.wired_count -= 1;
1560	/*
1561	 * Machines that don't support invlpg, also don't support
1562	 * PG_G.
1563	 */
1564	if (oldpte & PG_G)
1565		pmap_invalidate_page(kernel_pmap, va);
1566	pmap->pm_stats.resident_count -= 1;
1567	if (oldpte & PG_MANAGED) {
1568		m = PHYS_TO_VM_PAGE(oldpte);
1569		if (oldpte & PG_M) {
1570#if defined(PMAP_DIAGNOSTIC)
1571			if (pmap_nw_modified((pt_entry_t) oldpte)) {
1572				printf(
1573	"pmap_remove: modified page not writable: va: 0x%x, pte: 0x%x\n",
1574				    va, oldpte);
1575			}
1576#endif
1577			if (pmap_track_modified(va))
1578				vm_page_dirty(m);
1579		}
1580		if (oldpte & PG_A)
1581			vm_page_flag_set(m, PG_REFERENCED);
1582		return pmap_remove_entry(pmap, m, va);
1583	} else {
1584		mpte = PHYS_TO_VM_PAGE(*pmap_pde(pmap, va));
1585		return pmap_unuse_pt(pmap, va, mpte);
1586	}
1587}
1588
1589/*
1590 * Remove a single page from a process address space
1591 */
1592static void
1593pmap_remove_page(pmap_t pmap, vm_offset_t va)
1594{
1595	pt_entry_t *pte;
1596
1597	if ((pte = pmap_pte(pmap, va)) == NULL || *pte == 0)
1598		return;
1599	pmap_remove_pte(pmap, pte, va);
1600	pmap_invalidate_page(pmap, va);
1601}
1602
1603/*
1604 *	Remove the given range of addresses from the specified map.
1605 *
1606 *	It is assumed that the start and end are properly
1607 *	rounded to the page size.
1608 */
1609void
1610pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1611{
1612	vm_offset_t pdnxt;
1613	pd_entry_t ptpaddr;
1614	pt_entry_t *pte;
1615	int anyvalid;
1616
1617	if (pmap == NULL)
1618		return;
1619
1620	if (pmap->pm_stats.resident_count == 0)
1621		return;
1622
1623	/*
1624	 * special handling of removing one page.  a very
1625	 * common operation and easy to short circuit some
1626	 * code.
1627	 */
1628	if ((sva + PAGE_SIZE == eva) &&
1629	    ((pmap->pm_pdir[(sva >> PDRSHIFT)] & PG_PS) == 0)) {
1630		pmap_remove_page(pmap, sva);
1631		return;
1632	}
1633
1634	anyvalid = 0;
1635
1636	for (; sva < eva; sva = pdnxt) {
1637		unsigned pdirindex;
1638
1639		/*
1640		 * Calculate index for next page table.
1641		 */
1642		pdnxt = (sva + NBPDR) & ~PDRMASK;
1643		if (pmap->pm_stats.resident_count == 0)
1644			break;
1645
1646		pdirindex = sva >> PDRSHIFT;
1647		ptpaddr = pmap->pm_pdir[pdirindex];
1648
1649		/*
1650		 * Weed out invalid mappings. Note: we assume that the page
1651		 * directory table is always allocated, and in kernel virtual.
1652		 */
1653		if (ptpaddr == 0)
1654			continue;
1655
1656		/*
1657		 * Check for large page.
1658		 */
1659		if ((ptpaddr & PG_PS) != 0) {
1660			pmap->pm_pdir[pdirindex] = 0;
1661			pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
1662			anyvalid = 1;
1663			continue;
1664		}
1665
1666		/*
1667		 * Limit our scan to either the end of the va represented
1668		 * by the current page table page, or to the end of the
1669		 * range being removed.
1670		 */
1671		if (pdnxt > eva)
1672			pdnxt = eva;
1673
1674		for (; sva != pdnxt; sva += PAGE_SIZE) {
1675			if ((pte = pmap_pte(pmap, sva)) == NULL ||
1676			    *pte == 0)
1677				continue;
1678			anyvalid = 1;
1679			if (pmap_remove_pte(pmap, pte, sva))
1680				break;
1681		}
1682	}
1683
1684	if (anyvalid)
1685		pmap_invalidate_all(pmap);
1686}
1687
1688/*
1689 *	Routine:	pmap_remove_all
1690 *	Function:
1691 *		Removes this physical page from
1692 *		all physical maps in which it resides.
1693 *		Reflects back modify bits to the pager.
1694 *
1695 *	Notes:
1696 *		Original versions of this routine were very
1697 *		inefficient because they iteratively called
1698 *		pmap_remove (slow...)
1699 */
1700
1701void
1702pmap_remove_all(vm_page_t m)
1703{
1704	register pv_entry_t pv;
1705	pt_entry_t *pte, tpte;
1706
1707#if defined(PMAP_DIAGNOSTIC)
1708	/*
1709	 * XXX This makes pmap_remove_all() illegal for non-managed pages!
1710	 */
1711	if (!pmap_initialized || (m->flags & PG_FICTITIOUS)) {
1712		panic("pmap_remove_all: illegal for unmanaged page, va: 0x%x",
1713		    VM_PAGE_TO_PHYS(m));
1714	}
1715#endif
1716	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1717	sched_pin();
1718	while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
1719		pv->pv_pmap->pm_stats.resident_count--;
1720		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
1721		tpte = pte_load_clear(pte);
1722		if (tpte & PG_W)
1723			pv->pv_pmap->pm_stats.wired_count--;
1724		if (tpte & PG_A)
1725			vm_page_flag_set(m, PG_REFERENCED);
1726
1727		/*
1728		 * Update the vm_page_t clean and reference bits.
1729		 */
1730		if (tpte & PG_M) {
1731#if defined(PMAP_DIAGNOSTIC)
1732			if (pmap_nw_modified((pt_entry_t) tpte)) {
1733				printf(
1734	"pmap_remove_all: modified page not writable: va: 0x%x, pte: 0x%x\n",
1735				    pv->pv_va, tpte);
1736			}
1737#endif
1738			if (pmap_track_modified(pv->pv_va))
1739				vm_page_dirty(m);
1740		}
1741		pmap_invalidate_page(pv->pv_pmap, pv->pv_va);
1742		TAILQ_REMOVE(&pv->pv_pmap->pm_pvlist, pv, pv_plist);
1743		TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
1744		m->md.pv_list_count--;
1745		pmap_unuse_pt(pv->pv_pmap, pv->pv_va, pv->pv_ptem);
1746		free_pv_entry(pv);
1747	}
1748	vm_page_flag_clear(m, PG_WRITEABLE);
1749	sched_unpin();
1750}
1751
1752/*
1753 *	Set the physical protection on the
1754 *	specified range of this map as requested.
1755 */
1756void
1757pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
1758{
1759	vm_offset_t pdnxt;
1760	pd_entry_t ptpaddr;
1761	int anychanged;
1762
1763	if (pmap == NULL)
1764		return;
1765
1766	if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
1767		pmap_remove(pmap, sva, eva);
1768		return;
1769	}
1770
1771	if (prot & VM_PROT_WRITE)
1772		return;
1773
1774	anychanged = 0;
1775
1776	for (; sva < eva; sva = pdnxt) {
1777		unsigned pdirindex;
1778
1779		pdnxt = (sva + NBPDR) & ~PDRMASK;
1780
1781		pdirindex = sva >> PDRSHIFT;
1782		ptpaddr = pmap->pm_pdir[pdirindex];
1783
1784		/*
1785		 * Weed out invalid mappings. Note: we assume that the page
1786		 * directory table is always allocated, and in kernel virtual.
1787		 */
1788		if (ptpaddr == 0)
1789			continue;
1790
1791		/*
1792		 * Check for large page.
1793		 */
1794		if ((ptpaddr & PG_PS) != 0) {
1795			pmap->pm_pdir[pdirindex] &= ~(PG_M|PG_RW);
1796			pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
1797			anychanged = 1;
1798			continue;
1799		}
1800
1801		if (pdnxt > eva)
1802			pdnxt = eva;
1803
1804		for (; sva != pdnxt; sva += PAGE_SIZE) {
1805			pt_entry_t pbits;
1806			pt_entry_t *pte;
1807			vm_page_t m;
1808
1809			if ((pte = pmap_pte(pmap, sva)) == NULL)
1810				continue;
1811			pbits = *pte;
1812			if (pbits & PG_MANAGED) {
1813				m = NULL;
1814				if (pbits & PG_A) {
1815					m = PHYS_TO_VM_PAGE(pbits);
1816					vm_page_flag_set(m, PG_REFERENCED);
1817					pbits &= ~PG_A;
1818				}
1819				if ((pbits & PG_M) != 0 &&
1820				    pmap_track_modified(sva)) {
1821					if (m == NULL)
1822						m = PHYS_TO_VM_PAGE(pbits);
1823					vm_page_dirty(m);
1824					pbits &= ~PG_M;
1825				}
1826			}
1827
1828			pbits &= ~PG_RW;
1829
1830			if (pbits != *pte) {
1831				pte_store(pte, pbits);
1832				anychanged = 1;
1833			}
1834		}
1835	}
1836	if (anychanged)
1837		pmap_invalidate_all(pmap);
1838}
1839
1840/*
1841 *	Insert the given physical page (p) at
1842 *	the specified virtual address (v) in the
1843 *	target physical map with the protection requested.
1844 *
1845 *	If specified, the page will be wired down, meaning
1846 *	that the related pte can not be reclaimed.
1847 *
1848 *	NB:  This is the only routine which MAY NOT lazy-evaluate
1849 *	or lose information.  That is, this routine must actually
1850 *	insert this page into the given map NOW.
1851 */
1852void
1853pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
1854	   boolean_t wired)
1855{
1856	vm_paddr_t pa;
1857	register pt_entry_t *pte;
1858	vm_paddr_t opa;
1859	pt_entry_t origpte, newpte;
1860	vm_page_t mpte;
1861
1862	if (pmap == NULL)
1863		return;
1864
1865	va &= PG_FRAME;
1866#ifdef PMAP_DIAGNOSTIC
1867	if (va > VM_MAX_KERNEL_ADDRESS)
1868		panic("pmap_enter: toobig");
1869	if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
1870		panic("pmap_enter: invalid to pmap_enter page table pages (va: 0x%x)", va);
1871#endif
1872
1873	mpte = NULL;
1874	/*
1875	 * In the case that a page table page is not
1876	 * resident, we are creating it here.
1877	 */
1878	if (va < VM_MAXUSER_ADDRESS) {
1879		mpte = pmap_allocpte(pmap, va);
1880	}
1881#if 0 && defined(PMAP_DIAGNOSTIC)
1882	else {
1883		pd_entry_t *pdeaddr = pmap_pde(pmap, va);
1884		origpte = *pdeaddr;
1885		if ((origpte & PG_V) == 0) {
1886			panic("pmap_enter: invalid kernel page table page, pdir=%p, pde=%p, va=%p\n",
1887				pmap->pm_pdir[PTDPTDI], origpte, va);
1888		}
1889	}
1890#endif
1891
1892	pte = pmap_pte(pmap, va);
1893
1894	/*
1895	 * Page Directory table entry not valid, we need a new PT page
1896	 */
1897	if (pte == NULL) {
1898		panic("pmap_enter: invalid page directory pdir=%#jx, va=%#x\n",
1899			(uintmax_t)pmap->pm_pdir[PTDPTDI], va);
1900	}
1901
1902	pa = VM_PAGE_TO_PHYS(m) & PG_FRAME;
1903	origpte = *pte;
1904	opa = origpte & PG_FRAME;
1905
1906	if (origpte & PG_PS) {
1907		/*
1908		 * Yes, I know this will truncate upper address bits for PAE,
1909		 * but I'm actually more interested in the lower bits
1910		 */
1911		printf("pmap_enter: va %p, pte %p, origpte %p\n",
1912		    (void *)va, (void *)pte, (void *)(uintptr_t)origpte);
1913		panic("pmap_enter: attempted pmap_enter on 4MB page");
1914	}
1915
1916	/*
1917	 * Mapping has not changed, must be protection or wiring change.
1918	 */
1919	if (origpte && (opa == pa)) {
1920		/*
1921		 * Wiring change, just update stats. We don't worry about
1922		 * wiring PT pages as they remain resident as long as there
1923		 * are valid mappings in them. Hence, if a user page is wired,
1924		 * the PT page will be also.
1925		 */
1926		if (wired && ((origpte & PG_W) == 0))
1927			pmap->pm_stats.wired_count++;
1928		else if (!wired && (origpte & PG_W))
1929			pmap->pm_stats.wired_count--;
1930
1931#if defined(PMAP_DIAGNOSTIC)
1932		if (pmap_nw_modified((pt_entry_t) origpte)) {
1933			printf(
1934	"pmap_enter: modified page not writable: va: 0x%x, pte: 0x%x\n",
1935			    va, origpte);
1936		}
1937#endif
1938
1939		/*
1940		 * Remove extra pte reference
1941		 */
1942		if (mpte)
1943			mpte->hold_count--;
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_paddr_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
2340static __inline void
2341pagezero(void *page)
2342{
2343#if defined(I686_CPU)
2344	if (cpu_class == CPUCLASS_686) {
2345#if defined(CPU_ENABLE_SSE)
2346		if (cpu_feature & CPUID_SSE2)
2347			sse2_pagezero(page);
2348		else
2349#endif
2350			i686_pagezero(page);
2351	} else
2352#endif
2353		bzero(page, PAGE_SIZE);
2354}
2355
2356/*
2357 *	pmap_zero_page zeros the specified hardware page by mapping
2358 *	the page into KVM and using bzero to clear its contents.
2359 */
2360void
2361pmap_zero_page(vm_page_t m)
2362{
2363
2364	mtx_lock(&CMAPCADDR12_lock);
2365	if (*CMAP2)
2366		panic("pmap_zero_page: CMAP2 busy");
2367	sched_pin();
2368	*CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M;
2369	invlcaddr(CADDR2);
2370	pagezero(CADDR2);
2371	*CMAP2 = 0;
2372	sched_unpin();
2373	mtx_unlock(&CMAPCADDR12_lock);
2374}
2375
2376/*
2377 *	pmap_zero_page_area zeros the specified hardware page by mapping
2378 *	the page into KVM and using bzero to clear its contents.
2379 *
2380 *	off and size may not cover an area beyond a single hardware page.
2381 */
2382void
2383pmap_zero_page_area(vm_page_t m, int off, int size)
2384{
2385
2386	mtx_lock(&CMAPCADDR12_lock);
2387	if (*CMAP2)
2388		panic("pmap_zero_page: CMAP2 busy");
2389	sched_pin();
2390	*CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M;
2391	invlcaddr(CADDR2);
2392	if (off == 0 && size == PAGE_SIZE)
2393		pagezero(CADDR2);
2394	else
2395		bzero((char *)CADDR2 + off, size);
2396	*CMAP2 = 0;
2397	sched_unpin();
2398	mtx_unlock(&CMAPCADDR12_lock);
2399}
2400
2401/*
2402 *	pmap_zero_page_idle zeros the specified hardware page by mapping
2403 *	the page into KVM and using bzero to clear its contents.  This
2404 *	is intended to be called from the vm_pagezero process only and
2405 *	outside of Giant.
2406 */
2407void
2408pmap_zero_page_idle(vm_page_t m)
2409{
2410
2411	if (*CMAP3)
2412		panic("pmap_zero_page: CMAP3 busy");
2413	sched_pin();
2414	*CMAP3 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M;
2415	invlcaddr(CADDR3);
2416	pagezero(CADDR3);
2417	*CMAP3 = 0;
2418	sched_unpin();
2419}
2420
2421/*
2422 *	pmap_copy_page copies the specified (machine independent)
2423 *	page by mapping the page into virtual memory and using
2424 *	bcopy to copy the page, one machine dependent page at a
2425 *	time.
2426 */
2427void
2428pmap_copy_page(vm_page_t src, vm_page_t dst)
2429{
2430
2431	mtx_lock(&CMAPCADDR12_lock);
2432	if (*CMAP1)
2433		panic("pmap_copy_page: CMAP1 busy");
2434	if (*CMAP2)
2435		panic("pmap_copy_page: CMAP2 busy");
2436	sched_pin();
2437#ifdef I386_CPU
2438	invltlb();
2439#else
2440	invlpg((u_int)CADDR1);
2441	invlpg((u_int)CADDR2);
2442#endif
2443	*CMAP1 = PG_V | VM_PAGE_TO_PHYS(src) | PG_A;
2444	*CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(dst) | PG_A | PG_M;
2445	bcopy(CADDR1, CADDR2, PAGE_SIZE);
2446	*CMAP1 = 0;
2447	*CMAP2 = 0;
2448	sched_unpin();
2449	mtx_unlock(&CMAPCADDR12_lock);
2450}
2451
2452/*
2453 * Returns true if the pmap's pv is one of the first
2454 * 16 pvs linked to from this page.  This count may
2455 * be changed upwards or downwards in the future; it
2456 * is only necessary that true be returned for a small
2457 * subset of pmaps for proper page aging.
2458 */
2459boolean_t
2460pmap_page_exists_quick(pmap, m)
2461	pmap_t pmap;
2462	vm_page_t m;
2463{
2464	pv_entry_t pv;
2465	int loops = 0;
2466
2467	if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
2468		return FALSE;
2469
2470	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2471	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2472		if (pv->pv_pmap == pmap) {
2473			return TRUE;
2474		}
2475		loops++;
2476		if (loops >= 16)
2477			break;
2478	}
2479	return (FALSE);
2480}
2481
2482#define PMAP_REMOVE_PAGES_CURPROC_ONLY
2483/*
2484 * Remove all pages from specified address space
2485 * this aids process exit speeds.  Also, this code
2486 * is special cased for current process only, but
2487 * can have the more generic (and slightly slower)
2488 * mode enabled.  This is much faster than pmap_remove
2489 * in the case of running down an entire address space.
2490 */
2491void
2492pmap_remove_pages(pmap, sva, eva)
2493	pmap_t pmap;
2494	vm_offset_t sva, eva;
2495{
2496	pt_entry_t *pte, tpte;
2497	vm_page_t m;
2498	pv_entry_t pv, npv;
2499
2500#ifdef PMAP_REMOVE_PAGES_CURPROC_ONLY
2501	if (!curthread || (pmap != vmspace_pmap(curthread->td_proc->p_vmspace))) {
2502		printf("warning: pmap_remove_pages called with non-current pmap\n");
2503		return;
2504	}
2505#endif
2506	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2507	sched_pin();
2508	for (pv = TAILQ_FIRST(&pmap->pm_pvlist); pv; pv = npv) {
2509
2510		if (pv->pv_va >= eva || pv->pv_va < sva) {
2511			npv = TAILQ_NEXT(pv, pv_plist);
2512			continue;
2513		}
2514
2515#ifdef PMAP_REMOVE_PAGES_CURPROC_ONLY
2516		pte = vtopte(pv->pv_va);
2517#else
2518		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
2519#endif
2520		tpte = *pte;
2521
2522		if (tpte == 0) {
2523			printf("TPTE at %p  IS ZERO @ VA %08x\n",
2524							pte, pv->pv_va);
2525			panic("bad pte");
2526		}
2527
2528/*
2529 * We cannot remove wired pages from a process' mapping at this time
2530 */
2531		if (tpte & PG_W) {
2532			npv = TAILQ_NEXT(pv, pv_plist);
2533			continue;
2534		}
2535
2536		m = PHYS_TO_VM_PAGE(tpte);
2537		KASSERT(m->phys_addr == (tpte & PG_FRAME),
2538		    ("vm_page_t %p phys_addr mismatch %016jx %016jx",
2539		    m, (uintmax_t)m->phys_addr, (uintmax_t)tpte));
2540
2541		KASSERT(m < &vm_page_array[vm_page_array_size],
2542			("pmap_remove_pages: bad tpte %#jx", (uintmax_t)tpte));
2543
2544		pv->pv_pmap->pm_stats.resident_count--;
2545
2546		pte_clear(pte);
2547
2548		/*
2549		 * Update the vm_page_t clean and reference bits.
2550		 */
2551		if (tpte & PG_M) {
2552			vm_page_dirty(m);
2553		}
2554
2555		npv = TAILQ_NEXT(pv, pv_plist);
2556		TAILQ_REMOVE(&pv->pv_pmap->pm_pvlist, pv, pv_plist);
2557
2558		m->md.pv_list_count--;
2559		TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2560		if (TAILQ_FIRST(&m->md.pv_list) == NULL) {
2561			vm_page_flag_clear(m, PG_WRITEABLE);
2562		}
2563
2564		pmap_unuse_pt(pv->pv_pmap, pv->pv_va, pv->pv_ptem);
2565		free_pv_entry(pv);
2566	}
2567	sched_unpin();
2568	pmap_invalidate_all(pmap);
2569}
2570
2571/*
2572 *	pmap_is_modified:
2573 *
2574 *	Return whether or not the specified physical page was modified
2575 *	in any physical maps.
2576 */
2577boolean_t
2578pmap_is_modified(vm_page_t m)
2579{
2580	pv_entry_t pv;
2581	pt_entry_t *pte;
2582
2583	if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
2584		return FALSE;
2585
2586	sched_pin();
2587	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2588	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2589		/*
2590		 * if the bit being tested is the modified bit, then
2591		 * mark clean_map and ptes as never
2592		 * modified.
2593		 */
2594		if (!pmap_track_modified(pv->pv_va))
2595			continue;
2596#if defined(PMAP_DIAGNOSTIC)
2597		if (!pv->pv_pmap) {
2598			printf("Null pmap (tb) at va: 0x%x\n", pv->pv_va);
2599			continue;
2600		}
2601#endif
2602		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
2603		if (*pte & PG_M) {
2604			sched_unpin();
2605			return TRUE;
2606		}
2607	}
2608	sched_unpin();
2609	return (FALSE);
2610}
2611
2612/*
2613 *	pmap_is_prefaultable:
2614 *
2615 *	Return whether or not the specified virtual address is elgible
2616 *	for prefault.
2617 */
2618boolean_t
2619pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
2620{
2621	pt_entry_t *pte;
2622
2623	if ((*pmap_pde(pmap, addr)) == 0)
2624		return (FALSE);
2625	pte = vtopte(addr);
2626	if (*pte)
2627		return (FALSE);
2628	return (TRUE);
2629}
2630
2631/*
2632 *	Clear the given bit in each of the given page's ptes.
2633 */
2634static __inline void
2635pmap_clear_ptes(vm_page_t m, int bit)
2636{
2637	register pv_entry_t pv;
2638	pt_entry_t pbits, *pte;
2639
2640	if (!pmap_initialized || (m->flags & PG_FICTITIOUS) ||
2641	    (bit == PG_RW && (m->flags & PG_WRITEABLE) == 0))
2642		return;
2643
2644	sched_pin();
2645	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2646	/*
2647	 * Loop over all current mappings setting/clearing as appropos If
2648	 * setting RO do we need to clear the VAC?
2649	 */
2650	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2651		/*
2652		 * don't write protect pager mappings
2653		 */
2654		if (bit == PG_RW) {
2655			if (!pmap_track_modified(pv->pv_va))
2656				continue;
2657		}
2658
2659#if defined(PMAP_DIAGNOSTIC)
2660		if (!pv->pv_pmap) {
2661			printf("Null pmap (cb) at va: 0x%x\n", pv->pv_va);
2662			continue;
2663		}
2664#endif
2665
2666		pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
2667		pbits = *pte;
2668		if (pbits & bit) {
2669			if (bit == PG_RW) {
2670				if (pbits & PG_M) {
2671					vm_page_dirty(m);
2672				}
2673				pte_store(pte, pbits & ~(PG_M|PG_RW));
2674			} else {
2675				pte_store(pte, pbits & ~bit);
2676			}
2677			pmap_invalidate_page(pv->pv_pmap, pv->pv_va);
2678		}
2679	}
2680	if (bit == PG_RW)
2681		vm_page_flag_clear(m, PG_WRITEABLE);
2682	sched_unpin();
2683}
2684
2685/*
2686 *      pmap_page_protect:
2687 *
2688 *      Lower the permission for all mappings to a given page.
2689 */
2690void
2691pmap_page_protect(vm_page_t m, vm_prot_t prot)
2692{
2693	if ((prot & VM_PROT_WRITE) == 0) {
2694		if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
2695			pmap_clear_ptes(m, PG_RW);
2696		} else {
2697			pmap_remove_all(m);
2698		}
2699	}
2700}
2701
2702/*
2703 *	pmap_ts_referenced:
2704 *
2705 *	Return a count of reference bits for a page, clearing those bits.
2706 *	It is not necessary for every reference bit to be cleared, but it
2707 *	is necessary that 0 only be returned when there are truly no
2708 *	reference bits set.
2709 *
2710 *	XXX: The exact number of bits to check and clear is a matter that
2711 *	should be tested and standardized at some point in the future for
2712 *	optimal aging of shared pages.
2713 */
2714int
2715pmap_ts_referenced(vm_page_t m)
2716{
2717	register pv_entry_t pv, pvf, pvn;
2718	pt_entry_t *pte;
2719	pt_entry_t v;
2720	int rtval = 0;
2721
2722	if (!pmap_initialized || (m->flags & PG_FICTITIOUS))
2723		return (rtval);
2724
2725	sched_pin();
2726	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2727	if ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
2728
2729		pvf = pv;
2730
2731		do {
2732			pvn = TAILQ_NEXT(pv, pv_list);
2733
2734			TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2735
2736			TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
2737
2738			if (!pmap_track_modified(pv->pv_va))
2739				continue;
2740
2741			pte = pmap_pte_quick(pv->pv_pmap, pv->pv_va);
2742
2743			if (pte && ((v = pte_load(pte)) & PG_A) != 0) {
2744				atomic_clear_int((u_int *)pte, PG_A);
2745				pmap_invalidate_page(pv->pv_pmap, pv->pv_va);
2746
2747				rtval++;
2748				if (rtval > 4) {
2749					break;
2750				}
2751			}
2752		} while ((pv = pvn) != NULL && pv != pvf);
2753	}
2754	sched_unpin();
2755
2756	return (rtval);
2757}
2758
2759/*
2760 *	Clear the modify bits on the specified physical page.
2761 */
2762void
2763pmap_clear_modify(vm_page_t m)
2764{
2765	pmap_clear_ptes(m, PG_M);
2766}
2767
2768/*
2769 *	pmap_clear_reference:
2770 *
2771 *	Clear the reference bit on the specified physical page.
2772 */
2773void
2774pmap_clear_reference(vm_page_t m)
2775{
2776	pmap_clear_ptes(m, PG_A);
2777}
2778
2779/*
2780 * Miscellaneous support routines follow
2781 */
2782
2783/*
2784 * Map a set of physical memory pages into the kernel virtual
2785 * address space. Return a pointer to where it is mapped. This
2786 * routine is intended to be used for mapping device memory,
2787 * NOT real memory.
2788 */
2789void *
2790pmap_mapdev(pa, size)
2791	vm_paddr_t pa;
2792	vm_size_t size;
2793{
2794	vm_offset_t va, tmpva, offset;
2795
2796	offset = pa & PAGE_MASK;
2797	size = roundup(offset + size, PAGE_SIZE);
2798	pa = pa & PG_FRAME;
2799
2800	if (pa < KERNLOAD && pa + size <= KERNLOAD)
2801		va = KERNBASE + pa;
2802	else
2803		va = kmem_alloc_nofault(kernel_map, size);
2804	if (!va)
2805		panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
2806
2807	for (tmpva = va; size > 0; ) {
2808		pmap_kenter(tmpva, pa);
2809		size -= PAGE_SIZE;
2810		tmpva += PAGE_SIZE;
2811		pa += PAGE_SIZE;
2812	}
2813	pmap_invalidate_range(kernel_pmap, va, tmpva);
2814	return ((void *)(va + offset));
2815}
2816
2817void
2818pmap_unmapdev(va, size)
2819	vm_offset_t va;
2820	vm_size_t size;
2821{
2822	vm_offset_t base, offset, tmpva;
2823
2824	if (va >= KERNBASE && va + size <= KERNBASE + KERNLOAD)
2825		return;
2826	base = va & PG_FRAME;
2827	offset = va & PAGE_MASK;
2828	size = roundup(offset + size, PAGE_SIZE);
2829	for (tmpva = base; tmpva < (base + size); tmpva += PAGE_SIZE)
2830		pmap_kremove(tmpva);
2831	pmap_invalidate_range(kernel_pmap, va, tmpva);
2832	kmem_free(kernel_map, base, size);
2833}
2834
2835/*
2836 * perform the pmap work for mincore
2837 */
2838int
2839pmap_mincore(pmap, addr)
2840	pmap_t pmap;
2841	vm_offset_t addr;
2842{
2843	pt_entry_t *ptep, pte;
2844	vm_page_t m;
2845	int val = 0;
2846
2847	ptep = pmap_pte(pmap, addr);
2848	if (ptep == 0) {
2849		return 0;
2850	}
2851
2852	if ((pte = *ptep) != 0) {
2853		vm_paddr_t pa;
2854
2855		val = MINCORE_INCORE;
2856		if ((pte & PG_MANAGED) == 0)
2857			return val;
2858
2859		pa = pte & PG_FRAME;
2860
2861		m = PHYS_TO_VM_PAGE(pa);
2862
2863		/*
2864		 * Modified by us
2865		 */
2866		if (pte & PG_M)
2867			val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
2868		else {
2869			/*
2870			 * Modified by someone else
2871			 */
2872			vm_page_lock_queues();
2873			if (m->dirty || pmap_is_modified(m))
2874				val |= MINCORE_MODIFIED_OTHER;
2875			vm_page_unlock_queues();
2876		}
2877		/*
2878		 * Referenced by us
2879		 */
2880		if (pte & PG_A)
2881			val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
2882		else {
2883			/*
2884			 * Referenced by someone else
2885			 */
2886			vm_page_lock_queues();
2887			if ((m->flags & PG_REFERENCED) ||
2888			    pmap_ts_referenced(m)) {
2889				val |= MINCORE_REFERENCED_OTHER;
2890				vm_page_flag_set(m, PG_REFERENCED);
2891			}
2892			vm_page_unlock_queues();
2893		}
2894	}
2895	return val;
2896}
2897
2898void
2899pmap_activate(struct thread *td)
2900{
2901	struct proc *p = td->td_proc;
2902	pmap_t	pmap, oldpmap;
2903	u_int32_t  cr3;
2904
2905	critical_enter();
2906	pmap = vmspace_pmap(td->td_proc->p_vmspace);
2907	oldpmap = PCPU_GET(curpmap);
2908#if defined(SMP)
2909	atomic_clear_int(&oldpmap->pm_active, PCPU_GET(cpumask));
2910	atomic_set_int(&pmap->pm_active, PCPU_GET(cpumask));
2911#else
2912	oldpmap->pm_active &= ~1;
2913	pmap->pm_active |= 1;
2914#endif
2915#ifdef PAE
2916	cr3 = vtophys(pmap->pm_pdpt);
2917#else
2918	cr3 = vtophys(pmap->pm_pdir);
2919#endif
2920	/* XXXKSE this is wrong.
2921	 * pmap_activate is for the current thread on the current cpu
2922	 */
2923	if (p->p_flag & P_SA) {
2924		/* Make sure all other cr3 entries are updated. */
2925		/* what if they are running?  XXXKSE (maybe abort them) */
2926		FOREACH_THREAD_IN_PROC(p, td) {
2927			td->td_pcb->pcb_cr3 = cr3;
2928		}
2929	} else {
2930		td->td_pcb->pcb_cr3 = cr3;
2931	}
2932	load_cr3(cr3);
2933	PCPU_SET(curpmap, pmap);
2934	critical_exit();
2935}
2936
2937vm_offset_t
2938pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
2939{
2940
2941	if ((obj == NULL) || (size < NBPDR) || (obj->type != OBJT_DEVICE)) {
2942		return addr;
2943	}
2944
2945	addr = (addr + PDRMASK) & ~PDRMASK;
2946	return addr;
2947}
2948
2949
2950#if defined(PMAP_DEBUG)
2951pmap_pid_dump(int pid)
2952{
2953	pmap_t pmap;
2954	struct proc *p;
2955	int npte = 0;
2956	int index;
2957
2958	sx_slock(&allproc_lock);
2959	LIST_FOREACH(p, &allproc, p_list) {
2960		if (p->p_pid != pid)
2961			continue;
2962
2963		if (p->p_vmspace) {
2964			int i,j;
2965			index = 0;
2966			pmap = vmspace_pmap(p->p_vmspace);
2967			for (i = 0; i < NPDEPTD; i++) {
2968				pd_entry_t *pde;
2969				pt_entry_t *pte;
2970				vm_offset_t base = i << PDRSHIFT;
2971
2972				pde = &pmap->pm_pdir[i];
2973				if (pde && pmap_pde_v(pde)) {
2974					for (j = 0; j < NPTEPG; j++) {
2975						vm_offset_t va = base + (j << PAGE_SHIFT);
2976						if (va >= (vm_offset_t) VM_MIN_KERNEL_ADDRESS) {
2977							if (index) {
2978								index = 0;
2979								printf("\n");
2980							}
2981							sx_sunlock(&allproc_lock);
2982							return npte;
2983						}
2984						pte = pmap_pte(pmap, va);
2985						if (pte && pmap_pte_v(pte)) {
2986							pt_entry_t pa;
2987							vm_page_t m;
2988							pa = *pte;
2989							m = PHYS_TO_VM_PAGE(pa);
2990							printf("va: 0x%x, pt: 0x%x, h: %d, w: %d, f: 0x%x",
2991								va, pa, m->hold_count, m->wire_count, m->flags);
2992							npte++;
2993							index++;
2994							if (index >= 2) {
2995								index = 0;
2996								printf("\n");
2997							} else {
2998								printf(" ");
2999							}
3000						}
3001					}
3002				}
3003			}
3004		}
3005	}
3006	sx_sunlock(&allproc_lock);
3007	return npte;
3008}
3009#endif
3010
3011#if defined(DEBUG)
3012
3013static void	pads(pmap_t pm);
3014void		pmap_pvdump(vm_offset_t pa);
3015
3016/* print address space of pmap*/
3017static void
3018pads(pm)
3019	pmap_t pm;
3020{
3021	int i, j;
3022	vm_paddr_t va;
3023	pt_entry_t *ptep;
3024
3025	if (pm == kernel_pmap)
3026		return;
3027	for (i = 0; i < NPDEPTD; i++)
3028		if (pm->pm_pdir[i])
3029			for (j = 0; j < NPTEPG; j++) {
3030				va = (i << PDRSHIFT) + (j << PAGE_SHIFT);
3031				if (pm == kernel_pmap && va < KERNBASE)
3032					continue;
3033				if (pm != kernel_pmap && va > UPT_MAX_ADDRESS)
3034					continue;
3035				ptep = pmap_pte(pm, va);
3036				if (pmap_pte_v(ptep))
3037					printf("%x:%x ", va, *ptep);
3038			};
3039
3040}
3041
3042void
3043pmap_pvdump(pa)
3044	vm_paddr_t pa;
3045{
3046	pv_entry_t pv;
3047	vm_page_t m;
3048
3049	printf("pa %x", pa);
3050	m = PHYS_TO_VM_PAGE(pa);
3051	TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3052		printf(" -> pmap %p, va %x", (void *)pv->pv_pmap, pv->pv_va);
3053		pads(pv->pv_pmap);
3054	}
3055	printf(" ");
3056}
3057#endif
3058