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