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