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