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