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