2 * Copyright (c) 1991 Regents of the University of California.
4 * Copyright (c) 1994 John S. Dyson
6 * Copyright (c) 1994 David Greenman
8 * Copyright (c) 2005 Alan L. Cox <alc@cs.rice.edu>
11 * This code is derived from software contributed to Berkeley by
12 * the Systems Programming Group of the University of Utah Computer
13 * Science Department and William Jolitz of UUNET Technologies Inc.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
23 * 3. All advertising materials mentioning features or use of this software
24 * must display the following acknowledgement:
25 * This product includes software developed by the University of
26 * California, Berkeley and its contributors.
27 * 4. Neither the name of the University nor the names of its contributors
28 * may be used to endorse or promote products derived from this software
29 * without specific prior written permission.
31 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
32 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
35 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
37 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
39 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
40 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
43 * from: @(#)pmap.c 7.7 (Berkeley) 5/12/91
46 * Copyright (c) 2003 Networks Associates Technology, Inc.
47 * All rights reserved.
49 * This software was developed for the FreeBSD Project by Jake Burkholder,
50 * Safeport Network Services, and Network Associates Laboratories, the
51 * Security Research Division of Network Associates, Inc. under
52 * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
53 * CHATS research program.
55 * Redistribution and use in source and binary forms, with or without
56 * modification, are permitted provided that the following conditions
58 * 1. Redistributions of source code must retain the above copyright
59 * notice, this list of conditions and the following disclaimer.
60 * 2. Redistributions in binary form must reproduce the above copyright
61 * notice, this list of conditions and the following disclaimer in the
62 * documentation and/or other materials provided with the distribution.
64 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
65 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
66 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
67 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
68 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
69 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
70 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
71 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
72 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
73 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
77 #include <sys/cdefs.h>
78 __FBSDID("$FreeBSD$");
81 * Manages physical address maps.
83 * In addition to hardware address maps, this
84 * module is called upon to provide software-use-only
85 * maps which may or may not be stored in the same
86 * form as hardware maps. These pseudo-maps are
87 * used to store intermediate results from copy
88 * operations to and from address spaces.
90 * Since the information managed by this module is
91 * also stored by the logical address mapping module,
92 * this module may throw away valid virtual-to-physical
93 * mappings at almost any time. However, invalidations
94 * of virtual-to-physical mappings must be done as
97 * In order to cope with hardware architectures which
98 * make virtual-to-physical map invalidates expensive,
99 * this module may delay invalidate or reduced protection
100 * operations until such time as they are actually
101 * necessary. This module is given full information as
102 * to which processors are currently using which maps,
103 * and to when physical maps must be made correct.
107 #include "opt_pmap.h"
108 #include "opt_msgbuf.h"
110 #include "opt_xbox.h"
112 #include <sys/param.h>
113 #include <sys/systm.h>
114 #include <sys/kernel.h>
115 #include <sys/lock.h>
116 #include <sys/malloc.h>
117 #include <sys/mman.h>
118 #include <sys/msgbuf.h>
119 #include <sys/mutex.h>
120 #include <sys/proc.h>
122 #include <sys/vmmeter.h>
123 #include <sys/sched.h>
124 #include <sys/sysctl.h>
130 #include <vm/vm_param.h>
131 #include <vm/vm_kern.h>
132 #include <vm/vm_page.h>
133 #include <vm/vm_map.h>
134 #include <vm/vm_object.h>
135 #include <vm/vm_extern.h>
136 #include <vm/vm_pageout.h>
137 #include <vm/vm_pager.h>
140 #include <machine/cpu.h>
141 #include <machine/cputypes.h>
142 #include <machine/md_var.h>
143 #include <machine/pcb.h>
144 #include <machine/specialreg.h>
146 #include <machine/smp.h>
150 #include <machine/xbox.h>
153 #if !defined(CPU_DISABLE_SSE) && defined(I686_CPU)
154 #define CPU_ENABLE_SSE
157 #ifndef PMAP_SHPGPERPROC
158 #define PMAP_SHPGPERPROC 200
161 #if defined(DIAGNOSTIC)
162 #define PMAP_DIAGNOSTIC
165 #if !defined(PMAP_DIAGNOSTIC)
166 #define PMAP_INLINE __inline
173 #define PV_STAT(x) do { x ; } while (0)
175 #define PV_STAT(x) do { } while (0)
179 * Get PDEs and PTEs for user/kernel address space
181 #define pmap_pde(m, v) (&((m)->pm_pdir[(vm_offset_t)(v) >> PDRSHIFT]))
182 #define pdir_pde(m, v) (m[(vm_offset_t)(v) >> PDRSHIFT])
184 #define pmap_pde_v(pte) ((*(int *)pte & PG_V) != 0)
185 #define pmap_pte_w(pte) ((*(int *)pte & PG_W) != 0)
186 #define pmap_pte_m(pte) ((*(int *)pte & PG_M) != 0)
187 #define pmap_pte_u(pte) ((*(int *)pte & PG_A) != 0)
188 #define pmap_pte_v(pte) ((*(int *)pte & PG_V) != 0)
190 #define pmap_pte_set_w(pte, v) ((v) ? atomic_set_int((u_int *)(pte), PG_W) : \
191 atomic_clear_int((u_int *)(pte), PG_W))
192 #define pmap_pte_set_prot(pte, v) ((*(int *)pte &= ~PG_PROT), (*(int *)pte |= (v)))
194 struct pmap kernel_pmap_store;
195 LIST_HEAD(pmaplist, pmap);
196 static struct pmaplist allpmaps;
197 static struct mtx allpmaps_lock;
199 vm_paddr_t avail_end; /* PA of last available physical page */
200 vm_offset_t virtual_avail; /* VA of first avail page (after kernel bss) */
201 vm_offset_t virtual_end; /* VA of last avail page (end of kernel AS) */
202 int pgeflag = 0; /* PG_G or-in */
203 int pseflag = 0; /* PG_PS or-in */
206 vm_offset_t kernel_vm_end;
207 extern u_int32_t KERNend;
210 static uma_zone_t pdptzone;
214 * Data for the pv entry allocation mechanism
216 static int pv_entry_count = 0, pv_entry_max = 0, pv_entry_high_water = 0;
217 static int shpgperproc = PMAP_SHPGPERPROC;
219 struct pv_chunk *pv_chunkbase; /* KVA block for pv_chunks */
220 int pv_maxchunks; /* How many chunks we have KVA for */
221 vm_offset_t pv_vafree; /* freelist stored in the PTE */
224 * All those kernel PT submaps that BSD is so fond of
233 static struct sysmaps sysmaps_pcpu[MAXCPU];
234 pt_entry_t *CMAP1 = 0;
235 static pt_entry_t *CMAP3;
236 caddr_t CADDR1 = 0, ptvmmap = 0;
237 static caddr_t CADDR3;
238 struct msgbuf *msgbufp = 0;
243 static caddr_t crashdumpmap;
246 extern pt_entry_t *SMPpt;
248 static pt_entry_t *PMAP1 = 0, *PMAP2;
249 static pt_entry_t *PADDR1 = 0, *PADDR2;
252 static int PMAP1changedcpu;
253 SYSCTL_INT(_debug, OID_AUTO, PMAP1changedcpu, CTLFLAG_RD,
255 "Number of times pmap_pte_quick changed CPU with same PMAP1");
257 static int PMAP1changed;
258 SYSCTL_INT(_debug, OID_AUTO, PMAP1changed, CTLFLAG_RD,
260 "Number of times pmap_pte_quick changed PMAP1");
261 static int PMAP1unchanged;
262 SYSCTL_INT(_debug, OID_AUTO, PMAP1unchanged, CTLFLAG_RD,
264 "Number of times pmap_pte_quick didn't change PMAP1");
265 static struct mtx PMAP2mutex;
267 static void free_pv_entry(pmap_t pmap, pv_entry_t pv);
268 static pv_entry_t get_pv_entry(pmap_t locked_pmap, int try);
269 static void pmap_clear_ptes(vm_page_t m, int bit);
271 static vm_page_t pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va,
272 vm_page_t m, vm_prot_t prot, vm_page_t mpte);
273 static int pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t sva);
274 static void pmap_remove_page(struct pmap *pmap, vm_offset_t va);
275 static void pmap_remove_entry(struct pmap *pmap, vm_page_t m,
277 static void pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t m);
278 static boolean_t pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va,
281 static vm_page_t pmap_allocpte(pmap_t pmap, vm_offset_t va, int flags);
283 static vm_page_t _pmap_allocpte(pmap_t pmap, unsigned ptepindex, int flags);
284 static int _pmap_unwire_pte_hold(pmap_t pmap, vm_page_t m);
285 static pt_entry_t *pmap_pte_quick(pmap_t pmap, vm_offset_t va);
286 static void pmap_pte_release(pt_entry_t *pte);
287 static int pmap_unuse_pt(pmap_t, vm_offset_t);
288 static vm_offset_t pmap_kmem_choose(vm_offset_t addr);
290 static void *pmap_pdpt_allocf(uma_zone_t zone, int bytes, u_int8_t *flags, int wait);
293 CTASSERT(1 << PDESHIFT == sizeof(pd_entry_t));
294 CTASSERT(1 << PTESHIFT == sizeof(pt_entry_t));
297 * Move the kernel virtual free pointer to the next
298 * 4MB. This is used to help improve performance
299 * by using a large (4MB) page for much of the kernel
300 * (.text, .data, .bss)
303 pmap_kmem_choose(vm_offset_t addr)
305 vm_offset_t newaddr = addr;
308 if (cpu_feature & CPUID_PSE)
309 newaddr = (addr + PDRMASK) & ~PDRMASK;
315 * Bootstrap the system enough to run with virtual memory.
317 * On the i386 this is called after mapping has already been enabled
318 * and just syncs the pmap module with what has already been done.
319 * [We can't call it easily with mapping off since the kernel is not
320 * mapped with PA == VA, hence we would have to relocate every address
321 * from the linked base (virtual) address "KERNBASE" to the actual
322 * (physical) address starting relative to 0]
325 pmap_bootstrap(firstaddr, loadaddr)
326 vm_paddr_t firstaddr;
330 pt_entry_t *pte, *unused;
331 struct sysmaps *sysmaps;
335 * XXX The calculation of virtual_avail is wrong. It's NKPT*PAGE_SIZE too
336 * large. It should instead be correctly calculated in locore.s and
337 * not based on 'first' (which is a physical address, not a virtual
338 * address, for the start of unused physical memory). The kernel
339 * page tables are NOT double mapped and thus should not be included
340 * in this calculation.
342 virtual_avail = (vm_offset_t) KERNBASE + firstaddr;
343 virtual_avail = pmap_kmem_choose(virtual_avail);
345 virtual_end = VM_MAX_KERNEL_ADDRESS;
348 * Initialize the kernel pmap (which is statically allocated).
350 PMAP_LOCK_INIT(kernel_pmap);
351 kernel_pmap->pm_pdir = (pd_entry_t *) (KERNBASE + (u_int)IdlePTD);
353 kernel_pmap->pm_pdpt = (pdpt_entry_t *) (KERNBASE + (u_int)IdlePDPT);
355 kernel_pmap->pm_active = -1; /* don't allow deactivation */
356 TAILQ_INIT(&kernel_pmap->pm_pvchunk);
357 LIST_INIT(&allpmaps);
358 mtx_init(&allpmaps_lock, "allpmaps", NULL, MTX_SPIN);
359 mtx_lock_spin(&allpmaps_lock);
360 LIST_INSERT_HEAD(&allpmaps, kernel_pmap, pm_list);
361 mtx_unlock_spin(&allpmaps_lock);
365 * Reserve some special page table entries/VA space for temporary
368 #define SYSMAP(c, p, v, n) \
369 v = (c)va; va += ((n)*PAGE_SIZE); p = pte; pte += (n);
375 * CMAP1/CMAP2 are used for zeroing and copying pages.
376 * CMAP3 is used for the idle process page zeroing.
378 for (i = 0; i < MAXCPU; i++) {
379 sysmaps = &sysmaps_pcpu[i];
380 mtx_init(&sysmaps->lock, "SYSMAPS", NULL, MTX_DEF);
381 SYSMAP(caddr_t, sysmaps->CMAP1, sysmaps->CADDR1, 1)
382 SYSMAP(caddr_t, sysmaps->CMAP2, sysmaps->CADDR2, 1)
384 SYSMAP(caddr_t, CMAP1, CADDR1, 1)
385 SYSMAP(caddr_t, CMAP3, CADDR3, 1)
391 SYSMAP(caddr_t, unused, crashdumpmap, MAXDUMPPGS)
394 * ptvmmap is used for reading arbitrary physical pages via /dev/mem.
396 SYSMAP(caddr_t, unused, ptvmmap, 1)
399 * msgbufp is used to map the system message buffer.
401 SYSMAP(struct msgbuf *, unused, msgbufp, atop(round_page(MSGBUF_SIZE)))
404 * ptemap is used for pmap_pte_quick
406 SYSMAP(pt_entry_t *, PMAP1, PADDR1, 1);
407 SYSMAP(pt_entry_t *, PMAP2, PADDR2, 1);
409 mtx_init(&PMAP2mutex, "PMAP2", NULL, MTX_DEF);
416 /* FIXME: This is gross, but needed for the XBOX. Since we are in such
417 * an early stadium, we cannot yet neatly map video memory ... :-(
418 * Better fixes are very welcome! */
419 if (!arch_i386_is_xbox)
421 for (i = 0; i < NKPT; i++)
424 /* Initialize the PAT MSR if present. */
427 /* Turn on PG_G on kernel page(s) */
439 /* Bail if this CPU doesn't implement PAT. */
440 if (!(cpu_feature & CPUID_PAT))
445 * Leave the indices 0-3 at the default of WB, WT, UC, and UC-.
446 * Program 4 and 5 as WP and WC.
447 * Leave 6 and 7 as UC and UC-.
449 pat_msr = rdmsr(MSR_PAT);
450 pat_msr &= ~(PAT_MASK(4) | PAT_MASK(5));
451 pat_msr |= PAT_VALUE(4, PAT_WRITE_PROTECTED) |
452 PAT_VALUE(5, PAT_WRITE_COMBINING);
455 * Due to some Intel errata, we can only safely use the lower 4
456 * PAT entries. Thus, just replace PAT Index 2 with WC instead
459 * Intel Pentium III Processor Specification Update
460 * Errata E.27 (Upper Four PAT Entries Not Usable With Mode B
463 * Intel Pentium IV Processor Specification Update
464 * Errata N46 (PAT Index MSB May Be Calculated Incorrectly)
466 pat_msr = rdmsr(MSR_PAT);
467 pat_msr &= ~PAT_MASK(2);
468 pat_msr |= PAT_VALUE(2, PAT_WRITE_COMBINING);
470 wrmsr(MSR_PAT, pat_msr);
474 * Set PG_G on kernel pages. Only the BSP calls this when SMP is turned on.
481 vm_offset_t va, endva;
488 endva = KERNBASE + KERNend;
491 va = KERNBASE + KERNLOAD;
493 pdir = kernel_pmap->pm_pdir[KPTDI+i];
495 kernel_pmap->pm_pdir[KPTDI+i] = PTD[KPTDI+i] = pdir;
496 invltlb(); /* Play it safe, invltlb() every time */
501 va = (vm_offset_t)btext;
506 invltlb(); /* Play it safe, invltlb() every time */
513 * Initialize a vm_page's machine-dependent fields.
516 pmap_page_init(vm_page_t m)
519 TAILQ_INIT(&m->md.pv_list);
520 m->md.pv_list_count = 0;
525 static MALLOC_DEFINE(M_PMAPPDPT, "pmap", "pmap pdpt");
528 pmap_pdpt_allocf(uma_zone_t zone, int bytes, u_int8_t *flags, int wait)
530 *flags = UMA_SLAB_PRIV;
531 return (contigmalloc(PAGE_SIZE, M_PMAPPDPT, 0, 0x0ULL, 0xffffffffULL,
537 * ABuse the pte nodes for unmapped kva to thread a kva freelist through.
539 * - Must deal with pages in order to ensure that none of the PG_* bits
540 * are ever set, PG_V in particular.
541 * - Assumes we can write to ptes without pte_store() atomic ops, even
542 * on PAE systems. This should be ok.
543 * - Assumes nothing will ever test these addresses for 0 to indicate
544 * no mapping instead of correctly checking PG_V.
545 * - Assumes a vm_offset_t will fit in a pte (true for i386).
546 * Because PG_V is never set, there can be no mappings to invalidate.
549 pmap_ptelist_alloc(vm_offset_t *head)
556 return (va); /* Out of memory */
560 panic("pmap_ptelist_alloc: va with PG_V set!");
566 pmap_ptelist_free(vm_offset_t *head, vm_offset_t va)
571 panic("pmap_ptelist_free: freeing va with PG_V set!");
573 *pte = *head; /* virtual! PG_V is 0 though */
578 pmap_ptelist_init(vm_offset_t *head, void *base, int npages)
584 for (i = npages - 1; i >= 0; i--) {
585 va = (vm_offset_t)base + i * PAGE_SIZE;
586 pmap_ptelist_free(head, va);
592 * Initialize the pmap module.
593 * Called by vm_init, to initialize any structures that the pmap
594 * system needs to map virtual memory.
601 * Initialize the address space (zone) for the pv entries. Set a
602 * high water mark so that the system can recover from excessive
603 * numbers of pv entries.
605 TUNABLE_INT_FETCH("vm.pmap.shpgperproc", &shpgperproc);
606 pv_entry_max = shpgperproc * maxproc + cnt.v_page_count;
607 TUNABLE_INT_FETCH("vm.pmap.pv_entries", &pv_entry_max);
608 pv_entry_max = roundup(pv_entry_max, _NPCPV);
609 pv_entry_high_water = 9 * (pv_entry_max / 10);
611 pv_maxchunks = pv_entry_max / _NPCPV;
612 pv_chunkbase = (struct pv_chunk *)kmem_alloc_nofault(kernel_map,
613 PAGE_SIZE * pv_maxchunks);
614 if (pv_chunkbase == NULL)
615 panic("pmap_init: not enough kvm for pv chunks");
616 pmap_ptelist_init(&pv_vafree, pv_chunkbase, pv_maxchunks);
618 pdptzone = uma_zcreate("PDPT", NPGPTD * sizeof(pdpt_entry_t), NULL,
619 NULL, NULL, NULL, (NPGPTD * sizeof(pdpt_entry_t)) - 1,
620 UMA_ZONE_VM | UMA_ZONE_NOFREE);
621 uma_zone_set_allocf(pdptzone, pmap_pdpt_allocf);
626 SYSCTL_NODE(_vm, OID_AUTO, pmap, CTLFLAG_RD, 0, "VM/pmap parameters");
627 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_max, CTLFLAG_RD, &pv_entry_max, 0,
628 "Max number of PV entries");
629 SYSCTL_INT(_vm_pmap, OID_AUTO, shpgperproc, CTLFLAG_RD, &shpgperproc, 0,
630 "Page share factor per proc");
632 /***************************************************
633 * Low level helper routines.....
634 ***************************************************/
638 * For SMP, these functions have to use the IPI mechanism for coherence.
641 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
647 if (!(read_eflags() & PSL_I))
648 panic("%s: interrupts disabled", __func__);
649 mtx_lock_spin(&smp_ipi_mtx);
653 * We need to disable interrupt preemption but MUST NOT have
654 * interrupts disabled here.
655 * XXX we may need to hold schedlock to get a coherent pm_active
656 * XXX critical sections disable interrupts again
658 if (pmap == kernel_pmap || pmap->pm_active == all_cpus) {
662 cpumask = PCPU_GET(cpumask);
663 other_cpus = PCPU_GET(other_cpus);
664 if (pmap->pm_active & cpumask)
666 if (pmap->pm_active & other_cpus)
667 smp_masked_invlpg(pmap->pm_active & other_cpus, va);
670 mtx_unlock_spin(&smp_ipi_mtx);
676 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
683 if (!(read_eflags() & PSL_I))
684 panic("%s: interrupts disabled", __func__);
685 mtx_lock_spin(&smp_ipi_mtx);
689 * We need to disable interrupt preemption but MUST NOT have
690 * interrupts disabled here.
691 * XXX we may need to hold schedlock to get a coherent pm_active
692 * XXX critical sections disable interrupts again
694 if (pmap == kernel_pmap || pmap->pm_active == all_cpus) {
695 for (addr = sva; addr < eva; addr += PAGE_SIZE)
697 smp_invlpg_range(sva, eva);
699 cpumask = PCPU_GET(cpumask);
700 other_cpus = PCPU_GET(other_cpus);
701 if (pmap->pm_active & cpumask)
702 for (addr = sva; addr < eva; addr += PAGE_SIZE)
704 if (pmap->pm_active & other_cpus)
705 smp_masked_invlpg_range(pmap->pm_active & other_cpus,
709 mtx_unlock_spin(&smp_ipi_mtx);
715 pmap_invalidate_all(pmap_t pmap)
721 if (!(read_eflags() & PSL_I))
722 panic("%s: interrupts disabled", __func__);
723 mtx_lock_spin(&smp_ipi_mtx);
727 * We need to disable interrupt preemption but MUST NOT have
728 * interrupts disabled here.
729 * XXX we may need to hold schedlock to get a coherent pm_active
730 * XXX critical sections disable interrupts again
732 if (pmap == kernel_pmap || pmap->pm_active == all_cpus) {
736 cpumask = PCPU_GET(cpumask);
737 other_cpus = PCPU_GET(other_cpus);
738 if (pmap->pm_active & cpumask)
740 if (pmap->pm_active & other_cpus)
741 smp_masked_invltlb(pmap->pm_active & other_cpus);
744 mtx_unlock_spin(&smp_ipi_mtx);
750 pmap_invalidate_cache(void)
754 if (!(read_eflags() & PSL_I))
755 panic("%s: interrupts disabled", __func__);
756 mtx_lock_spin(&smp_ipi_mtx);
760 * We need to disable interrupt preemption but MUST NOT have
761 * interrupts disabled here.
762 * XXX we may need to hold schedlock to get a coherent pm_active
763 * XXX critical sections disable interrupts again
768 mtx_unlock_spin(&smp_ipi_mtx);
774 * Normal, non-SMP, 486+ invalidation functions.
775 * We inline these within pmap.c for speed.
778 pmap_invalidate_page(pmap_t pmap, vm_offset_t va)
781 if (pmap == kernel_pmap || pmap->pm_active)
786 pmap_invalidate_range(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
790 if (pmap == kernel_pmap || pmap->pm_active)
791 for (addr = sva; addr < eva; addr += PAGE_SIZE)
796 pmap_invalidate_all(pmap_t pmap)
799 if (pmap == kernel_pmap || pmap->pm_active)
804 pmap_invalidate_cache(void)
812 * Are we current address space or kernel? N.B. We return FALSE when
813 * a pmap's page table is in use because a kernel thread is borrowing
814 * it. The borrowed page table can change spontaneously, making any
815 * dependence on its continued use subject to a race condition.
818 pmap_is_current(pmap_t pmap)
821 return (pmap == kernel_pmap ||
822 (pmap == vmspace_pmap(curthread->td_proc->p_vmspace) &&
823 (pmap->pm_pdir[PTDPTDI] & PG_FRAME) == (PTDpde[0] & PG_FRAME)));
827 * If the given pmap is not the current or kernel pmap, the returned pte must
828 * be released by passing it to pmap_pte_release().
831 pmap_pte(pmap_t pmap, vm_offset_t va)
836 pde = pmap_pde(pmap, va);
840 /* are we current address space or kernel? */
841 if (pmap_is_current(pmap))
843 mtx_lock(&PMAP2mutex);
844 newpf = *pde & PG_FRAME;
845 if ((*PMAP2 & PG_FRAME) != newpf) {
846 *PMAP2 = newpf | PG_RW | PG_V | PG_A | PG_M;
847 pmap_invalidate_page(kernel_pmap, (vm_offset_t)PADDR2);
849 return (PADDR2 + (i386_btop(va) & (NPTEPG - 1)));
855 * Releases a pte that was obtained from pmap_pte(). Be prepared for the pte
859 pmap_pte_release(pt_entry_t *pte)
862 if ((pt_entry_t *)((vm_offset_t)pte & ~PAGE_MASK) == PADDR2)
863 mtx_unlock(&PMAP2mutex);
867 invlcaddr(void *caddr)
870 invlpg((u_int)caddr);
874 * Super fast pmap_pte routine best used when scanning
875 * the pv lists. This eliminates many coarse-grained
876 * invltlb calls. Note that many of the pv list
877 * scans are across different pmaps. It is very wasteful
878 * to do an entire invltlb for checking a single mapping.
880 * If the given pmap is not the current pmap, vm_page_queue_mtx
881 * must be held and curthread pinned to a CPU.
884 pmap_pte_quick(pmap_t pmap, vm_offset_t va)
889 pde = pmap_pde(pmap, va);
893 /* are we current address space or kernel? */
894 if (pmap_is_current(pmap))
896 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
897 KASSERT(curthread->td_pinned > 0, ("curthread not pinned"));
898 newpf = *pde & PG_FRAME;
899 if ((*PMAP1 & PG_FRAME) != newpf) {
900 *PMAP1 = newpf | PG_RW | PG_V | PG_A | PG_M;
902 PMAP1cpu = PCPU_GET(cpuid);
908 if (PMAP1cpu != PCPU_GET(cpuid)) {
909 PMAP1cpu = PCPU_GET(cpuid);
915 return (PADDR1 + (i386_btop(va) & (NPTEPG - 1)));
921 * Routine: pmap_extract
923 * Extract the physical page address associated
924 * with the given map/virtual_address pair.
927 pmap_extract(pmap_t pmap, vm_offset_t va)
935 pde = pmap->pm_pdir[va >> PDRSHIFT];
937 if ((pde & PG_PS) != 0) {
938 rtval = (pde & ~PDRMASK) | (va & PDRMASK);
942 pte = pmap_pte(pmap, va);
943 rtval = (*pte & PG_FRAME) | (va & PAGE_MASK);
944 pmap_pte_release(pte);
951 * Routine: pmap_extract_and_hold
953 * Atomically extract and hold the physical page
954 * with the given pmap and virtual address pair
955 * if that mapping permits the given protection.
958 pmap_extract_and_hold(pmap_t pmap, vm_offset_t va, vm_prot_t prot)
965 vm_page_lock_queues();
967 pde = *pmap_pde(pmap, va);
970 if ((pde & PG_RW) || (prot & VM_PROT_WRITE) == 0) {
971 m = PHYS_TO_VM_PAGE((pde & ~PDRMASK) |
977 pte = *pmap_pte_quick(pmap, va);
979 ((pte & PG_RW) || (prot & VM_PROT_WRITE) == 0)) {
980 m = PHYS_TO_VM_PAGE(pte & PG_FRAME);
986 vm_page_unlock_queues();
991 /***************************************************
992 * Low level mapping routines.....
993 ***************************************************/
996 * Add a wired page to the kva.
997 * Note: not SMP coherent.
1000 pmap_kenter(vm_offset_t va, vm_paddr_t pa)
1005 pte_store(pte, pa | PG_RW | PG_V | pgeflag);
1009 * Remove a page from the kernel pagetables.
1010 * Note: not SMP coherent.
1013 pmap_kremove(vm_offset_t va)
1022 * Used to map a range of physical addresses into kernel
1023 * virtual address space.
1025 * The value passed in '*virt' is a suggested virtual address for
1026 * the mapping. Architectures which can support a direct-mapped
1027 * physical to virtual region can return the appropriate address
1028 * within that region, leaving '*virt' unchanged. Other
1029 * architectures should map the pages starting at '*virt' and
1030 * update '*virt' with the first usable address after the mapped
1034 pmap_map(vm_offset_t *virt, vm_paddr_t start, vm_paddr_t end, int prot)
1036 vm_offset_t va, sva;
1039 while (start < end) {
1040 pmap_kenter(va, start);
1044 pmap_invalidate_range(kernel_pmap, sva, va);
1051 * Add a list of wired pages to the kva
1052 * this routine is only used for temporary
1053 * kernel mappings that do not need to have
1054 * page modification or references recorded.
1055 * Note that old mappings are simply written
1056 * over. The page *must* be wired.
1057 * Note: SMP coherent. Uses a ranged shootdown IPI.
1060 pmap_qenter(vm_offset_t sva, vm_page_t *ma, int count)
1062 pt_entry_t *endpte, oldpte, *pte;
1066 endpte = pte + count;
1067 while (pte < endpte) {
1069 pte_store(pte, VM_PAGE_TO_PHYS(*ma) | pgeflag | PG_RW | PG_V);
1073 if ((oldpte & PG_V) != 0)
1074 pmap_invalidate_range(kernel_pmap, sva, sva + count *
1079 * This routine tears out page mappings from the
1080 * kernel -- it is meant only for temporary mappings.
1081 * Note: SMP coherent. Uses a ranged shootdown IPI.
1084 pmap_qremove(vm_offset_t sva, int count)
1089 while (count-- > 0) {
1093 pmap_invalidate_range(kernel_pmap, sva, va);
1096 /***************************************************
1097 * Page table page management routines.....
1098 ***************************************************/
1101 * This routine unholds page table pages, and if the hold count
1102 * drops to zero, then it decrements the wire count.
1104 static PMAP_INLINE int
1105 pmap_unwire_pte_hold(pmap_t pmap, vm_page_t m)
1109 if (m->wire_count == 0)
1110 return _pmap_unwire_pte_hold(pmap, m);
1116 _pmap_unwire_pte_hold(pmap_t pmap, vm_page_t m)
1121 * unmap the page table page
1123 pmap->pm_pdir[m->pindex] = 0;
1124 --pmap->pm_stats.resident_count;
1127 * Do an invltlb to make the invalidated mapping
1128 * take effect immediately.
1130 pteva = VM_MAXUSER_ADDRESS + i386_ptob(m->pindex);
1131 pmap_invalidate_page(pmap, pteva);
1133 vm_page_free_zero(m);
1134 atomic_subtract_int(&cnt.v_wire_count, 1);
1139 * After removing a page table entry, this routine is used to
1140 * conditionally free the page, and manage the hold/wire counts.
1143 pmap_unuse_pt(pmap_t pmap, vm_offset_t va)
1148 if (va >= VM_MAXUSER_ADDRESS)
1150 ptepde = *pmap_pde(pmap, va);
1151 mpte = PHYS_TO_VM_PAGE(ptepde & PG_FRAME);
1152 return pmap_unwire_pte_hold(pmap, mpte);
1160 PMAP_LOCK_INIT(pmap);
1161 pmap->pm_pdir = (pd_entry_t *)(KERNBASE + (vm_offset_t)IdlePTD);
1163 pmap->pm_pdpt = (pdpt_entry_t *)(KERNBASE + (vm_offset_t)IdlePDPT);
1165 pmap->pm_active = 0;
1166 PCPU_SET(curpmap, pmap);
1167 TAILQ_INIT(&pmap->pm_pvchunk);
1168 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1169 mtx_lock_spin(&allpmaps_lock);
1170 LIST_INSERT_HEAD(&allpmaps, pmap, pm_list);
1171 mtx_unlock_spin(&allpmaps_lock);
1175 * Initialize a preallocated and zeroed pmap structure,
1176 * such as one in a vmspace structure.
1180 register struct pmap *pmap;
1182 vm_page_t m, ptdpg[NPGPTD];
1187 PMAP_LOCK_INIT(pmap);
1190 * No need to allocate page table space yet but we do need a valid
1191 * page directory table.
1193 if (pmap->pm_pdir == NULL) {
1194 pmap->pm_pdir = (pd_entry_t *)kmem_alloc_nofault(kernel_map,
1197 pmap->pm_pdpt = uma_zalloc(pdptzone, M_WAITOK | M_ZERO);
1198 KASSERT(((vm_offset_t)pmap->pm_pdpt &
1199 ((NPGPTD * sizeof(pdpt_entry_t)) - 1)) == 0,
1200 ("pmap_pinit: pdpt misaligned"));
1201 KASSERT(pmap_kextract((vm_offset_t)pmap->pm_pdpt) < (4ULL<<30),
1202 ("pmap_pinit: pdpt above 4g"));
1207 * allocate the page directory page(s)
1209 for (i = 0; i < NPGPTD;) {
1210 m = vm_page_alloc(NULL, color++,
1211 VM_ALLOC_NORMAL | VM_ALLOC_NOOBJ | VM_ALLOC_WIRED |
1220 pmap_qenter((vm_offset_t)pmap->pm_pdir, ptdpg, NPGPTD);
1222 for (i = 0; i < NPGPTD; i++) {
1223 if ((ptdpg[i]->flags & PG_ZERO) == 0)
1224 bzero(pmap->pm_pdir + (i * NPDEPG), PAGE_SIZE);
1227 mtx_lock_spin(&allpmaps_lock);
1228 LIST_INSERT_HEAD(&allpmaps, pmap, pm_list);
1229 mtx_unlock_spin(&allpmaps_lock);
1230 /* Wire in kernel global address entries. */
1231 /* XXX copies current process, does not fill in MPPTDI */
1232 bcopy(PTD + KPTDI, pmap->pm_pdir + KPTDI, nkpt * sizeof(pd_entry_t));
1234 pmap->pm_pdir[MPPTDI] = PTD[MPPTDI];
1237 /* install self-referential address mapping entry(s) */
1238 for (i = 0; i < NPGPTD; i++) {
1239 pa = VM_PAGE_TO_PHYS(ptdpg[i]);
1240 pmap->pm_pdir[PTDPTDI + i] = pa | PG_V | PG_RW | PG_A | PG_M;
1242 pmap->pm_pdpt[i] = pa | PG_V;
1246 pmap->pm_active = 0;
1247 TAILQ_INIT(&pmap->pm_pvchunk);
1248 bzero(&pmap->pm_stats, sizeof pmap->pm_stats);
1252 * this routine is called if the page table page is not
1256 _pmap_allocpte(pmap_t pmap, unsigned ptepindex, int flags)
1261 KASSERT((flags & (M_NOWAIT | M_WAITOK)) == M_NOWAIT ||
1262 (flags & (M_NOWAIT | M_WAITOK)) == M_WAITOK,
1263 ("_pmap_allocpte: flags is neither M_NOWAIT nor M_WAITOK"));
1266 * Allocate a page table page.
1268 if ((m = vm_page_alloc(NULL, ptepindex, VM_ALLOC_NOOBJ |
1269 VM_ALLOC_WIRED | VM_ALLOC_ZERO)) == NULL) {
1270 if (flags & M_WAITOK) {
1272 vm_page_unlock_queues();
1274 vm_page_lock_queues();
1279 * Indicate the need to retry. While waiting, the page table
1280 * page may have been allocated.
1284 if ((m->flags & PG_ZERO) == 0)
1288 * Map the pagetable page into the process address space, if
1289 * it isn't already there.
1292 pmap->pm_stats.resident_count++;
1294 ptepa = VM_PAGE_TO_PHYS(m);
1295 pmap->pm_pdir[ptepindex] =
1296 (pd_entry_t) (ptepa | PG_U | PG_RW | PG_V | PG_A | PG_M);
1302 pmap_allocpte(pmap_t pmap, vm_offset_t va, int flags)
1308 KASSERT((flags & (M_NOWAIT | M_WAITOK)) == M_NOWAIT ||
1309 (flags & (M_NOWAIT | M_WAITOK)) == M_WAITOK,
1310 ("pmap_allocpte: flags is neither M_NOWAIT nor M_WAITOK"));
1313 * Calculate pagetable page index
1315 ptepindex = va >> PDRSHIFT;
1318 * Get the page directory entry
1320 ptepa = pmap->pm_pdir[ptepindex];
1323 * This supports switching from a 4MB page to a
1326 if (ptepa & PG_PS) {
1327 pmap->pm_pdir[ptepindex] = 0;
1329 pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
1330 pmap_invalidate_all(kernel_pmap);
1334 * If the page table page is mapped, we just increment the
1335 * hold count, and activate it.
1338 m = PHYS_TO_VM_PAGE(ptepa);
1342 * Here if the pte page isn't mapped, or if it has
1345 m = _pmap_allocpte(pmap, ptepindex, flags);
1346 if (m == NULL && (flags & M_WAITOK))
1353 /***************************************************
1354 * Pmap allocation/deallocation routines.
1355 ***************************************************/
1359 * Deal with a SMP shootdown of other users of the pmap that we are
1360 * trying to dispose of. This can be a bit hairy.
1362 static u_int *lazymask;
1363 static u_int lazyptd;
1364 static volatile u_int lazywait;
1366 void pmap_lazyfix_action(void);
1369 pmap_lazyfix_action(void)
1371 u_int mymask = PCPU_GET(cpumask);
1374 *ipi_lazypmap_counts[PCPU_GET(cpuid)]++;
1376 if (rcr3() == lazyptd)
1377 load_cr3(PCPU_GET(curpcb)->pcb_cr3);
1378 atomic_clear_int(lazymask, mymask);
1379 atomic_store_rel_int(&lazywait, 1);
1383 pmap_lazyfix_self(u_int mymask)
1386 if (rcr3() == lazyptd)
1387 load_cr3(PCPU_GET(curpcb)->pcb_cr3);
1388 atomic_clear_int(lazymask, mymask);
1393 pmap_lazyfix(pmap_t pmap)
1397 register u_int spins;
1399 while ((mask = pmap->pm_active) != 0) {
1401 mask = mask & -mask; /* Find least significant set bit */
1402 mtx_lock_spin(&smp_ipi_mtx);
1404 lazyptd = vtophys(pmap->pm_pdpt);
1406 lazyptd = vtophys(pmap->pm_pdir);
1408 mymask = PCPU_GET(cpumask);
1409 if (mask == mymask) {
1410 lazymask = &pmap->pm_active;
1411 pmap_lazyfix_self(mymask);
1413 atomic_store_rel_int((u_int *)&lazymask,
1414 (u_int)&pmap->pm_active);
1415 atomic_store_rel_int(&lazywait, 0);
1416 ipi_selected(mask, IPI_LAZYPMAP);
1417 while (lazywait == 0) {
1423 mtx_unlock_spin(&smp_ipi_mtx);
1425 printf("pmap_lazyfix: spun for 50000000\n");
1432 * Cleaning up on uniprocessor is easy. For various reasons, we're
1433 * unlikely to have to even execute this code, including the fact
1434 * that the cleanup is deferred until the parent does a wait(2), which
1435 * means that another userland process has run.
1438 pmap_lazyfix(pmap_t pmap)
1442 cr3 = vtophys(pmap->pm_pdir);
1443 if (cr3 == rcr3()) {
1444 load_cr3(PCPU_GET(curpcb)->pcb_cr3);
1445 pmap->pm_active &= ~(PCPU_GET(cpumask));
1451 * Release any resources held by the given physical map.
1452 * Called when a pmap initialized by pmap_pinit is being released.
1453 * Should only be called if the map contains no valid mappings.
1456 pmap_release(pmap_t pmap)
1458 vm_page_t m, ptdpg[NPGPTD];
1461 KASSERT(pmap->pm_stats.resident_count == 0,
1462 ("pmap_release: pmap resident count %ld != 0",
1463 pmap->pm_stats.resident_count));
1466 mtx_lock_spin(&allpmaps_lock);
1467 LIST_REMOVE(pmap, pm_list);
1468 mtx_unlock_spin(&allpmaps_lock);
1470 for (i = 0; i < NPGPTD; i++)
1471 ptdpg[i] = PHYS_TO_VM_PAGE(pmap->pm_pdir[PTDPTDI + i]);
1473 bzero(pmap->pm_pdir + PTDPTDI, (nkpt + NPGPTD) *
1474 sizeof(*pmap->pm_pdir));
1476 pmap->pm_pdir[MPPTDI] = 0;
1479 pmap_qremove((vm_offset_t)pmap->pm_pdir, NPGPTD);
1481 vm_page_lock_queues();
1482 for (i = 0; i < NPGPTD; i++) {
1485 KASSERT(VM_PAGE_TO_PHYS(m) == (pmap->pm_pdpt[i] & PG_FRAME),
1486 ("pmap_release: got wrong ptd page"));
1489 atomic_subtract_int(&cnt.v_wire_count, 1);
1490 vm_page_free_zero(m);
1492 vm_page_unlock_queues();
1493 PMAP_LOCK_DESTROY(pmap);
1497 kvm_size(SYSCTL_HANDLER_ARGS)
1499 unsigned long ksize = VM_MAX_KERNEL_ADDRESS - KERNBASE;
1501 return sysctl_handle_long(oidp, &ksize, 0, req);
1503 SYSCTL_PROC(_vm, OID_AUTO, kvm_size, CTLTYPE_LONG|CTLFLAG_RD,
1504 0, 0, kvm_size, "IU", "Size of KVM");
1507 kvm_free(SYSCTL_HANDLER_ARGS)
1509 unsigned long kfree = VM_MAX_KERNEL_ADDRESS - kernel_vm_end;
1511 return sysctl_handle_long(oidp, &kfree, 0, req);
1513 SYSCTL_PROC(_vm, OID_AUTO, kvm_free, CTLTYPE_LONG|CTLFLAG_RD,
1514 0, 0, kvm_free, "IU", "Amount of KVM free");
1517 * grow the number of kernel page table entries, if needed
1520 pmap_growkernel(vm_offset_t addr)
1523 vm_paddr_t ptppaddr;
1528 mtx_assert(&kernel_map->system_mtx, MA_OWNED);
1529 if (kernel_vm_end == 0) {
1530 kernel_vm_end = KERNBASE;
1532 while (pdir_pde(PTD, kernel_vm_end)) {
1533 kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1535 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
1536 kernel_vm_end = kernel_map->max_offset;
1541 addr = roundup2(addr, PAGE_SIZE * NPTEPG);
1542 if (addr - 1 >= kernel_map->max_offset)
1543 addr = kernel_map->max_offset;
1544 while (kernel_vm_end < addr) {
1545 if (pdir_pde(PTD, kernel_vm_end)) {
1546 kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1547 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
1548 kernel_vm_end = kernel_map->max_offset;
1555 * This index is bogus, but out of the way
1557 nkpg = vm_page_alloc(NULL, nkpt,
1558 VM_ALLOC_NOOBJ | VM_ALLOC_SYSTEM | VM_ALLOC_WIRED);
1560 panic("pmap_growkernel: no memory to grow kernel");
1564 pmap_zero_page(nkpg);
1565 ptppaddr = VM_PAGE_TO_PHYS(nkpg);
1566 newpdir = (pd_entry_t) (ptppaddr | PG_V | PG_RW | PG_A | PG_M);
1567 pdir_pde(PTD, kernel_vm_end) = newpdir;
1569 mtx_lock_spin(&allpmaps_lock);
1570 LIST_FOREACH(pmap, &allpmaps, pm_list) {
1571 pde = pmap_pde(pmap, kernel_vm_end);
1572 pde_store(pde, newpdir);
1574 mtx_unlock_spin(&allpmaps_lock);
1575 kernel_vm_end = (kernel_vm_end + PAGE_SIZE * NPTEPG) & ~(PAGE_SIZE * NPTEPG - 1);
1576 if (kernel_vm_end - 1 >= kernel_map->max_offset) {
1577 kernel_vm_end = kernel_map->max_offset;
1584 /***************************************************
1585 * page management routines.
1586 ***************************************************/
1588 CTASSERT(sizeof(struct pv_chunk) == PAGE_SIZE);
1589 CTASSERT(_NPCM == 11);
1591 static __inline struct pv_chunk *
1592 pv_to_chunk(pv_entry_t pv)
1595 return (struct pv_chunk *)((uintptr_t)pv & ~(uintptr_t)PAGE_MASK);
1598 #define PV_PMAP(pv) (pv_to_chunk(pv)->pc_pmap)
1600 #define PC_FREE0_9 0xfffffffful /* Free values for index 0 through 9 */
1601 #define PC_FREE10 0x0000fffful /* Free values for index 10 */
1603 static uint64_t pc_freemask[11] = {
1604 PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
1605 PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
1606 PC_FREE0_9, PC_FREE0_9, PC_FREE0_9,
1607 PC_FREE0_9, PC_FREE10
1610 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_count, CTLFLAG_RD, &pv_entry_count, 0,
1611 "Current number of pv entries");
1614 static int pc_chunk_count, pc_chunk_allocs, pc_chunk_frees, pc_chunk_tryfail;
1616 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_count, CTLFLAG_RD, &pc_chunk_count, 0,
1617 "Current number of pv entry chunks");
1618 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_allocs, CTLFLAG_RD, &pc_chunk_allocs, 0,
1619 "Current number of pv entry chunks allocated");
1620 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_frees, CTLFLAG_RD, &pc_chunk_frees, 0,
1621 "Current number of pv entry chunks frees");
1622 SYSCTL_INT(_vm_pmap, OID_AUTO, pc_chunk_tryfail, CTLFLAG_RD, &pc_chunk_tryfail, 0,
1623 "Number of times tried to get a chunk page but failed.");
1625 static long pv_entry_frees, pv_entry_allocs;
1626 static int pv_entry_spare;
1628 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_frees, CTLFLAG_RD, &pv_entry_frees, 0,
1629 "Current number of pv entry frees");
1630 SYSCTL_LONG(_vm_pmap, OID_AUTO, pv_entry_allocs, CTLFLAG_RD, &pv_entry_allocs, 0,
1631 "Current number of pv entry allocs");
1632 SYSCTL_INT(_vm_pmap, OID_AUTO, pv_entry_spare, CTLFLAG_RD, &pv_entry_spare, 0,
1633 "Current number of spare pv entries");
1635 static int pmap_collect_inactive, pmap_collect_active;
1637 SYSCTL_INT(_vm_pmap, OID_AUTO, pmap_collect_inactive, CTLFLAG_RD, &pmap_collect_inactive, 0,
1638 "Current number times pmap_collect called on inactive queue");
1639 SYSCTL_INT(_vm_pmap, OID_AUTO, pmap_collect_active, CTLFLAG_RD, &pmap_collect_active, 0,
1640 "Current number times pmap_collect called on active queue");
1644 * We are in a serious low memory condition. Resort to
1645 * drastic measures to free some pages so we can allocate
1646 * another pv entry chunk. This is normally called to
1647 * unmap inactive pages, and if necessary, active pages.
1650 pmap_collect(pmap_t locked_pmap, struct vpgqueues *vpq)
1653 pt_entry_t *pte, tpte;
1654 pv_entry_t next_pv, pv;
1659 TAILQ_FOREACH(m, &vpq->pl, pageq) {
1660 if (m->hold_count || m->busy || (m->flags & PG_BUSY))
1662 TAILQ_FOREACH_SAFE(pv, &m->md.pv_list, pv_list, next_pv) {
1665 /* Avoid deadlock and lock recursion. */
1666 if (pmap > locked_pmap)
1668 else if (pmap != locked_pmap && !PMAP_TRYLOCK(pmap))
1670 pmap->pm_stats.resident_count--;
1671 pte = pmap_pte_quick(pmap, va);
1672 tpte = pte_load_clear(pte);
1673 KASSERT((tpte & PG_W) == 0,
1674 ("pmap_collect: wired pte %#jx", (uintmax_t)tpte));
1676 vm_page_flag_set(m, PG_REFERENCED);
1678 KASSERT((tpte & PG_RW),
1679 ("pmap_collect: modified page not writable: va: %#x, pte: %#jx",
1680 va, (uintmax_t)tpte));
1683 pmap_invalidate_page(pmap, va);
1684 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
1685 if (TAILQ_EMPTY(&m->md.pv_list))
1686 vm_page_flag_clear(m, PG_WRITEABLE);
1687 m->md.pv_list_count--;
1688 pmap_unuse_pt(pmap, va);
1689 if (pmap != locked_pmap)
1691 free_pv_entry(locked_pmap, pv);
1699 * free the pv_entry back to the free list
1702 free_pv_entry(pmap_t pmap, pv_entry_t pv)
1705 struct pv_chunk *pc;
1706 int idx, field, bit;
1708 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1709 PV_STAT(pv_entry_frees++);
1710 PV_STAT(pv_entry_spare++);
1712 pc = pv_to_chunk(pv);
1713 idx = pv - &pc->pc_pventry[0];
1716 pc->pc_map[field] |= 1ul << bit;
1717 /* move to head of list */
1718 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
1719 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
1720 for (idx = 0; idx < _NPCM; idx++)
1721 if (pc->pc_map[idx] != pc_freemask[idx])
1723 PV_STAT(pv_entry_spare -= _NPCPV);
1724 PV_STAT(pc_chunk_count--);
1725 PV_STAT(pc_chunk_frees++);
1726 /* entire chunk is free, return it */
1727 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
1728 m = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)pc));
1729 pmap_qremove((vm_offset_t)pc, 1);
1730 vm_page_unwire(m, 0);
1732 pmap_ptelist_free(&pv_vafree, (vm_offset_t)pc);
1736 * get a new pv_entry, allocating a block from the system
1740 get_pv_entry(pmap_t pmap, int try)
1742 static const struct timeval printinterval = { 60, 0 };
1743 static struct timeval lastprint;
1744 static vm_pindex_t colour;
1747 struct pv_chunk *pc;
1750 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1751 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1752 PV_STAT(pv_entry_allocs++);
1754 if (pv_entry_count > pv_entry_high_water)
1755 pagedaemon_wakeup();
1756 pc = TAILQ_FIRST(&pmap->pm_pvchunk);
1758 for (field = 0; field < _NPCM; field++) {
1759 if (pc->pc_map[field]) {
1760 bit = bsfl(pc->pc_map[field]);
1764 if (field < _NPCM) {
1765 pv = &pc->pc_pventry[field * 32 + bit];
1766 pc->pc_map[field] &= ~(1ul << bit);
1767 /* If this was the last item, move it to tail */
1768 for (field = 0; field < _NPCM; field++)
1769 if (pc->pc_map[field] != 0) {
1770 PV_STAT(pv_entry_spare--);
1771 return (pv); /* not full, return */
1773 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
1774 TAILQ_INSERT_TAIL(&pmap->pm_pvchunk, pc, pc_list);
1775 PV_STAT(pv_entry_spare--);
1779 pc = (struct pv_chunk *)pmap_ptelist_alloc(&pv_vafree);
1780 m = vm_page_alloc(NULL, colour, VM_ALLOC_SYSTEM |
1781 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED);
1782 if (m == NULL || pc == NULL) {
1785 PV_STAT(pc_chunk_tryfail++);
1787 vm_page_lock_queues();
1788 vm_page_unwire(m, 0);
1790 vm_page_unlock_queues();
1793 pmap_ptelist_free(&pv_vafree, (vm_offset_t)pc);
1797 * Reclaim pv entries: At first, destroy mappings to
1798 * inactive pages. After that, if a pv chunk entry
1799 * is still needed, destroy mappings to active pages.
1801 if (ratecheck(&lastprint, &printinterval))
1802 printf("Approaching the limit on PV entries, "
1803 "consider increasing tunables "
1804 "vm.pmap.shpgperproc or "
1805 "vm.pmap.pv_entry_max\n");
1806 PV_STAT(pmap_collect_inactive++);
1807 pmap_collect(pmap, &vm_page_queues[PQ_INACTIVE]);
1809 m = vm_page_alloc(NULL, colour, VM_ALLOC_SYSTEM |
1810 VM_ALLOC_NOOBJ | VM_ALLOC_WIRED);
1812 pc = (struct pv_chunk *)pmap_ptelist_alloc(&pv_vafree);
1813 if (m == NULL || pc == NULL) {
1814 PV_STAT(pmap_collect_active++);
1815 pmap_collect(pmap, &vm_page_queues[PQ_ACTIVE]);
1817 m = vm_page_alloc(NULL, colour,
1818 VM_ALLOC_SYSTEM | VM_ALLOC_NOOBJ |
1821 pc = (struct pv_chunk *)
1822 pmap_ptelist_alloc(&pv_vafree);
1823 if (m == NULL || pc == NULL)
1824 panic("get_pv_entry: increase vm.pmap.shpgperproc");
1827 PV_STAT(pc_chunk_count++);
1828 PV_STAT(pc_chunk_allocs++);
1830 pmap_qenter((vm_offset_t)pc, &m, 1);
1832 pc->pc_map[0] = pc_freemask[0] & ~1ul; /* preallocated bit 0 */
1833 for (field = 1; field < _NPCM; field++)
1834 pc->pc_map[field] = pc_freemask[field];
1835 pv = &pc->pc_pventry[0];
1836 TAILQ_INSERT_HEAD(&pmap->pm_pvchunk, pc, pc_list);
1837 PV_STAT(pv_entry_spare += _NPCPV - 1);
1842 pmap_remove_entry(pmap_t pmap, vm_page_t m, vm_offset_t va)
1846 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1847 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1848 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
1849 if (pmap == PV_PMAP(pv) && va == pv->pv_va)
1852 KASSERT(pv != NULL, ("pmap_remove_entry: pv not found"));
1853 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
1854 m->md.pv_list_count--;
1855 if (TAILQ_EMPTY(&m->md.pv_list))
1856 vm_page_flag_clear(m, PG_WRITEABLE);
1857 free_pv_entry(pmap, pv);
1861 * Create a pv entry for page at pa for
1865 pmap_insert_entry(pmap_t pmap, vm_offset_t va, vm_page_t m)
1869 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1870 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1871 pv = get_pv_entry(pmap, FALSE);
1873 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
1874 m->md.pv_list_count++;
1878 * Conditionally create a pv entry.
1881 pmap_try_insert_pv_entry(pmap_t pmap, vm_offset_t va, vm_page_t m)
1885 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1886 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1887 if (pv_entry_count < pv_entry_high_water &&
1888 (pv = get_pv_entry(pmap, TRUE)) != NULL) {
1890 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
1891 m->md.pv_list_count++;
1898 * pmap_remove_pte: do the things to unmap a page in a process
1901 pmap_remove_pte(pmap_t pmap, pt_entry_t *ptq, vm_offset_t va)
1906 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1907 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1908 oldpte = pte_load_clear(ptq);
1910 pmap->pm_stats.wired_count -= 1;
1912 * Machines that don't support invlpg, also don't support
1916 pmap_invalidate_page(kernel_pmap, va);
1917 pmap->pm_stats.resident_count -= 1;
1918 if (oldpte & PG_MANAGED) {
1919 m = PHYS_TO_VM_PAGE(oldpte);
1920 if (oldpte & PG_M) {
1921 KASSERT((oldpte & PG_RW),
1922 ("pmap_remove_pte: modified page not writable: va: %#x, pte: %#jx",
1923 va, (uintmax_t)oldpte));
1927 vm_page_flag_set(m, PG_REFERENCED);
1928 pmap_remove_entry(pmap, m, va);
1930 return (pmap_unuse_pt(pmap, va));
1934 * Remove a single page from a process address space
1937 pmap_remove_page(pmap_t pmap, vm_offset_t va)
1941 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1942 KASSERT(curthread->td_pinned > 0, ("curthread not pinned"));
1943 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
1944 if ((pte = pmap_pte_quick(pmap, va)) == NULL || *pte == 0)
1946 pmap_remove_pte(pmap, pte, va);
1947 pmap_invalidate_page(pmap, va);
1951 * Remove the given range of addresses from the specified map.
1953 * It is assumed that the start and end are properly
1954 * rounded to the page size.
1957 pmap_remove(pmap_t pmap, vm_offset_t sva, vm_offset_t eva)
1965 * Perform an unsynchronized read. This is, however, safe.
1967 if (pmap->pm_stats.resident_count == 0)
1972 vm_page_lock_queues();
1977 * special handling of removing one page. a very
1978 * common operation and easy to short circuit some
1981 if ((sva + PAGE_SIZE == eva) &&
1982 ((pmap->pm_pdir[(sva >> PDRSHIFT)] & PG_PS) == 0)) {
1983 pmap_remove_page(pmap, sva);
1987 for (; sva < eva; sva = pdnxt) {
1991 * Calculate index for next page table.
1993 pdnxt = (sva + NBPDR) & ~PDRMASK;
1994 if (pmap->pm_stats.resident_count == 0)
1997 pdirindex = sva >> PDRSHIFT;
1998 ptpaddr = pmap->pm_pdir[pdirindex];
2001 * Weed out invalid mappings. Note: we assume that the page
2002 * directory table is always allocated, and in kernel virtual.
2008 * Check for large page.
2010 if ((ptpaddr & PG_PS) != 0) {
2011 pmap->pm_pdir[pdirindex] = 0;
2012 pmap->pm_stats.resident_count -= NBPDR / PAGE_SIZE;
2018 * Limit our scan to either the end of the va represented
2019 * by the current page table page, or to the end of the
2020 * range being removed.
2025 for (pte = pmap_pte_quick(pmap, sva); sva != pdnxt; pte++,
2031 * The TLB entry for a PG_G mapping is invalidated
2032 * by pmap_remove_pte().
2034 if ((*pte & PG_G) == 0)
2036 if (pmap_remove_pte(pmap, pte, sva))
2042 vm_page_unlock_queues();
2044 pmap_invalidate_all(pmap);
2049 * Routine: pmap_remove_all
2051 * Removes this physical page from
2052 * all physical maps in which it resides.
2053 * Reflects back modify bits to the pager.
2056 * Original versions of this routine were very
2057 * inefficient because they iteratively called
2058 * pmap_remove (slow...)
2062 pmap_remove_all(vm_page_t m)
2064 register pv_entry_t pv;
2066 pt_entry_t *pte, tpte;
2068 #if defined(PMAP_DIAGNOSTIC)
2070 * XXX This makes pmap_remove_all() illegal for non-managed pages!
2072 if (m->flags & PG_FICTITIOUS) {
2073 panic("pmap_remove_all: illegal for unmanaged page, va: 0x%x",
2074 VM_PAGE_TO_PHYS(m));
2077 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2079 while ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
2082 pmap->pm_stats.resident_count--;
2083 pte = pmap_pte_quick(pmap, pv->pv_va);
2084 tpte = pte_load_clear(pte);
2086 pmap->pm_stats.wired_count--;
2088 vm_page_flag_set(m, PG_REFERENCED);
2091 * Update the vm_page_t clean and reference bits.
2094 KASSERT((tpte & PG_RW),
2095 ("pmap_remove_all: modified page not writable: va: %#x, pte: %#jx",
2096 pv->pv_va, (uintmax_t)tpte));
2099 pmap_invalidate_page(pmap, pv->pv_va);
2100 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
2101 m->md.pv_list_count--;
2102 pmap_unuse_pt(pmap, pv->pv_va);
2104 free_pv_entry(pmap, pv);
2106 vm_page_flag_clear(m, PG_WRITEABLE);
2111 * Set the physical protection on the
2112 * specified range of this map as requested.
2115 pmap_protect(pmap_t pmap, vm_offset_t sva, vm_offset_t eva, vm_prot_t prot)
2122 if ((prot & VM_PROT_READ) == VM_PROT_NONE) {
2123 pmap_remove(pmap, sva, eva);
2127 if (prot & VM_PROT_WRITE)
2132 vm_page_lock_queues();
2135 for (; sva < eva; sva = pdnxt) {
2136 unsigned obits, pbits, pdirindex;
2138 pdnxt = (sva + NBPDR) & ~PDRMASK;
2140 pdirindex = sva >> PDRSHIFT;
2141 ptpaddr = pmap->pm_pdir[pdirindex];
2144 * Weed out invalid mappings. Note: we assume that the page
2145 * directory table is always allocated, and in kernel virtual.
2151 * Check for large page.
2153 if ((ptpaddr & PG_PS) != 0) {
2154 pmap->pm_pdir[pdirindex] &= ~(PG_M|PG_RW);
2162 for (pte = pmap_pte_quick(pmap, sva); sva != pdnxt; pte++,
2168 * Regardless of whether a pte is 32 or 64 bits in
2169 * size, PG_RW, PG_A, and PG_M are among the least
2170 * significant 32 bits.
2172 obits = pbits = *(u_int *)pte;
2173 if (pbits & PG_MANAGED) {
2176 m = PHYS_TO_VM_PAGE(*pte);
2177 vm_page_flag_set(m, PG_REFERENCED);
2180 if ((pbits & PG_M) != 0) {
2182 m = PHYS_TO_VM_PAGE(*pte);
2187 pbits &= ~(PG_RW | PG_M);
2189 if (pbits != obits) {
2190 if (!atomic_cmpset_int((u_int *)pte, obits,
2194 pmap_invalidate_page(pmap, sva);
2201 vm_page_unlock_queues();
2203 pmap_invalidate_all(pmap);
2208 * Insert the given physical page (p) at
2209 * the specified virtual address (v) in the
2210 * target physical map with the protection requested.
2212 * If specified, the page will be wired down, meaning
2213 * that the related pte can not be reclaimed.
2215 * NB: This is the only routine which MAY NOT lazy-evaluate
2216 * or lose information. That is, this routine must actually
2217 * insert this page into the given map NOW.
2220 pmap_enter(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
2225 register pt_entry_t *pte;
2227 pt_entry_t origpte, newpte;
2232 #ifdef PMAP_DIAGNOSTIC
2233 if (va > VM_MAX_KERNEL_ADDRESS)
2234 panic("pmap_enter: toobig");
2235 if ((va >= UPT_MIN_ADDRESS) && (va < UPT_MAX_ADDRESS))
2236 panic("pmap_enter: invalid to pmap_enter page table pages (va: 0x%x)", va);
2241 vm_page_lock_queues();
2246 * In the case that a page table page is not
2247 * resident, we are creating it here.
2249 if (va < VM_MAXUSER_ADDRESS) {
2250 mpte = pmap_allocpte(pmap, va, M_WAITOK);
2252 #if 0 && defined(PMAP_DIAGNOSTIC)
2254 pd_entry_t *pdeaddr = pmap_pde(pmap, va);
2256 if ((origpte & PG_V) == 0) {
2257 panic("pmap_enter: invalid kernel page table page, pdir=%p, pde=%p, va=%p\n",
2258 pmap->pm_pdir[PTDPTDI], origpte, va);
2263 pde = pmap_pde(pmap, va);
2264 if ((*pde & PG_PS) != 0)
2265 panic("pmap_enter: attempted pmap_enter on 4MB page");
2266 pte = pmap_pte_quick(pmap, va);
2269 * Page Directory table entry not valid, we need a new PT page
2272 panic("pmap_enter: invalid page directory pdir=%#jx, va=%#x\n",
2273 (uintmax_t)pmap->pm_pdir[PTDPTDI], va);
2276 pa = VM_PAGE_TO_PHYS(m);
2279 opa = origpte & PG_FRAME;
2282 * Mapping has not changed, must be protection or wiring change.
2284 if (origpte && (opa == pa)) {
2286 * Wiring change, just update stats. We don't worry about
2287 * wiring PT pages as they remain resident as long as there
2288 * are valid mappings in them. Hence, if a user page is wired,
2289 * the PT page will be also.
2291 if (wired && ((origpte & PG_W) == 0))
2292 pmap->pm_stats.wired_count++;
2293 else if (!wired && (origpte & PG_W))
2294 pmap->pm_stats.wired_count--;
2297 * Remove extra pte reference
2303 * We might be turning off write access to the page,
2304 * so we go ahead and sense modify status.
2306 if (origpte & PG_MANAGED) {
2313 * Mapping has changed, invalidate old range and fall through to
2314 * handle validating new mapping.
2318 pmap->pm_stats.wired_count--;
2319 if (origpte & PG_MANAGED) {
2320 om = PHYS_TO_VM_PAGE(opa);
2321 pmap_remove_entry(pmap, om, va);
2325 KASSERT(mpte->wire_count > 0,
2326 ("pmap_enter: missing reference to page table page,"
2330 pmap->pm_stats.resident_count++;
2333 * Enter on the PV list if part of our managed memory.
2335 if ((m->flags & (PG_FICTITIOUS | PG_UNMANAGED)) == 0) {
2336 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva,
2337 ("pmap_enter: managed mapping within the clean submap"));
2338 pmap_insert_entry(pmap, va, m);
2343 * Increment counters
2346 pmap->pm_stats.wired_count++;
2350 * Now validate mapping with desired protection/wiring.
2352 newpte = (pt_entry_t)(pa | PG_V);
2353 if ((prot & VM_PROT_WRITE) != 0)
2357 if (va < VM_MAXUSER_ADDRESS)
2359 if (pmap == kernel_pmap)
2363 * if the mapping or permission bits are different, we need
2364 * to update the pte.
2366 if ((origpte & ~(PG_M|PG_A)) != newpte) {
2367 if (origpte & PG_V) {
2369 origpte = pte_load_store(pte, newpte | PG_A);
2370 if (origpte & PG_A) {
2371 if (origpte & PG_MANAGED)
2372 vm_page_flag_set(om, PG_REFERENCED);
2373 if (opa != VM_PAGE_TO_PHYS(m))
2376 if (origpte & PG_M) {
2377 KASSERT((origpte & PG_RW),
2378 ("pmap_enter: modified page not writable: va: %#x, pte: %#jx",
2379 va, (uintmax_t)origpte));
2380 if ((origpte & PG_MANAGED) != 0)
2382 if ((prot & VM_PROT_WRITE) == 0)
2386 pmap_invalidate_page(pmap, va);
2388 pte_store(pte, newpte | PG_A);
2391 vm_page_unlock_queues();
2396 * Maps a sequence of resident pages belonging to the same object.
2397 * The sequence begins with the given page m_start. This page is
2398 * mapped at the given virtual address start. Each subsequent page is
2399 * mapped at a virtual address that is offset from start by the same
2400 * amount as the page is offset from m_start within the object. The
2401 * last page in the sequence is the page with the largest offset from
2402 * m_start that can be mapped at a virtual address less than the given
2403 * virtual address end. Not every virtual page between start and end
2404 * is mapped; only those for which a resident page exists with the
2405 * corresponding offset from m_start are mapped.
2408 pmap_enter_object(pmap_t pmap, vm_offset_t start, vm_offset_t end,
2409 vm_page_t m_start, vm_prot_t prot)
2412 vm_pindex_t diff, psize;
2414 psize = atop(end - start);
2418 while (m != NULL && (diff = m->pindex - m_start->pindex) < psize) {
2419 mpte = pmap_enter_quick_locked(pmap, start + ptoa(diff), m,
2421 m = TAILQ_NEXT(m, listq);
2427 * this code makes some *MAJOR* assumptions:
2428 * 1. Current pmap & pmap exists.
2431 * 4. No page table pages.
2432 * but is *MUCH* faster than pmap_enter...
2436 pmap_enter_quick(pmap_t pmap, vm_offset_t va, vm_page_t m, vm_prot_t prot,
2441 mpte = pmap_enter_quick_locked(pmap, va, m, prot, mpte);
2447 pmap_enter_quick_locked(pmap_t pmap, vm_offset_t va, vm_page_t m,
2448 vm_prot_t prot, vm_page_t mpte)
2453 KASSERT(va < kmi.clean_sva || va >= kmi.clean_eva ||
2454 (m->flags & (PG_FICTITIOUS | PG_UNMANAGED)) != 0,
2455 ("pmap_enter_quick_locked: managed mapping within the clean submap"));
2456 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2457 VM_OBJECT_LOCK_ASSERT(m->object, MA_OWNED);
2458 PMAP_LOCK_ASSERT(pmap, MA_OWNED);
2461 * In the case that a page table page is not
2462 * resident, we are creating it here.
2464 if (va < VM_MAXUSER_ADDRESS) {
2469 * Calculate pagetable page index
2471 ptepindex = va >> PDRSHIFT;
2472 if (mpte && (mpte->pindex == ptepindex)) {
2477 * Get the page directory entry
2479 ptepa = pmap->pm_pdir[ptepindex];
2482 * If the page table page is mapped, we just increment
2483 * the hold count, and activate it.
2487 panic("pmap_enter_quick: unexpected mapping into 4MB page");
2488 mpte = PHYS_TO_VM_PAGE(ptepa);
2491 mpte = _pmap_allocpte(pmap, ptepindex,
2496 vm_page_unlock_queues();
2497 VM_OBJECT_UNLOCK(m->object);
2499 VM_OBJECT_LOCK(m->object);
2500 vm_page_lock_queues();
2512 * This call to vtopte makes the assumption that we are
2513 * entering the page into the current pmap. In order to support
2514 * quick entry into any pmap, one would likely use pmap_pte_quick.
2515 * But that isn't as quick as vtopte.
2520 pmap_unwire_pte_hold(pmap, mpte);
2527 * Enter on the PV list if part of our managed memory. Note that we
2528 * raise IPL while manipulating pv_table since pmap_enter can be
2529 * called at interrupt time.
2531 if ((m->flags & (PG_FICTITIOUS|PG_UNMANAGED)) == 0)
2532 pmap_insert_entry(pmap, va, m);
2535 * Increment counters
2537 pmap->pm_stats.resident_count++;
2539 pa = VM_PAGE_TO_PHYS(m);
2542 * Now validate mapping with RO protection
2544 if (m->flags & (PG_FICTITIOUS|PG_UNMANAGED))
2545 pte_store(pte, pa | PG_V | PG_U);
2547 pte_store(pte, pa | PG_V | PG_U | PG_MANAGED);
2552 * Make a temporary mapping for a physical address. This is only intended
2553 * to be used for panic dumps.
2556 pmap_kenter_temporary(vm_paddr_t pa, int i)
2560 va = (vm_offset_t)crashdumpmap + (i * PAGE_SIZE);
2561 pmap_kenter(va, pa);
2563 return ((void *)crashdumpmap);
2567 * This code maps large physical mmap regions into the
2568 * processor address space. Note that some shortcuts
2569 * are taken, but the code works.
2572 pmap_object_init_pt(pmap_t pmap, vm_offset_t addr,
2573 vm_object_t object, vm_pindex_t pindex,
2578 VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2579 KASSERT(object->type == OBJT_DEVICE,
2580 ("pmap_object_init_pt: non-device object"));
2582 ((addr & (NBPDR - 1)) == 0) && ((size & (NBPDR - 1)) == 0)) {
2585 unsigned int ptepindex;
2590 if (pmap->pm_pdir[ptepindex = (addr >> PDRSHIFT)])
2594 p = vm_page_lookup(object, pindex);
2596 vm_page_lock_queues();
2597 if (vm_page_sleep_if_busy(p, FALSE, "init4p"))
2600 p = vm_page_alloc(object, pindex, VM_ALLOC_NORMAL);
2605 if (vm_pager_get_pages(object, m, 1, 0) != VM_PAGER_OK) {
2606 vm_page_lock_queues();
2608 vm_page_unlock_queues();
2612 p = vm_page_lookup(object, pindex);
2613 vm_page_lock_queues();
2616 vm_page_unlock_queues();
2618 ptepa = VM_PAGE_TO_PHYS(p);
2619 if (ptepa & (NBPDR - 1))
2622 p->valid = VM_PAGE_BITS_ALL;
2625 pmap->pm_stats.resident_count += size >> PAGE_SHIFT;
2626 npdes = size >> PDRSHIFT;
2627 for(i = 0; i < npdes; i++) {
2628 pde_store(&pmap->pm_pdir[ptepindex],
2629 ptepa | PG_U | PG_RW | PG_V | PG_PS);
2633 pmap_invalidate_all(pmap);
2640 * Routine: pmap_change_wiring
2641 * Function: Change the wiring attribute for a map/virtual-address
2643 * In/out conditions:
2644 * The mapping must already exist in the pmap.
2647 pmap_change_wiring(pmap, va, wired)
2648 register pmap_t pmap;
2652 register pt_entry_t *pte;
2655 pte = pmap_pte(pmap, va);
2657 if (wired && !pmap_pte_w(pte))
2658 pmap->pm_stats.wired_count++;
2659 else if (!wired && pmap_pte_w(pte))
2660 pmap->pm_stats.wired_count--;
2663 * Wiring is not a hardware characteristic so there is no need to
2666 pmap_pte_set_w(pte, wired);
2667 pmap_pte_release(pte);
2674 * Copy the range specified by src_addr/len
2675 * from the source map to the range dst_addr/len
2676 * in the destination map.
2678 * This routine is only advisory and need not do anything.
2682 pmap_copy(pmap_t dst_pmap, pmap_t src_pmap, vm_offset_t dst_addr, vm_size_t len,
2683 vm_offset_t src_addr)
2686 vm_offset_t end_addr = src_addr + len;
2689 if (dst_addr != src_addr)
2692 if (!pmap_is_current(src_pmap))
2695 vm_page_lock_queues();
2696 if (dst_pmap < src_pmap) {
2697 PMAP_LOCK(dst_pmap);
2698 PMAP_LOCK(src_pmap);
2700 PMAP_LOCK(src_pmap);
2701 PMAP_LOCK(dst_pmap);
2704 for (addr = src_addr; addr < end_addr; addr = pdnxt) {
2705 pt_entry_t *src_pte, *dst_pte;
2706 vm_page_t dstmpte, srcmpte;
2707 pd_entry_t srcptepaddr;
2710 if (addr >= UPT_MIN_ADDRESS)
2711 panic("pmap_copy: invalid to pmap_copy page tables");
2713 pdnxt = (addr + NBPDR) & ~PDRMASK;
2714 ptepindex = addr >> PDRSHIFT;
2716 srcptepaddr = src_pmap->pm_pdir[ptepindex];
2717 if (srcptepaddr == 0)
2720 if (srcptepaddr & PG_PS) {
2721 if (dst_pmap->pm_pdir[ptepindex] == 0) {
2722 dst_pmap->pm_pdir[ptepindex] = srcptepaddr;
2723 dst_pmap->pm_stats.resident_count +=
2729 srcmpte = PHYS_TO_VM_PAGE(srcptepaddr);
2730 if (srcmpte->wire_count == 0)
2731 panic("pmap_copy: source page table page is unused");
2733 if (pdnxt > end_addr)
2736 src_pte = vtopte(addr);
2737 while (addr < pdnxt) {
2741 * we only virtual copy managed pages
2743 if ((ptetemp & PG_MANAGED) != 0) {
2745 * We have to check after allocpte for the
2746 * pte still being around... allocpte can
2749 dstmpte = pmap_allocpte(dst_pmap, addr,
2751 if (dstmpte == NULL)
2753 dst_pte = pmap_pte_quick(dst_pmap, addr);
2754 if (*dst_pte == 0 &&
2755 pmap_try_insert_pv_entry(dst_pmap, addr,
2756 PHYS_TO_VM_PAGE(ptetemp & PG_FRAME))) {
2758 * Clear the modified and
2759 * accessed (referenced) bits
2762 *dst_pte = ptetemp & ~(PG_M | PG_A);
2763 dst_pmap->pm_stats.resident_count++;
2765 pmap_unwire_pte_hold(dst_pmap, dstmpte);
2766 if (dstmpte->wire_count >= srcmpte->wire_count)
2774 vm_page_unlock_queues();
2775 PMAP_UNLOCK(src_pmap);
2776 PMAP_UNLOCK(dst_pmap);
2779 static __inline void
2780 pagezero(void *page)
2782 #if defined(I686_CPU)
2783 if (cpu_class == CPUCLASS_686) {
2784 #if defined(CPU_ENABLE_SSE)
2785 if (cpu_feature & CPUID_SSE2)
2786 sse2_pagezero(page);
2789 i686_pagezero(page);
2792 bzero(page, PAGE_SIZE);
2796 * pmap_zero_page zeros the specified hardware page by mapping
2797 * the page into KVM and using bzero to clear its contents.
2800 pmap_zero_page(vm_page_t m)
2802 struct sysmaps *sysmaps;
2804 sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
2805 mtx_lock(&sysmaps->lock);
2806 if (*sysmaps->CMAP2)
2807 panic("pmap_zero_page: CMAP2 busy");
2809 *sysmaps->CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M;
2810 invlcaddr(sysmaps->CADDR2);
2811 pagezero(sysmaps->CADDR2);
2812 *sysmaps->CMAP2 = 0;
2814 mtx_unlock(&sysmaps->lock);
2818 * pmap_zero_page_area zeros the specified hardware page by mapping
2819 * the page into KVM and using bzero to clear its contents.
2821 * off and size may not cover an area beyond a single hardware page.
2824 pmap_zero_page_area(vm_page_t m, int off, int size)
2826 struct sysmaps *sysmaps;
2828 sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
2829 mtx_lock(&sysmaps->lock);
2830 if (*sysmaps->CMAP2)
2831 panic("pmap_zero_page: CMAP2 busy");
2833 *sysmaps->CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M;
2834 invlcaddr(sysmaps->CADDR2);
2835 if (off == 0 && size == PAGE_SIZE)
2836 pagezero(sysmaps->CADDR2);
2838 bzero((char *)sysmaps->CADDR2 + off, size);
2839 *sysmaps->CMAP2 = 0;
2841 mtx_unlock(&sysmaps->lock);
2845 * pmap_zero_page_idle zeros the specified hardware page by mapping
2846 * the page into KVM and using bzero to clear its contents. This
2847 * is intended to be called from the vm_pagezero process only and
2851 pmap_zero_page_idle(vm_page_t m)
2855 panic("pmap_zero_page: CMAP3 busy");
2857 *CMAP3 = PG_V | PG_RW | VM_PAGE_TO_PHYS(m) | PG_A | PG_M;
2865 * pmap_copy_page copies the specified (machine independent)
2866 * page by mapping the page into virtual memory and using
2867 * bcopy to copy the page, one machine dependent page at a
2871 pmap_copy_page(vm_page_t src, vm_page_t dst)
2873 struct sysmaps *sysmaps;
2875 sysmaps = &sysmaps_pcpu[PCPU_GET(cpuid)];
2876 mtx_lock(&sysmaps->lock);
2877 if (*sysmaps->CMAP1)
2878 panic("pmap_copy_page: CMAP1 busy");
2879 if (*sysmaps->CMAP2)
2880 panic("pmap_copy_page: CMAP2 busy");
2882 invlpg((u_int)sysmaps->CADDR1);
2883 invlpg((u_int)sysmaps->CADDR2);
2884 *sysmaps->CMAP1 = PG_V | VM_PAGE_TO_PHYS(src) | PG_A;
2885 *sysmaps->CMAP2 = PG_V | PG_RW | VM_PAGE_TO_PHYS(dst) | PG_A | PG_M;
2886 bcopy(sysmaps->CADDR1, sysmaps->CADDR2, PAGE_SIZE);
2887 *sysmaps->CMAP1 = 0;
2888 *sysmaps->CMAP2 = 0;
2890 mtx_unlock(&sysmaps->lock);
2894 * Returns true if the pmap's pv is one of the first
2895 * 16 pvs linked to from this page. This count may
2896 * be changed upwards or downwards in the future; it
2897 * is only necessary that true be returned for a small
2898 * subset of pmaps for proper page aging.
2901 pmap_page_exists_quick(pmap, m)
2908 if (m->flags & PG_FICTITIOUS)
2911 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
2912 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
2913 if (PV_PMAP(pv) == pmap) {
2924 * Remove all pages from specified address space
2925 * this aids process exit speeds. Also, this code
2926 * is special cased for current process only, but
2927 * can have the more generic (and slightly slower)
2928 * mode enabled. This is much faster than pmap_remove
2929 * in the case of running down an entire address space.
2932 pmap_remove_pages(pmap_t pmap)
2934 pt_entry_t *pte, tpte;
2937 struct pv_chunk *pc, *npc;
2940 uint32_t inuse, bitmask;
2943 if (pmap != vmspace_pmap(curthread->td_proc->p_vmspace)) {
2944 printf("warning: pmap_remove_pages called with non-current pmap\n");
2947 vm_page_lock_queues();
2950 TAILQ_FOREACH_SAFE(pc, &pmap->pm_pvchunk, pc_list, npc) {
2952 for (field = 0; field < _NPCM; field++) {
2953 inuse = (~(pc->pc_map[field])) & pc_freemask[field];
2954 while (inuse != 0) {
2956 bitmask = 1UL << bit;
2957 idx = field * 32 + bit;
2958 pv = &pc->pc_pventry[idx];
2961 pte = vtopte(pv->pv_va);
2966 "TPTE at %p IS ZERO @ VA %08x\n",
2972 * We cannot remove wired pages from a process' mapping at this time
2979 m = PHYS_TO_VM_PAGE(tpte);
2980 KASSERT(m->phys_addr == (tpte & PG_FRAME),
2981 ("vm_page_t %p phys_addr mismatch %016jx %016jx",
2982 m, (uintmax_t)m->phys_addr,
2985 KASSERT(m < &vm_page_array[vm_page_array_size],
2986 ("pmap_remove_pages: bad tpte %#jx",
2989 pmap->pm_stats.resident_count--;
2994 * Update the vm_page_t clean/reference bits.
3000 PV_STAT(pv_entry_frees++);
3001 PV_STAT(pv_entry_spare++);
3003 pc->pc_map[field] |= bitmask;
3004 m->md.pv_list_count--;
3005 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
3006 if (TAILQ_EMPTY(&m->md.pv_list))
3007 vm_page_flag_clear(m, PG_WRITEABLE);
3009 pmap_unuse_pt(pmap, pv->pv_va);
3013 PV_STAT(pv_entry_spare -= _NPCPV);
3014 PV_STAT(pc_chunk_count--);
3015 PV_STAT(pc_chunk_frees++);
3016 TAILQ_REMOVE(&pmap->pm_pvchunk, pc, pc_list);
3017 m = PHYS_TO_VM_PAGE(pmap_kextract((vm_offset_t)pc));
3018 pmap_qremove((vm_offset_t)pc, 1);
3019 vm_page_unwire(m, 0);
3021 pmap_ptelist_free(&pv_vafree, (vm_offset_t)pc);
3025 vm_page_unlock_queues();
3026 pmap_invalidate_all(pmap);
3033 * Return whether or not the specified physical page was modified
3034 * in any physical maps.
3037 pmap_is_modified(vm_page_t m)
3045 if (m->flags & PG_FICTITIOUS)
3049 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3050 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3053 pte = pmap_pte_quick(pmap, pv->pv_va);
3054 rv = (*pte & PG_M) != 0;
3064 * pmap_is_prefaultable:
3066 * Return whether or not the specified virtual address is elgible
3070 pmap_is_prefaultable(pmap_t pmap, vm_offset_t addr)
3077 if (*pmap_pde(pmap, addr)) {
3086 * Clear the given bit in each of the given page's ptes. The bit is
3087 * expressed as a 32-bit mask. Consequently, if the pte is 64 bits in
3088 * size, only a bit within the least significant 32 can be cleared.
3090 static __inline void
3091 pmap_clear_ptes(vm_page_t m, int bit)
3093 register pv_entry_t pv;
3095 pt_entry_t pbits, *pte;
3097 if ((m->flags & PG_FICTITIOUS) ||
3098 (bit == PG_RW && (m->flags & PG_WRITEABLE) == 0))
3102 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3104 * Loop over all current mappings setting/clearing as appropos If
3105 * setting RO do we need to clear the VAC?
3107 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3110 pte = pmap_pte_quick(pmap, pv->pv_va);
3116 * Regardless of whether a pte is 32 or 64 bits
3117 * in size, PG_RW and PG_M are among the least
3118 * significant 32 bits.
3120 if (!atomic_cmpset_int((u_int *)pte, pbits,
3121 pbits & ~(PG_RW | PG_M)))
3127 atomic_clear_int((u_int *)pte, bit);
3129 pmap_invalidate_page(pmap, pv->pv_va);
3134 vm_page_flag_clear(m, PG_WRITEABLE);
3139 * pmap_page_protect:
3141 * Lower the permission for all mappings to a given page.
3144 pmap_page_protect(vm_page_t m, vm_prot_t prot)
3146 if ((prot & VM_PROT_WRITE) == 0) {
3147 if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
3148 pmap_clear_ptes(m, PG_RW);
3156 * pmap_ts_referenced:
3158 * Return a count of reference bits for a page, clearing those bits.
3159 * It is not necessary for every reference bit to be cleared, but it
3160 * is necessary that 0 only be returned when there are truly no
3161 * reference bits set.
3163 * XXX: The exact number of bits to check and clear is a matter that
3164 * should be tested and standardized at some point in the future for
3165 * optimal aging of shared pages.
3168 pmap_ts_referenced(vm_page_t m)
3170 register pv_entry_t pv, pvf, pvn;
3176 if (m->flags & PG_FICTITIOUS)
3180 mtx_assert(&vm_page_queue_mtx, MA_OWNED);
3181 if ((pv = TAILQ_FIRST(&m->md.pv_list)) != NULL) {
3186 pvn = TAILQ_NEXT(pv, pv_list);
3188 TAILQ_REMOVE(&m->md.pv_list, pv, pv_list);
3190 TAILQ_INSERT_TAIL(&m->md.pv_list, pv, pv_list);
3194 pte = pmap_pte_quick(pmap, pv->pv_va);
3196 if (pte && ((v = pte_load(pte)) & PG_A) != 0) {
3197 atomic_clear_int((u_int *)pte, PG_A);
3198 pmap_invalidate_page(pmap, pv->pv_va);
3207 } while ((pv = pvn) != NULL && pv != pvf);
3215 * Clear the modify bits on the specified physical page.
3218 pmap_clear_modify(vm_page_t m)
3220 pmap_clear_ptes(m, PG_M);
3224 * pmap_clear_reference:
3226 * Clear the reference bit on the specified physical page.
3229 pmap_clear_reference(vm_page_t m)
3231 pmap_clear_ptes(m, PG_A);
3235 * Miscellaneous support routines follow
3239 * Map a set of physical memory pages into the kernel virtual
3240 * address space. Return a pointer to where it is mapped. This
3241 * routine is intended to be used for mapping device memory,
3245 pmap_mapdev(pa, size)
3249 vm_offset_t va, tmpva, offset;
3251 offset = pa & PAGE_MASK;
3252 size = roundup(offset + size, PAGE_SIZE);
3255 if (pa < KERNLOAD && pa + size <= KERNLOAD)
3258 va = kmem_alloc_nofault(kernel_map, size);
3260 panic("pmap_mapdev: Couldn't alloc kernel virtual memory");
3262 for (tmpva = va; size > 0; ) {
3263 pmap_kenter(tmpva, pa);
3268 pmap_invalidate_range(kernel_pmap, va, tmpva);
3269 return ((void *)(va + offset));
3273 pmap_unmapdev(va, size)
3277 vm_offset_t base, offset, tmpva;
3279 if (va >= KERNBASE && va + size <= KERNBASE + KERNLOAD)
3281 base = va & PG_FRAME;
3282 offset = va & PAGE_MASK;
3283 size = roundup(offset + size, PAGE_SIZE);
3284 for (tmpva = base; tmpva < (base + size); tmpva += PAGE_SIZE)
3285 pmap_kremove(tmpva);
3286 pmap_invalidate_range(kernel_pmap, va, tmpva);
3287 kmem_free(kernel_map, base, size);
3291 * perform the pmap work for mincore
3294 pmap_mincore(pmap, addr)
3298 pt_entry_t *ptep, pte;
3303 ptep = pmap_pte(pmap, addr);
3304 pte = (ptep != NULL) ? *ptep : 0;
3305 pmap_pte_release(ptep);
3311 val = MINCORE_INCORE;
3312 if ((pte & PG_MANAGED) == 0)
3315 pa = pte & PG_FRAME;
3317 m = PHYS_TO_VM_PAGE(pa);
3323 val |= MINCORE_MODIFIED|MINCORE_MODIFIED_OTHER;
3326 * Modified by someone else
3328 vm_page_lock_queues();
3329 if (m->dirty || pmap_is_modified(m))
3330 val |= MINCORE_MODIFIED_OTHER;
3331 vm_page_unlock_queues();
3337 val |= MINCORE_REFERENCED|MINCORE_REFERENCED_OTHER;
3340 * Referenced by someone else
3342 vm_page_lock_queues();
3343 if ((m->flags & PG_REFERENCED) ||
3344 pmap_ts_referenced(m)) {
3345 val |= MINCORE_REFERENCED_OTHER;
3346 vm_page_flag_set(m, PG_REFERENCED);
3348 vm_page_unlock_queues();
3355 pmap_activate(struct thread *td)
3357 pmap_t pmap, oldpmap;
3361 pmap = vmspace_pmap(td->td_proc->p_vmspace);
3362 oldpmap = PCPU_GET(curpmap);
3364 atomic_clear_int(&oldpmap->pm_active, PCPU_GET(cpumask));
3365 atomic_set_int(&pmap->pm_active, PCPU_GET(cpumask));
3367 oldpmap->pm_active &= ~1;
3368 pmap->pm_active |= 1;
3371 cr3 = vtophys(pmap->pm_pdpt);
3373 cr3 = vtophys(pmap->pm_pdir);
3376 * pmap_activate is for the current thread on the current cpu
3378 td->td_pcb->pcb_cr3 = cr3;
3380 PCPU_SET(curpmap, pmap);
3385 pmap_addr_hint(vm_object_t obj, vm_offset_t addr, vm_size_t size)
3388 if ((obj == NULL) || (size < NBPDR) || (obj->type != OBJT_DEVICE)) {
3392 addr = (addr + PDRMASK) & ~PDRMASK;
3397 #if defined(PMAP_DEBUG)
3398 pmap_pid_dump(int pid)
3405 sx_slock(&allproc_lock);
3406 LIST_FOREACH(p, &allproc, p_list) {
3407 if (p->p_pid != pid)
3413 pmap = vmspace_pmap(p->p_vmspace);
3414 for (i = 0; i < NPDEPTD; i++) {
3417 vm_offset_t base = i << PDRSHIFT;
3419 pde = &pmap->pm_pdir[i];
3420 if (pde && pmap_pde_v(pde)) {
3421 for (j = 0; j < NPTEPG; j++) {
3422 vm_offset_t va = base + (j << PAGE_SHIFT);
3423 if (va >= (vm_offset_t) VM_MIN_KERNEL_ADDRESS) {
3428 sx_sunlock(&allproc_lock);
3431 pte = pmap_pte(pmap, va);
3432 if (pte && pmap_pte_v(pte)) {
3436 m = PHYS_TO_VM_PAGE(pa);
3437 printf("va: 0x%x, pt: 0x%x, h: %d, w: %d, f: 0x%x",
3438 va, pa, m->hold_count, m->wire_count, m->flags);
3453 sx_sunlock(&allproc_lock);
3460 static void pads(pmap_t pm);
3461 void pmap_pvdump(vm_offset_t pa);
3463 /* print address space of pmap*/
3472 if (pm == kernel_pmap)
3474 for (i = 0; i < NPDEPTD; i++)
3476 for (j = 0; j < NPTEPG; j++) {
3477 va = (i << PDRSHIFT) + (j << PAGE_SHIFT);
3478 if (pm == kernel_pmap && va < KERNBASE)
3480 if (pm != kernel_pmap && va > UPT_MAX_ADDRESS)
3482 ptep = pmap_pte(pm, va);
3483 if (pmap_pte_v(ptep))
3484 printf("%x:%x ", va, *ptep);
3497 printf("pa %x", pa);
3498 m = PHYS_TO_VM_PAGE(pa);
3499 TAILQ_FOREACH(pv, &m->md.pv_list, pv_list) {
3501 printf(" -> pmap %p, va %x", (void *)pmap, pv->pv_va);