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