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